diff --git a/types/accounting/accounting-tests.ts b/types/accounting/accounting-tests.ts index a397c559eb..41150f7a37 100644 --- a/types/accounting/accounting-tests.ts +++ b/types/accounting/accounting-tests.ts @@ -3,6 +3,9 @@ // Default usage: accounting.formatMoney(12345678); // $12,345,678.00 +// Stringified usage: +accounting.formatMoney('$4394958309392.9401'); // $4,394,958,309,392.94 + // European formatting (custom symbol and separators), could also use options object as second param: accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99 diff --git a/types/accounting/index.d.ts b/types/accounting/index.d.ts index ef8991999f..9a990a6519 100644 --- a/types/accounting/index.d.ts +++ b/types/accounting/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for accounting.js 0.3 -// Project: http://josscrowcroft.github.io/accounting.js/ +// Type definitions for accounting.js 0.4 +// Project: http://openexchangerates.github.io/accounting.js/ // Definitions by: Sergey Gerasimov +// Christopher Eck // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace accounting { @@ -30,9 +31,9 @@ declare namespace accounting { } interface Static { - // format any number into currency - formatMoney(number: number, symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string; - formatMoney(number: number, options: CurrencySettings | CurrencySettings): string; + // format any number or stringified number into currency + formatMoney(number: number | string, symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string; + formatMoney(number: number | string, options: CurrencySettings | CurrencySettings): string; formatMoney(numbers: number[], symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string[]; formatMoney(numbers: number[], options: CurrencySettings | CurrencySettings): string[]; diff --git a/types/alt/index.d.ts b/types/alt/index.d.ts index f0ea3ba008..2d4c6e259f 100644 --- a/types/alt/index.d.ts +++ b/types/alt/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/goatslacker/alt // Definitions by: Michael Shearer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 /// @@ -141,7 +141,7 @@ declare module "alt/utils/chromeDebug" { declare module "alt/AltContainer" { - import React = require("react"); + import * as React from "react"; interface ContainerProps { store?:AltJS.AltStore; @@ -152,7 +152,7 @@ declare module "alt/AltContainer" { flux?:AltJS.Alt; transform?:(store:AltJS.AltStore, actions:any) => any; shouldComponentUpdate?:(props:any) => boolean; - component?:React.Component; + component?:React.Component; } type AltContainer = React.ReactElement; diff --git a/types/amqplib/index.d.ts b/types/amqplib/index.d.ts index a6e5aec204..45b5e6e3ca 100644 --- a/types/amqplib/index.d.ts +++ b/types/amqplib/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/squaremo/amqp.node // Definitions by: Michael Nahkies , Ab Reitsma , Nicolás Fantone // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/angular-block-ui/index.d.ts b/types/angular-block-ui/index.d.ts index bf311b04a1..7733bc72f7 100644 --- a/types/angular-block-ui/index.d.ts +++ b/types/angular-block-ui/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/McNull/angular-block-ui // Definitions by: Lasse Nørregaard , Stephan Classen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as angular from "angular"; diff --git a/types/angular-gridster/index.d.ts b/types/angular-gridster/index.d.ts index 272470bc6f..3d4fbbe799 100644 --- a/types/angular-gridster/index.d.ts +++ b/types/angular-gridster/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/ManifestWebDesign/angular-gridster // Definitions by: Joao Monteiro // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as angular from "angular"; diff --git a/types/angular-oauth2/index.d.ts b/types/angular-oauth2/index.d.ts index 23df762df1..1c5e3ac6ed 100644 --- a/types/angular-oauth2/index.d.ts +++ b/types/angular-oauth2/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/oauthjs/angular-oauth2 // Definitions by: Antério Vieira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as angular from 'angular'; diff --git a/types/angular/angular-tests.ts b/types/angular/angular-tests.ts index d77c18fa37..80b73c062a 100644 --- a/types/angular/angular-tests.ts +++ b/types/angular/angular-tests.ts @@ -337,6 +337,16 @@ namespace TestQ { let result: angular.IPromise<{a: number; b: string; }>; result = $q.all<{a: number; b: string; }>({a: promiseAny, b: promiseAny}); } + { + let result = $q.all({ num: $q.when(2), str: $q.when('test') }); + // TS should infer that num is a number and str is a string + result.then(r => (r.num * 2) + r.str.indexOf('s')); + } + { + let result = $q.all({ num: $q.when(2), str: 'test' }); + // TS should infer that num is a number and str is a string + result.then(r => (r.num * 2) + r.str.indexOf('s')); + } // $q.defer { @@ -367,8 +377,7 @@ namespace TestQ { let result: angular.IPromise; result = $q.resolve(tResult); result = $q.resolve(promiseTResult); - result = $q.resolve(Math.random() > 0.5 ? tResult : promiseTOther); - result = $q.resolve(Math.random() > 0.5 ? tResult : promiseTOther); + let result2: angular.IPromise = $q.resolve(Math.random() > 0.5 ? tResult : promiseTOther); } // $q.when @@ -378,7 +387,8 @@ namespace TestQ { } { let result: angular.IPromise; - let resultOther: angular.IPromise; + let other: angular.IPromise; + let resultOther: angular.IPromise; result = $q.when(tResult); result = $q.when(promiseTResult); @@ -388,20 +398,21 @@ namespace TestQ { result = $q.when(tValue, (result: TValue) => tResult, (any) => any, (any) => any); result = $q.when(promiseTValue, (result: TValue) => tResult); - result = resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => tOther); - result = resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => tOther, (any) => any); - result = resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => promiseTOther); - result = resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => promiseTOther, (any) => any); + resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => tOther); + resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => tOther); + resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => tOther, (any) => any); + resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => promiseTOther); + resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => promiseTOther, (any) => any); result = $q.when(tValue, (result: TValue) => promiseTResult); result = $q.when(tValue, (result: TValue) => promiseTResult, (any) => any); result = $q.when(tValue, (result: TValue) => promiseTResult, (any) => any, (any) => any); result = $q.when(promiseTValue, (result: TValue) => promiseTResult); - result = resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => tOther); - result = resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => tOther, (any) => any); - result = resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => promiseTOther); - result = resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => promiseTOther, (any) => any); + resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => tOther); + resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => tOther, (any) => any); + resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => promiseTOther); + resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => promiseTOther, (any) => any); } } @@ -547,7 +558,7 @@ namespace TestPromise { assertPromiseType(promise.then((result) => result, (any) => any, (any) => any)); assertPromiseType(promise.then((result) => result, (any) => reject, (any) => any)); - assertPromiseType(promise.then((result) => anyOf2(reject, result))); + assertPromiseType | TResult>(promise.then((result) => anyOf2(reject, result))); assertPromiseType(promise.then((result) => anyOf3(result, tresultPromise, reject))); assertPromiseType(promise.then( (result) => anyOf3(reject, result, tresultPromise), @@ -557,7 +568,7 @@ namespace TestPromise { assertPromiseType>(promise.then((result) => tresultHttpPromise)); assertPromiseType(promise.then((result) => result, (any) => tother)); - assertPromiseType(promise.then( + assertPromiseType | angular.IPromise | TOther | angular.IPromise>(promise.then( (result) => anyOf3(reject, result, totherPromise), (reason) => anyOf3(reject, tother, tresultPromise) )); @@ -588,7 +599,7 @@ namespace TestPromise { assertPromiseType(promise.catch((err) => err)); assertPromiseType(promise.catch((err) => any)); assertPromiseType(promise.catch((err) => tresult)); - assertPromiseType(promise.catch((err) => anyOf2(tresult, reject))); + assertPromiseType>(promise.catch((err) => anyOf2(tresult, reject))); assertPromiseType(promise.catch((err) => anyOf3(tresult, tresultPromise, reject))); assertPromiseType(promise.catch((err) => tresultPromise)); assertPromiseType>(promise.catch((err) => tresultHttpPromise)); diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index d0e2d978dc..fe78ba03ff 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -1029,8 +1029,7 @@ declare namespace angular { * * @param promises A hash of promises. */ - all(promises: { [id: string]: IPromise; }): IPromise<{ [id: string]: any; }>; - all(promises: { [id: string]: IPromise; }): IPromise; + all(promises: { [K in keyof T]: (IPromise | T[K]); }): IPromise; /** * Creates a Deferred object which represents a task which will finish in the future. */ @@ -1049,6 +1048,10 @@ declare namespace angular { * @param value Value or a promise */ resolve(value: IPromise|T): IPromise; + /** + * @deprecated Since TS 2.4, inference is stricter and no longer produces the desired type when T1 !== T2. + * To use resolve with two different types, pass a union type to the single-type-argument overload. + */ resolve(value: IPromise|T2): IPromise; /** * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. @@ -1846,6 +1849,10 @@ declare namespace angular { * different in Angular 1 there is no direct mapping and care should be taken when upgrading. */ $postLink?(): void; + + // IController implementations frequently do not implement any of its methods. + // A string indexer indicates to TypeScript not to issue a weak type error in this case. + [s: string]: any; } /** diff --git a/types/anydb-sql-migrations/index.d.ts b/types/anydb-sql-migrations/index.d.ts index 5db740c70f..ae922c37ae 100644 --- a/types/anydb-sql-migrations/index.d.ts +++ b/types/anydb-sql-migrations/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/spion/anydb-sql-migrations // Definitions by: Gorgi Kosev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import Promise = require('bluebird'); import { Column, Table, Transaction, AnydbSql } from 'anydb-sql'; diff --git a/types/aphrodite/aphrodite-tests.tsx b/types/aphrodite/aphrodite-tests.tsx index f3c51f899e..685a9a4283 100644 --- a/types/aphrodite/aphrodite-tests.tsx +++ b/types/aphrodite/aphrodite-tests.tsx @@ -39,7 +39,7 @@ const withFont = StyleSheet.create({ }); -class App extends React.Component<{}, {}> { +class App extends React.Component { render() { return
diff --git a/types/aphrodite/index.d.ts b/types/aphrodite/index.d.ts index 63eba46927..0e04b07af7 100644 --- a/types/aphrodite/index.d.ts +++ b/types/aphrodite/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/Khan/aphrodite // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 import * as React from "react"; diff --git a/types/asana/index.d.ts b/types/asana/index.d.ts index 364980b66c..ede3bc99f9 100644 --- a/types/asana/index.d.ts +++ b/types/asana/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/Asana/node-asana // Definitions by: Qubo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/askmethat-rating/askmethat-rating-tests.ts b/types/askmethat-rating/askmethat-rating-tests.ts new file mode 100644 index 0000000000..2f17ad0b62 --- /dev/null +++ b/types/askmethat-rating/askmethat-rating-tests.ts @@ -0,0 +1,15 @@ +import { AskmethatRating, AskmethatRatingSteps } from "askmethat-rating"; + +let options = { + backgroundColor: "#e5e500", + hoverColor: "#ffff66", + fontClass: "fa fa-star", + minRating: 1, + maxRating: 5, + readonly: false, + step: AskmethatRatingSteps["OnePerOneStep"], + inputName: "AskmethatRating" +}; + +let div = document.createElement("div"); +let amcRating = new AskmethatRating(div, 2 , options); diff --git a/types/askmethat-rating/index.d.ts b/types/askmethat-rating/index.d.ts new file mode 100644 index 0000000000..ff31f81747 --- /dev/null +++ b/types/askmethat-rating/index.d.ts @@ -0,0 +1,131 @@ +// Type definitions for askmethat-rating 0.3 +// Project: https://alexteixeira.github.io/Askmethat-Rating/ +// Definitions by: Alexandre Teixeira +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export enum AskmethatRatingSteps { + /** + * Step 0.1 per 0.1 + */ + DecimalStep = 0, + /** + * Step 0.5 per 0.5 + */ + HalfStep = 1, + /** + * Step 1 per 1 + */ + OnePerOneStep = 2, +} +export interface AskmethatRatingOptions { + hoverColor?: string; + /** + * Color when the rating is not hovered + */ + backgroundColor?: string; + /** + * Mininmum rating that the user can set + */ + minRating?: number; + /** + * Maximum rating that the plugin display + */ + maxRating?: number; + /** + * Class to display as rating (FontAwesome or Rating for exemple) + */ + fontClass: string; + /** + * Set the rating to readonly + */ + readonly: boolean; + /** + * The stepping for the rating + */ + step: AskmethatRatingSteps; + /** + * Input name (Default is AskmethatRating) + */ + inputName: string; +} +export class AskmethatRating { + private parentElement; + private pValue; + private styleSheet; + private changeEvent; + private ratingClick; + private mouseMove; + /** + * @function get the current value for the rating + */ + /** + * @function set a new value for the rating + * + * @param _value this is the new value you want to set to the rating + * @returns the current number + */ + value: number; + /** + * Default option base on @type IAskmethatRatingOptions + */ + private _defaultOptions; + /** + * @function get the default option for the rating + * + * @return options based on @type AskmethatRatingOptions + */ + readonly defaultOptions: any; + /** + * constructor with div element, default rating value & default options + * + * @param element This is the html container for the rating elements + * @param defaultValue Default value set when the plugin render the rating + * @param options Default option base on AskmethatRatingOptions type + */ + constructor(element: HTMLDivElement, defaultValue?: number, options?: any); + /** + * render a new rating, by default value is the minRating + * + * @param value this is the default value set when the plugin is rendered, by default IAskmethatRatingOptions.minRating + */ + render(value?: number): void; + /** + * @function when a rating is clicked + * @param {type} event : Event {event object} + */ + private onRatingClick(event?); + /** + * @function Calculate the value according to the step provided in options + * @param {Number} value:number the current value + * @return {Number} the new value according to step + */ + protected getValueAccordingToStep(value: number): number; + /** + * @function mouse event enter in rating + * @param {type} event?: Event {event} + */ + private onMouseMove(event?); + /** + * @function mouse out event in rating + * @param {type} event?: Event {event} + */ + private onMouseLeave(event?); + /** + * @function set or unset the active class and color + * @param {HTMLSpanElement} current : current span element + * @param {number} current : value needed for the if + */ + protected setOrUnsetActive(value: number): void; + /** + * Check if disabled attribute is added or removed from the input + * Update readonly status if needed for the rating + */ + private mutationEvent(); + /** + * @function static method to retrieve with identifier the value + * @param {string} identifier: string container identifier + * @return {number} current rating + */ + static value(identifier: string): number; +} diff --git a/types/askmethat-rating/tsconfig.json b/types/askmethat-rating/tsconfig.json new file mode 100644 index 0000000000..fd5ef4ae50 --- /dev/null +++ b/types/askmethat-rating/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "askmethat-rating-tests.ts" + ] +} diff --git a/types/askmethat-rating/tslint.json b/types/askmethat-rating/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/askmethat-rating/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/assert-equal-jsx/index.d.ts b/types/assert-equal-jsx/index.d.ts index 5deb9ede36..f571020ef8 100644 --- a/types/assert-equal-jsx/index.d.ts +++ b/types/assert-equal-jsx/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/thejameskyle/assert-equal-jsx // Definitions by: Josh Toft // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import * as React from 'react'; diff --git a/types/audiosprite/audiosprite-tests.ts b/types/audiosprite/audiosprite-tests.ts new file mode 100644 index 0000000000..a3f400d454 --- /dev/null +++ b/types/audiosprite/audiosprite-tests.ts @@ -0,0 +1,26 @@ +import * as audiosprite from 'audiosprite'; + +const files = ['file1.mp3', 'file2.mp3']; +const opts = {output: 'result'}; + +audiosprite(files, opts, (err, obj) => { + if (err) { + return err; + } + + return JSON.stringify(obj, null, 2); +}); + +audiosprite(files, { + path: "aaa", + format: "howler", + export: "ogg,mp3", + minlength: 9999, + vbr: 9, + 'vbr:vorbis': 10, + logger: { + debug(a) { + } + } +}, (err, obj) => { +}); diff --git a/types/audiosprite/index.d.ts b/types/audiosprite/index.d.ts new file mode 100644 index 0000000000..c1738386d6 --- /dev/null +++ b/types/audiosprite/index.d.ts @@ -0,0 +1,55 @@ +// Type definitions for audiosprite 0.6 +// Project: https://github.com/tonistiigi/audiosprite +// Definitions by: Gyusun Yeom +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export as namespace audiosprite; +export = audiosprite; + +declare function audiosprite(files: string[], callback: (error: Error, obj: audiosprite.Result) => void): void; +declare function audiosprite(files: string[], option: audiosprite.Option, callback: (error: Error, obj: audiosprite.Result) => void): void; + +declare namespace audiosprite { + type ExportType = "jukebox" | "howler" | "createjs" | null; + type LogLevel = "debug" | "info" | "notice" | "warning" | "error"; + type VBR = -1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + type VBR_Vorbis = VBR | 10; + type Channels = 1 | 2; + interface Option { + output?: string; + path?: string; + export?: string; + format?: ExportType; + log?: LogLevel; + autoplay?: string | null; + loop?: string[]; + silence?: number; + gap?: number; + minlength?: number; + bitrate?: number; + vbr?: VBR; + 'vbr:vorbis'?: VBR_Vorbis; + samplerate?: number; + channels?: Channels; + rawparts?: string; + logger?: Logger; + } + + interface Logger { + debug?(...log: any[]): void; + info?(...log: any[]): void; + log?(...log: any[]): void; + } + + interface Result { + resources: string[]; + spritemap: { + [key: string]: { + start: number; + end: number; + loop: boolean; + } + }; + autoplay?: string; + } +} diff --git a/types/audiosprite/tsconfig.json b/types/audiosprite/tsconfig.json new file mode 100644 index 0000000000..7348d046e8 --- /dev/null +++ b/types/audiosprite/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "audiosprite-tests.ts" + ] +} diff --git a/types/audiosprite/tslint.json b/types/audiosprite/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/audiosprite/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/auth0-js/index.d.ts b/types/auth0-js/index.d.ts index e44092a9c8..4e6afded1d 100644 --- a/types/auth0-js/index.d.ts +++ b/types/auth0-js/index.d.ts @@ -650,8 +650,9 @@ interface RenewAuthOptions { interface AuthorizeOptions { domain?: string; clientID?: string; - redirectUri: string; - responseType: string; + connection?:string; + redirectUri?: string; + responseType?: string; responseMode?: string; state?: string; nonce?: string; diff --git a/types/auth0/auth0-tests.ts b/types/auth0/auth0-tests.ts index 24a4aad87d..b84e92e223 100644 --- a/types/auth0/auth0-tests.ts +++ b/types/auth0/auth0-tests.ts @@ -28,6 +28,42 @@ management // Handle the error. }); +// Using a callback. +management.getUser({id: 'user_id'},(err: Error, user: auth0.User) => { + if (err) { + // Handle error. + } + console.log(user); +}); + +// Using a Promise. +management + .getUser({id: 'user_id'}) + .then((user) => { + console.log(user); + }) + .catch((err) => { + // Handle the error. + }); + +// Using a callback. +management.deleteUser({id: 'user_id'},(err: Error) => { + if (err) { + // Handle error. + } + console.log('deleted'); +}); + +// Using a Promise. +management + .deleteUser({id: 'user_id'}) + .then(() => { + console.log('deleted'); + }) + .catch((err) => { + // Handle the error. + }); + management .createUser({ connection: 'My-Connection', diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index a8a6242bb4..3025b8d380 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for auth0 2.4 +// Type definitions for auth0 3.0 // Project: https://github.com/auth0/node-auth0 -// Definitions by: Wilson Hobbs , Seth Westphal +// Definitions by: Wilson Hobbs , Seth Westphal , Amiram Korach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as Promise from 'bluebird'; @@ -14,16 +15,29 @@ export interface UserMetadata { } export interface AppMetadata { } export interface UserData { - connection: string; email?: string; username?: string; + email_verified?: boolean; + verify_email?: boolean; password?: string; phone_number?: string; + phone_verified?: boolean, user_metadata?: UserMetadata; - email_verified?: boolean; app_metadata?: AppMetadata; } +export interface CreateUserData extends UserData { + connection: string; +} + +export interface UpdateUserData extends UserData { + connection?: string; + blocked?: boolean; + verify_phone_number?: boolean, + verify_password?: boolean, + client_id?: string +} + export interface GetUsersData { per_page?: number; page?: number; @@ -67,10 +81,6 @@ export interface Identity { isSocial: boolean; } -export interface UpdateUserParameters { - id: string; -} - export interface AuthenticationClientOptions { clientId?: string; domain: string; @@ -134,17 +144,47 @@ export interface ClientParams { client_id: string; } +export type DeleteDeleteMultifactorParamsProvider = 'duo' | 'google-authenticator'; + export interface DeleteMultifactorParams { id: string; - provider: string; + provider: DeleteDeleteMultifactorParamsProvider; } -export interface LinkAccountsParams { +export type UnlinkAccountsParamsProvider = 'ad' | 'adfs' | 'amazon' | 'dropbox' | 'bitbucket' | 'aol' | 'auth0-adldap' | + 'auth0-oidc' | 'auth0' | 'baidu' | 'bitly' | 'box' | 'custom' | 'dwolla' | 'email' | 'evernote-sandbox' | 'evernote' | + 'exact' | 'facebook' | 'fitbit' | 'flickr' | 'github' | 'google-apps' | 'google-oauth2' | 'guardian' | 'instagram' | + 'ip' | 'linkedin' | 'miicard' | 'oauth1' | 'oauth2' | 'office365' | 'paypal' | 'paypal-sandbox' | 'pingfederate' | + 'planningcenter' | 'renren' | 'salesforce-community' | 'salesforce-sandbox' | 'salesforce' | 'samlp' | 'sharepoint' | + 'shopify' | 'sms' | 'soundcloud' | 'thecity-sandbox' | 'thecity' | 'thirtysevensignals' | 'twitter' | 'untappd' | + 'vkontakte' | 'waad' | 'weibo' | 'windowslive' | 'wordpress' | 'yahoo' | 'yammer' | 'yandex'; + +export interface UnlinkAccountsParams { id: string; - provider: string; + provider: UnlinkAccountsParamsProvider; user_id: string; } +export interface UnlinkAccountsResponseProfile { + email?: string; + email_verified?: boolean; + name?: string; + username?: string; + given_name?: string; + phone_number?: string; + phone_verified?: boolean; + family_name?: string; +} + +export interface UnlinkAccountsResponse { + connection: string; + user_id: string; + provider: string; + isSocial?: boolean; + access_token?: string; + profileData?: UnlinkAccountsResponseProfile +} + export interface LinkAccountsData { user_id: string; connection_id: string; @@ -307,32 +347,33 @@ export class ManagementClient { getUsers(params?: GetUsersData): Promise; getUsers(params?: GetUsersData, cb?: (err: Error, users: User[]) => void): void; - getUser(params?: ObjectWithId): Promise; - getUser(params?: ObjectWithId, cb?: (err: Error, users: User[]) => void): void; + getUser(params: ObjectWithId): Promise; + getUser(params: ObjectWithId, cb?: (err: Error, user: User) => void): void; - createUser(data: UserData): Promise; - createUser(data: UserData, cb: (err: Error, data: User) => void): void; + createUser(data: CreateUserData): Promise; + createUser(data: CreateUserData, cb: (err: Error, data: User) => void): void; - updateUser(params: UpdateUserParameters, data: User): Promise; - updateUser(params: UpdateUserParameters, data: User, cb: (err: Error, data: User) => void): void; + updateUser(params: ObjectWithId, data: UpdateUserData): Promise; + updateUser(params: ObjectWithId, data: UpdateUserData, cb: (err: Error, data: User) => void): void; - updateUserMetadata(params: UpdateUserParameters, data: UserMetadata): Promise; - updateUserMetadata(params: UpdateUserParameters, data: UserMetadata, cb: (err: Error, data: User) => void): void; + updateUserMetadata(params: ObjectWithId, data: UserMetadata): Promise; + updateUserMetadata(params: ObjectWithId, data: UserMetadata, cb: (err: Error, data: User) => void): void; + // Should be removed from auth0 also. Doesn't exist in api. deleteAllUsers(): Promise; deleteAllUsers(cb: (err: Error, data: any) => void): void; - deleteUser(params?: ObjectWithId): Promise; - deleteUser(params?: ObjectWithId, cb?: (err: Error, users: User[]) => void): void; + deleteUser(params: ObjectWithId): Promise; + deleteUser(params: ObjectWithId, cb?: (err: Error) => void): void; - updateAppMetadata(params: UpdateUserParameters, data: AppMetadata): Promise; - updateAppMetadata(params: UpdateUserParameters, data: AppMetadata, cb: (err: Error, data: User) => void): void; + updateAppMetadata(params: ObjectWithId, data: AppMetadata): Promise; + updateAppMetadata(params: ObjectWithId, data: AppMetadata, cb: (err: Error, data: User) => void): void; - deleteUserMultifactor(params: DeleteMultifactorParams): Promise; - deleteUserMultifactor(params: DeleteMultifactorParams, cb: (err: Error, data: any) => void): void; + deleteUserMultifactor(params: DeleteMultifactorParams): Promise; + deleteUserMultifactor(params: DeleteMultifactorParams, cb: (err: Error) => void): void; - unlinkUsers(params: LinkAccountsParams): Promise; - unlinkUsers(params: LinkAccountsParams, cb: (err: Error, data: any) => void): void; + unlinkUsers(params: UnlinkAccountsParams): Promise; + unlinkUsers(params: UnlinkAccountsParams, cb: (err: Error, data: UnlinkAccountsResponse) => void): void; linkUsers(params: ObjectWithId, data: LinkAccountsData): Promise; linkUsers(params: ObjectWithId, data: LinkAccountsData, cb: (err: Error, data: any) => void): void; diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index 55a3d6b99f..7f8b8fabdd 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -61,6 +61,8 @@ var S3CreateEvent: AWSLambda.S3CreateEvent = { ] }; var cognitoUserPoolEvent: AWSLambda.CognitoUserPoolEvent; +var cloudformationCustomResourceEvent: AWSLambda.CloudFormationCustomResourceEvent; +var cloudformationCustomResourceResponse: AWSLambda.CloudFormationCustomResourceResponse; /* API Gateway Event */ str = apiGwEvt.body; @@ -213,6 +215,33 @@ str = cognitoUserPoolEvent.response.privateChallengeParameters["answer"]; str = cognitoUserPoolEvent.response.challengeMetaData; b = cognitoUserPoolEvent.response.answerCorrect; +// CloudFormation Custom Resource +switch (cloudformationCustomResourceEvent.RequestType) { + case "Create": + str = cloudformationCustomResourceEvent.LogicalResourceId; + str = cloudformationCustomResourceEvent.RequestId; + anyObj = cloudformationCustomResourceEvent.ResourceProperties; + str = cloudformationCustomResourceEvent.ResourceProperties.ServiceToken; + str = cloudformationCustomResourceEvent.ResourceType; + str = cloudformationCustomResourceEvent.ResponseURL; + str = cloudformationCustomResourceEvent.ServiceToken; + str = cloudformationCustomResourceEvent.StackId; + break; + case "Update": + anyObj = cloudformationCustomResourceEvent.OldResourceProperties; + break; + case "Delete": + str = cloudformationCustomResourceEvent.PhysicalResourceId; + break; +} +anyObj = cloudformationCustomResourceResponse.Data; +str = cloudformationCustomResourceResponse.LogicalResourceId; +str = cloudformationCustomResourceResponse.PhysicalResourceId; +str = cloudformationCustomResourceResponse.Reason; +str = cloudformationCustomResourceResponse.RequestId; +str = cloudformationCustomResourceResponse.StackId; +str = cloudformationCustomResourceResponse.Status; + /* Context */ b = context.callbackWaitsForEmptyEventLoop; str = context.functionName; diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index 2980555a6d..df8effb82b 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -168,6 +168,64 @@ interface CognitoUserPoolEvent { }; } +/** + * CloudFormation Custom Resource event and response + * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/crpg-ref.html + */ +type CloudFormationCustomResourceEventCommon = { + ServiceToken: string; + ResponseURL: string; + StackId: string; + RequestId: string; + LogicalResourceId: string; + ResourceType: string; + ResourceProperties: { + ServiceToken: string; + [Key: string]: any; + } +} + +type CloudFormationCustomResourceCreateEvent = CloudFormationCustomResourceEventCommon & { + RequestType: "Create"; +} + +type CloudFormationCustomResourceUpdateEvent = CloudFormationCustomResourceEventCommon & { + RequestType: "Update"; + PhysicalResourceId: string; + OldResourceProperties: { + [Key: string]: any; + }; +} + +type CloudFormationCustomResourceDeleteEvent = CloudFormationCustomResourceEventCommon & { + RequestType: "Delete"; + PhysicalResourceId: string; +} + +export type CloudFormationCustomResourceEvent = CloudFormationCustomResourceCreateEvent | CloudFormationCustomResourceUpdateEvent | CloudFormationCustomResourceDeleteEvent; + +type CloudFormationCustomResourceResponseCommon = { + PhysicalResourceId: string; + StackId: string; + RequestId: string; + LogicalResourceId: string; + Data?: { + [Key: string]: any; + } +} + +type CloudFormationCustomResourceSuccessResponse = CloudFormationCustomResourceResponseCommon & { + Status: "SUCCESS"; + Reason?: string; +} + +type CloudFormationCustomResourceFailedResponse = CloudFormationCustomResourceResponseCommon & { + Status: "FAILED"; + Reason: string; +} + +export type CloudFormationCustomResourceResponse = CloudFormationCustomResourceSuccessResponse | CloudFormationCustomResourceFailedResponse; + // Context // http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html interface Context { diff --git a/types/baidumap-web-sdk/baidumap-web-sdk-tests.ts b/types/baidumap-web-sdk/baidumap-web-sdk-tests.ts index 0a4052b147..cc525509c6 100644 --- a/types/baidumap-web-sdk/baidumap-web-sdk-tests.ts +++ b/types/baidumap-web-sdk/baidumap-web-sdk-tests.ts @@ -1,24 +1,24 @@ -import "./index" -namespace BMapTests { - export class TestFixture { - //document: http://lbsyun.baidu.com/index.php?title=jspopular - public createMap(container: string | HTMLElement) { - navigator.geolocation.getCurrentPosition((position: Position) => { - let point = new BMap.Point(position.coords.longitude, position.coords.latitude); - let map = new BMap.Map(container); - map.centerAndZoom(point, 15); - }, console.log, { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }); - } - public addControl(map: BMap.Map) { - map.addControl(new BMap.ScaleControl({ anchor: BMAP_ANCHOR_TOP_LEFT })); - map.addControl(new BMap.NavigationControl()); - map.addControl(new BMap.MapTypeControl({ mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP] })); - map.addControl(new BMap.OverviewMapControl({ isOpen: true, anchor: BMAP_ANCHOR_BOTTOM_RIGHT })); - } - public addMarker(map: BMap.Map, point: BMap.Point) { - var marker = new BMap.Marker(point); - map.addOverlay(marker); - marker.setAnimation(BMAP_ANIMATION_BOUNCE); - } - } -} +import "./index" +namespace BMapTests { + export class TestFixture { + //document: http://lbsyun.baidu.com/index.php?title=jspopular + public createMap(container: string | HTMLElement) { + navigator.geolocation.getCurrentPosition((position: Position) => { + let point = new BMap.Point(position.coords.longitude, position.coords.latitude); + let map = new BMap.Map(container); + map.centerAndZoom(point, 15); + }, console.log, { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }); + } + public addControl(map: BMap.Map) { + map.addControl(new BMap.ScaleControl({ anchor: BMAP_ANCHOR_TOP_LEFT })); + map.addControl(new BMap.NavigationControl()); + map.addControl(new BMap.MapTypeControl({ mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP] })); + map.addControl(new BMap.OverviewMapControl({ isOpen: true, anchor: BMAP_ANCHOR_BOTTOM_RIGHT })); + } + public addMarker(map: BMap.Map, point: BMap.Point) { + var marker = new BMap.Marker(point); + map.addOverlay(marker); + marker.setAnimation(BMAP_ANIMATION_BOUNCE); + } + } +} diff --git a/types/baidumap-web-sdk/baidumap.base.d.ts b/types/baidumap-web-sdk/baidumap.base.d.ts index 4bea8ad872..9dc07a9377 100644 --- a/types/baidumap-web-sdk/baidumap.base.d.ts +++ b/types/baidumap-web-sdk/baidumap.base.d.ts @@ -1,56 +1,56 @@ -// Type definitions for BaiduMap v2.0 -// Project: http://lbsyun.baidu.com/index.php?title=jspopular -// Definitions by: Codemonk -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/* ***************************************************************************** -Copyright [Codemonk] [Codemonk@live.cn] - -This project is licensed under the MIT license. -Copyrights are respective of each contributor listed at the beginning of each definition file. - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -***************************************************************************** */ - -declare namespace BMap { - class Point { - constructor (lng: number, lat: number) - lng: number - lat: number - equals(other: Point): boolean - } - class Pixel { - constructor (x: number, y: number) - x: number - y: number - equals(other: Pixel): boolean - } - class Size { - constructor (width: number, height: number) - width: number - height: number - equals(other: Size): boolean - } - class Bounds { - constructor (minX: number, minY: number, maxX: number, maxY: number) - constructor (sw: Point, ne: Point) - minX: number - minY: number - maxX: number - maxY: number - equals(other: Bounds): boolean - containsPoint(point: Point): boolean - containsBounds(bounds: Bounds): boolean - intersects(other: Bounds): boolean - extend(point: Point): void - getCenter(): Point - isEmpty(): boolean - getSouthWest(): Point - getNorthEast(): Point - toSpan(): Point - } +// Type definitions for BaiduMap v2.0 +// Project: http://lbsyun.baidu.com/index.php?title=jspopular +// Definitions by: Codemonk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/* ***************************************************************************** +Copyright [Codemonk] [Codemonk@live.cn] + +This project is licensed under the MIT license. +Copyrights are respective of each contributor listed at the beginning of each definition file. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************** */ + +declare namespace BMap { + class Point { + constructor (lng: number, lat: number) + lng: number + lat: number + equals(other: Point): boolean + } + class Pixel { + constructor (x: number, y: number) + x: number + y: number + equals(other: Pixel): boolean + } + class Size { + constructor (width: number, height: number) + width: number + height: number + equals(other: Size): boolean + } + class Bounds { + constructor (minX: number, minY: number, maxX: number, maxY: number) + constructor (sw: Point, ne: Point) + minX: number + minY: number + maxX: number + maxY: number + equals(other: Bounds): boolean + containsPoint(point: Point): boolean + containsBounds(bounds: Bounds): boolean + intersects(other: Bounds): boolean + extend(point: Point): void + getCenter(): Point + isEmpty(): boolean + getSouthWest(): Point + getNorthEast(): Point + toSpan(): Point + } } \ No newline at end of file diff --git a/types/baidumap-web-sdk/baidumap.control.d.ts b/types/baidumap-web-sdk/baidumap.control.d.ts index 2eb4344dc9..6e3fb771be 100644 --- a/types/baidumap-web-sdk/baidumap.control.d.ts +++ b/types/baidumap-web-sdk/baidumap.control.d.ts @@ -1,132 +1,132 @@ -// Type definitions for BaiduMap v2.0 -// Project: http://lbsyun.baidu.com/index.php?title=jspopular -// Definitions by: Codemonk -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/* ***************************************************************************** -Copyright [Codemonk] [Codemonk@live.cn] - -This project is licensed under the MIT license. -Copyrights are respective of each contributor listed at the beginning of each definition file. - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -***************************************************************************** */ - -/// -/// -/// -declare namespace BMap { - class Control { - constructor() - defaultAnchor: ControlAnchor - defaultOffset: Size - initialize(map: Map): HTMLElement - setAnchor(anchor: ControlAnchor): void - getAnchor(): ControlAnchor - setOffset(offset: Size): void - getOffset(): Size - show(): void - hide(): void - isVisible(): boolean - } - interface NavigationControlOptions { - anchor?: ControlAnchor - offset?: Size - type?: NavigationControlType - showZoomInfo?: boolean - enableGeolocation?: boolean - } - interface ScaleControlOptions { - anchor?: ControlAnchor - offset?: Size - } - interface CopyrightControlOptions { - anchor?: ControlAnchor - offset?: Size - } - type ControlAnchor = number - class OverviewMapControl extends Control { - constructor(opts: OverviewMapControlOptions) - changeView(): void - setSize(size: Size): void - getSize(): Size - onviewchanged: (event: { type: string, target: any, isOpen: boolean }) => void - onviewchanging: (event: { type: string, target: any }) => void - } - type LengthUnit = string - class MapTypeControl extends Control { - constructor(opts?: MapTypeControlOptions) - } - class NavigationControl extends Control { - constructor(opts?: NavigationControlOptions) - getType(): NavigationControlOptions - setType(type: NavigationControlType): void - } - interface OverviewMapControlOptions { - anchor?: ControlAnchor - offset?: Size - size?: Size - isOpen?: boolean - } - class CopyrightControl extends Control { - constructor(opts?: CopyrightControlOptions) - addCopyright(copyright: Copyright): void - removeCopyright(id: number): void - getCopyright(id: number): Copyright - getCopyrightCollection(): Copyright[] - } - interface MapTypeControlOptions { - type?: MapTypeControlType, - mapTypes?: MapType[] - } - type NavigationControlType = number - class ScaleControl extends Control { - constructor(opts?: ScaleControlOptions) - getUnit(): LengthUnit - setUnit(unit: LengthUnit): void - } - interface Copyright { - id?: number - content?: string - bounds?: Bounds - } - type MapTypeControlType = number - class GeolocationControl extends Control { - constructor(opts?: GeolocationControlOptions) - } - interface GeolocationControlOptions { - anchor?: ControlAnchor - offset?: Size - showAddressBar?: boolean - enableAutoLocation?: boolean - locationIcon?: Icon - } - type StatusCode = number - class PanoramaControl extends Control { - constructor() - } -} -declare const BMAP_UNIT_METRIC: BMap.LengthUnit -declare const BMAP_UNIT_IMPERIAL: BMap.LengthUnit - -declare const BMAP_ANCHOR_TOP_LEFT: BMap.ControlAnchor -declare const BMAP_ANCHOR_TOP_RIGHT: BMap.ControlAnchor -declare const BMAP_ANCHOR_BOTTOM_LEFT: BMap.ControlAnchor -declare const BMAP_ANCHOR_BOTTOM_RIGHT: BMap.ControlAnchor - -declare const BMAP_NAVIGATION_CONTROL_LARGE: BMap.NavigationControlType -declare const BMAP_NAVIGATION_CONTROL_SMALL: BMap.NavigationControlType -declare const BMAP_NAVIGATION_CONTROL_PAN: BMap.NavigationControlType -declare const BMAP_NAVIGATION_CONTROL_ZOOM: BMap.NavigationControlType - -declare const BMAP_MAPTYPE_CONTROL_HORIZONTAL: BMap.MapTypeControlType -declare const BMAP_MAPTYPE_CONTROL_DROPDOWN: BMap.MapTypeControlType -declare const BMAP_MAPTYPE_CONTROL_MAP: BMap.MapTypeControlType - -declare const BMAP_STATUS_PERMISSION_DENIED: BMap.StatusCode -declare const BMAP_STATUS_SERVICE_UNAVAILABLE: BMap.StatusCode +// Type definitions for BaiduMap v2.0 +// Project: http://lbsyun.baidu.com/index.php?title=jspopular +// Definitions by: Codemonk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/* ***************************************************************************** +Copyright [Codemonk] [Codemonk@live.cn] + +This project is licensed under the MIT license. +Copyrights are respective of each contributor listed at the beginning of each definition file. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************** */ + +/// +/// +/// +declare namespace BMap { + class Control { + constructor() + defaultAnchor: ControlAnchor + defaultOffset: Size + initialize(map: Map): HTMLElement + setAnchor(anchor: ControlAnchor): void + getAnchor(): ControlAnchor + setOffset(offset: Size): void + getOffset(): Size + show(): void + hide(): void + isVisible(): boolean + } + interface NavigationControlOptions { + anchor?: ControlAnchor + offset?: Size + type?: NavigationControlType + showZoomInfo?: boolean + enableGeolocation?: boolean + } + interface ScaleControlOptions { + anchor?: ControlAnchor + offset?: Size + } + interface CopyrightControlOptions { + anchor?: ControlAnchor + offset?: Size + } + type ControlAnchor = number + class OverviewMapControl extends Control { + constructor(opts: OverviewMapControlOptions) + changeView(): void + setSize(size: Size): void + getSize(): Size + onviewchanged: (event: { type: string, target: any, isOpen: boolean }) => void + onviewchanging: (event: { type: string, target: any }) => void + } + type LengthUnit = string + class MapTypeControl extends Control { + constructor(opts?: MapTypeControlOptions) + } + class NavigationControl extends Control { + constructor(opts?: NavigationControlOptions) + getType(): NavigationControlOptions + setType(type: NavigationControlType): void + } + interface OverviewMapControlOptions { + anchor?: ControlAnchor + offset?: Size + size?: Size + isOpen?: boolean + } + class CopyrightControl extends Control { + constructor(opts?: CopyrightControlOptions) + addCopyright(copyright: Copyright): void + removeCopyright(id: number): void + getCopyright(id: number): Copyright + getCopyrightCollection(): Copyright[] + } + interface MapTypeControlOptions { + type?: MapTypeControlType, + mapTypes?: MapType[] + } + type NavigationControlType = number + class ScaleControl extends Control { + constructor(opts?: ScaleControlOptions) + getUnit(): LengthUnit + setUnit(unit: LengthUnit): void + } + interface Copyright { + id?: number + content?: string + bounds?: Bounds + } + type MapTypeControlType = number + class GeolocationControl extends Control { + constructor(opts?: GeolocationControlOptions) + } + interface GeolocationControlOptions { + anchor?: ControlAnchor + offset?: Size + showAddressBar?: boolean + enableAutoLocation?: boolean + locationIcon?: Icon + } + type StatusCode = number + class PanoramaControl extends Control { + constructor() + } +} +declare const BMAP_UNIT_METRIC: BMap.LengthUnit +declare const BMAP_UNIT_IMPERIAL: BMap.LengthUnit + +declare const BMAP_ANCHOR_TOP_LEFT: BMap.ControlAnchor +declare const BMAP_ANCHOR_TOP_RIGHT: BMap.ControlAnchor +declare const BMAP_ANCHOR_BOTTOM_LEFT: BMap.ControlAnchor +declare const BMAP_ANCHOR_BOTTOM_RIGHT: BMap.ControlAnchor + +declare const BMAP_NAVIGATION_CONTROL_LARGE: BMap.NavigationControlType +declare const BMAP_NAVIGATION_CONTROL_SMALL: BMap.NavigationControlType +declare const BMAP_NAVIGATION_CONTROL_PAN: BMap.NavigationControlType +declare const BMAP_NAVIGATION_CONTROL_ZOOM: BMap.NavigationControlType + +declare const BMAP_MAPTYPE_CONTROL_HORIZONTAL: BMap.MapTypeControlType +declare const BMAP_MAPTYPE_CONTROL_DROPDOWN: BMap.MapTypeControlType +declare const BMAP_MAPTYPE_CONTROL_MAP: BMap.MapTypeControlType + +declare const BMAP_STATUS_PERMISSION_DENIED: BMap.StatusCode +declare const BMAP_STATUS_SERVICE_UNAVAILABLE: BMap.StatusCode declare const BMAP_STATUS_TIMEOUT: BMap.StatusCode \ No newline at end of file diff --git a/types/baidumap-web-sdk/baidumap.core.d.ts b/types/baidumap-web-sdk/baidumap.core.d.ts index f736013589..24d1aed9f0 100644 --- a/types/baidumap-web-sdk/baidumap.core.d.ts +++ b/types/baidumap-web-sdk/baidumap.core.d.ts @@ -1,154 +1,154 @@ -// Type definitions for BaiduMap v2.0 -// Project: http://lbsyun.baidu.com/index.php?title=jspopular -// Definitions by: Codemonk -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/* ***************************************************************************** -Copyright [Codemonk] [Codemonk@live.cn] - -This project is licensed under the MIT license. -Copyrights are respective of each contributor listed at the beginning of each definition file. - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -***************************************************************************** */ - -/// -/// -/// -declare namespace BMap { - class Map { - constructor(container: string | HTMLElement, opts?: MapOptions) - enableDragging(): void - disableDragging(): void - enableScrollWheelZoom(): void - disableScrollWheelZoom(): void - enableDoubleClickZoom(): void - disableDoubleClickZoom(): void - enableKeyboard(): void - disableKeyboard(): void - enableInertialDragging(): void - disableInertialDragging(): void - enableContinuousZoom(): void - disableContinuousZoom(): void - enablePinchToZoom(): void - disablePinchToZoom(): void - enableAutoResize(): void - disableAutoResize(): void - setDefaultCursor(cursor: string): void - getDefaultCursor(): string - setDraggingCursor(cursor: string): void - getDraggingCursor(): string - setMinZoom(zoom: number): void - setMaxZoom(zoom: number): void - setMapStyle(mapStyle: MapStyle): void - setPanorama(pano: Panorama): void - disable3DBuilding(): void - getBounds(): Bounds - getCenter(): Point - getDistance(start: Point, end: Point): number - getMapType(): MapType - getSize(): Size - getViewport(view: Point[], viewportOptions?: ViewportOptions): Viewport - getZoom(): number - getPanorama(): Panorama - centerAndZoom(center: Point, zoom: number): void - panTo(center: Point, opts?: PanOptions): void - panBy(x: number, y: number, opts?: PanOptions): void - reset(): void - setCenter(center: Point | string): void - setCurrentCity(city: string): void - setMapType(mapType: MapType): void - setViewport(view: Point[], viewportOptions?: ViewportOptions): void - setZoom(zoom: number): void - highResolutionEnabled(): boolean - zoomIn(): void - zoomOut(): void - addHotspot(hotspot: Hotspot): void - removeHotspot(hotspot: Hotspot): void - clearHotspots(): void - addControl(control: Control): void - removeControl(control: Control): void - getContainer(): HTMLElement - addContextMenu(menu: ContextMenu): void - removeContextMenu(menu: ContextMenu): void - addOverlay(overlay: Overlay): void - removeOverlay(overlay: Overlay): void - clearOverlays(): void - openInfoWindow(infoWnd: InfoWindow, point: Point): void - closeInfoWindow(): void - pointToOverlayPixel(point: Point): Pixel - overlayPixelToPoint(pixel: Pixel): Point - getInfoWindow(): InfoWindow - getOverlays(): Overlay[] - getPanes(): MapPanes - addTileLayer(tileLayer: TileLayer): void - removeTileLayer(tilelayer: TileLayer): void - getTileLayer(mapType: string): TileLayer - pixelToPoint(pixel: Pixel): Point - pointToPixel(point: Point): Pixel - onclick: (event: { type: string, target: any, point: Point, pixel: Pixel, overlay: Overlay }) => void - ondblclick: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onrightclick: (event: { type: string, target: any, point: Point, pixel: Pixel, overlay: Overlay }) => void - onrightdblclick: (event: { type: string, target: any, point: Point, pixel: Pixel, overlay: Overlay }) => void - onmaptypechange: (event: { type: string, target: any }) => void - onmousemove: (event: { type: string, target: any, point: Point, pixel: Pixel, overlay: Overlay }) => void - onmouseover: (event: { type: string, target: any }) => void - onmouseout: (event: { type: string, target: any }) => void - onmovestart: (event: { type: string, target: any }) => void - onmoving: (event: { type: string, target: any }) => void - onmoveend: (event: { type: string, target: any }) => void - onzoomstart: (event: { type: string, target: any }) => void - onzoomend: (event: { type: string, target: any }) => void - onaddoverlay: (event: { type: string, target: any }) => void - onaddcontrol: (event: { type: string, target: any }) => void - onremovecontrol: (event: { type: string, target: any }) => void - onremoveoverlay: (event: { type: string, target: any }) => void - onclearoverlays: (event: { type: string, target: any }) => void - ondragstart: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - ondragging: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - ondragend: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onaddtilelayer: (event: { type: string, target: any }) => void - onremovetilelayer: (event: { type: string, target: any }) => void - onload: (event: { type: string, target: any, point: Point, pixel: Pixel, zoom: number }) => void - onresize: (event: { type: string, target: any, size: Size }) => void - onhotspotclick: (event: { type: string, target: any, spots: HotspotOptions }) => void - onhotspotover: (event: { type: string, target: any, spots: HotspotOptions }) => void - onhotspotout: (event: { type: string, target: any, spots: HotspotOptions }) => void - ontilesloaded: (event: { type: string, target: any }) => void - ontouchstart: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - ontouchmove: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - ontouchend: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onlongpress: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - } - interface PanOptions { - noAnimation?: boolean - } - interface MapOptions { - minZoom?: number - maxZoom?: number - mapType?: MapType - enableHighResolution?: boolean - enableAutoResize?: boolean - enableMapClick?: boolean - } - interface Viewport { - center: Point - zoom: number - } - interface ViewportOptions { - enableAnimation?: boolean - margins?: number[] - zoomFactor?: number - delay?: number - } - type APIVersion = number - interface MapStyle { - features: any[] - style: string - } -} +// Type definitions for BaiduMap v2.0 +// Project: http://lbsyun.baidu.com/index.php?title=jspopular +// Definitions by: Codemonk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/* ***************************************************************************** +Copyright [Codemonk] [Codemonk@live.cn] + +This project is licensed under the MIT license. +Copyrights are respective of each contributor listed at the beginning of each definition file. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************** */ + +/// +/// +/// +declare namespace BMap { + class Map { + constructor(container: string | HTMLElement, opts?: MapOptions) + enableDragging(): void + disableDragging(): void + enableScrollWheelZoom(): void + disableScrollWheelZoom(): void + enableDoubleClickZoom(): void + disableDoubleClickZoom(): void + enableKeyboard(): void + disableKeyboard(): void + enableInertialDragging(): void + disableInertialDragging(): void + enableContinuousZoom(): void + disableContinuousZoom(): void + enablePinchToZoom(): void + disablePinchToZoom(): void + enableAutoResize(): void + disableAutoResize(): void + setDefaultCursor(cursor: string): void + getDefaultCursor(): string + setDraggingCursor(cursor: string): void + getDraggingCursor(): string + setMinZoom(zoom: number): void + setMaxZoom(zoom: number): void + setMapStyle(mapStyle: MapStyle): void + setPanorama(pano: Panorama): void + disable3DBuilding(): void + getBounds(): Bounds + getCenter(): Point + getDistance(start: Point, end: Point): number + getMapType(): MapType + getSize(): Size + getViewport(view: Point[], viewportOptions?: ViewportOptions): Viewport + getZoom(): number + getPanorama(): Panorama + centerAndZoom(center: Point, zoom: number): void + panTo(center: Point, opts?: PanOptions): void + panBy(x: number, y: number, opts?: PanOptions): void + reset(): void + setCenter(center: Point | string): void + setCurrentCity(city: string): void + setMapType(mapType: MapType): void + setViewport(view: Point[], viewportOptions?: ViewportOptions): void + setZoom(zoom: number): void + highResolutionEnabled(): boolean + zoomIn(): void + zoomOut(): void + addHotspot(hotspot: Hotspot): void + removeHotspot(hotspot: Hotspot): void + clearHotspots(): void + addControl(control: Control): void + removeControl(control: Control): void + getContainer(): HTMLElement + addContextMenu(menu: ContextMenu): void + removeContextMenu(menu: ContextMenu): void + addOverlay(overlay: Overlay): void + removeOverlay(overlay: Overlay): void + clearOverlays(): void + openInfoWindow(infoWnd: InfoWindow, point: Point): void + closeInfoWindow(): void + pointToOverlayPixel(point: Point): Pixel + overlayPixelToPoint(pixel: Pixel): Point + getInfoWindow(): InfoWindow + getOverlays(): Overlay[] + getPanes(): MapPanes + addTileLayer(tileLayer: TileLayer): void + removeTileLayer(tilelayer: TileLayer): void + getTileLayer(mapType: string): TileLayer + pixelToPoint(pixel: Pixel): Point + pointToPixel(point: Point): Pixel + onclick: (event: { type: string, target: any, point: Point, pixel: Pixel, overlay: Overlay }) => void + ondblclick: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onrightclick: (event: { type: string, target: any, point: Point, pixel: Pixel, overlay: Overlay }) => void + onrightdblclick: (event: { type: string, target: any, point: Point, pixel: Pixel, overlay: Overlay }) => void + onmaptypechange: (event: { type: string, target: any }) => void + onmousemove: (event: { type: string, target: any, point: Point, pixel: Pixel, overlay: Overlay }) => void + onmouseover: (event: { type: string, target: any }) => void + onmouseout: (event: { type: string, target: any }) => void + onmovestart: (event: { type: string, target: any }) => void + onmoving: (event: { type: string, target: any }) => void + onmoveend: (event: { type: string, target: any }) => void + onzoomstart: (event: { type: string, target: any }) => void + onzoomend: (event: { type: string, target: any }) => void + onaddoverlay: (event: { type: string, target: any }) => void + onaddcontrol: (event: { type: string, target: any }) => void + onremovecontrol: (event: { type: string, target: any }) => void + onremoveoverlay: (event: { type: string, target: any }) => void + onclearoverlays: (event: { type: string, target: any }) => void + ondragstart: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + ondragging: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + ondragend: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onaddtilelayer: (event: { type: string, target: any }) => void + onremovetilelayer: (event: { type: string, target: any }) => void + onload: (event: { type: string, target: any, point: Point, pixel: Pixel, zoom: number }) => void + onresize: (event: { type: string, target: any, size: Size }) => void + onhotspotclick: (event: { type: string, target: any, spots: HotspotOptions }) => void + onhotspotover: (event: { type: string, target: any, spots: HotspotOptions }) => void + onhotspotout: (event: { type: string, target: any, spots: HotspotOptions }) => void + ontilesloaded: (event: { type: string, target: any }) => void + ontouchstart: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + ontouchmove: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + ontouchend: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onlongpress: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + } + interface PanOptions { + noAnimation?: boolean + } + interface MapOptions { + minZoom?: number + maxZoom?: number + mapType?: MapType + enableHighResolution?: boolean + enableAutoResize?: boolean + enableMapClick?: boolean + } + interface Viewport { + center: Point + zoom: number + } + interface ViewportOptions { + enableAnimation?: boolean + margins?: number[] + zoomFactor?: number + delay?: number + } + type APIVersion = number + interface MapStyle { + features: any[] + style: string + } +} declare const BMAP_API_VERSION: BMap.APIVersion \ No newline at end of file diff --git a/types/baidumap-web-sdk/baidumap.maplayer.d.ts b/types/baidumap-web-sdk/baidumap.maplayer.d.ts index 4ed2230bfb..244fff0c7b 100644 --- a/types/baidumap-web-sdk/baidumap.maplayer.d.ts +++ b/types/baidumap-web-sdk/baidumap.maplayer.d.ts @@ -1,82 +1,82 @@ -// Type definitions for BaiduMap v2.0 -// Project: http://lbsyun.baidu.com/index.php?title=jspopular -// Definitions by: Codemonk -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/* ***************************************************************************** -Copyright [Codemonk] [Codemonk@live.cn] - -This project is licensed under the MIT license. -Copyrights are respective of each contributor listed at the beginning of each definition file. - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -***************************************************************************** */ - -/// -/// -declare namespace BMap { - class TileLayer { - constructor(opts?: TileLayerOptions) - getTilesUrl(tileCoord: Pixel, zoom: number): string - getCopyright(): Copyright - isTransparentPng(): boolean - } - interface TileLayerOptions { - transparentPng?: boolean - tileUrlTemplate?: string - copyright?: Copyright - zIndex?: number - } - class TrafficLayer extends TileLayer { - constructor(opts?: TrafficLayerOptions) - } - interface TrafficLayerOptions { - predictDate?: PredictDate - } - interface PredictDate { - weekday: number - hour: number - } - class CustomLayer extends TileLayer { - constructor(opts: CustomLayerOptions) - onhotspotclick: (event: { type: string, target: any, content: any }) => void - } - interface Custompoi { - poiId: string - databoxId: string - title: string - address: string - phoneNumber: string - postcode: string - provinceCode: number - province: string - cityCode: number - city: string - districtCode: number - district: string - point: Point - tags: string[] - typeId: number - extendedData: any - } - class PanoramaCoverageLayer extends TileLayer { - constructor() - } - interface CustomLayerOptions { - databoxId?: string - geotableId?: string - q?: string - tags?: string - filter?: string - pointDensityType?: PointDensityType - } - type PointDensityType = number -} - -declare const BMAP_POINT_DENSITY_HIGH: BMap.PointDensityType -declare const BMAP_POINT_DENSITY_MEDIUM: BMap.PointDensityType +// Type definitions for BaiduMap v2.0 +// Project: http://lbsyun.baidu.com/index.php?title=jspopular +// Definitions by: Codemonk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/* ***************************************************************************** +Copyright [Codemonk] [Codemonk@live.cn] + +This project is licensed under the MIT license. +Copyrights are respective of each contributor listed at the beginning of each definition file. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************** */ + +/// +/// +declare namespace BMap { + class TileLayer { + constructor(opts?: TileLayerOptions) + getTilesUrl(tileCoord: Pixel, zoom: number): string + getCopyright(): Copyright + isTransparentPng(): boolean + } + interface TileLayerOptions { + transparentPng?: boolean + tileUrlTemplate?: string + copyright?: Copyright + zIndex?: number + } + class TrafficLayer extends TileLayer { + constructor(opts?: TrafficLayerOptions) + } + interface TrafficLayerOptions { + predictDate?: PredictDate + } + interface PredictDate { + weekday: number + hour: number + } + class CustomLayer extends TileLayer { + constructor(opts: CustomLayerOptions) + onhotspotclick: (event: { type: string, target: any, content: any }) => void + } + interface Custompoi { + poiId: string + databoxId: string + title: string + address: string + phoneNumber: string + postcode: string + provinceCode: number + province: string + cityCode: number + city: string + districtCode: number + district: string + point: Point + tags: string[] + typeId: number + extendedData: any + } + class PanoramaCoverageLayer extends TileLayer { + constructor() + } + interface CustomLayerOptions { + databoxId?: string + geotableId?: string + q?: string + tags?: string + filter?: string + pointDensityType?: PointDensityType + } + type PointDensityType = number +} + +declare const BMAP_POINT_DENSITY_HIGH: BMap.PointDensityType +declare const BMAP_POINT_DENSITY_MEDIUM: BMap.PointDensityType declare const BMAP_POINT_DENSITY_LOW: BMap.PointDensityType \ No newline at end of file diff --git a/types/baidumap-web-sdk/baidumap.maptype.d.ts b/types/baidumap-web-sdk/baidumap.maptype.d.ts index 804b200cb1..01056212bc 100644 --- a/types/baidumap-web-sdk/baidumap.maptype.d.ts +++ b/types/baidumap-web-sdk/baidumap.maptype.d.ts @@ -1,51 +1,51 @@ -// Type definitions for BaiduMap v2.0 -// Project: http://lbsyun.baidu.com/index.php?title=jspopular -// Definitions by: Codemonk -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/* ***************************************************************************** -Copyright [Codemonk] [Codemonk@live.cn] - -This project is licensed under the MIT license. -Copyrights are respective of each contributor listed at the beginning of each definition file. - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -***************************************************************************** */ - -/// -/// -declare namespace BMap { - class MapType { - constructor(name: string, layers: TileLayer | TileLayer[], opts?: MapTypeOptions) - getName(): string - getTileLayer(): TileLayer - getMinZoom(): number - getMaxZoom(): number - getProjection(): Projection - getTextColor(): string - getTips(): string - } - interface MapTypeOptions { - minZoom?: number - maxZoom?: number - errorImageUrl?: string - textColor?: number - tips?: string - } - interface Projection { - lngLatToPoint(lngLat: Point): Pixel - pointToLngLat(point: Pixel): Point - } - interface MercatorProjection extends Projection { - } - interface PerspectiveProjection extends Projection { - } -} -declare const BMAP_NORMAL_MAP: BMap.MapType -declare const BMAP_PERSPECTIVE_MAP: BMap.MapType -declare const BMAP_SATELLITE_MAP: BMap.MapType +// Type definitions for BaiduMap v2.0 +// Project: http://lbsyun.baidu.com/index.php?title=jspopular +// Definitions by: Codemonk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/* ***************************************************************************** +Copyright [Codemonk] [Codemonk@live.cn] + +This project is licensed under the MIT license. +Copyrights are respective of each contributor listed at the beginning of each definition file. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************** */ + +/// +/// +declare namespace BMap { + class MapType { + constructor(name: string, layers: TileLayer | TileLayer[], opts?: MapTypeOptions) + getName(): string + getTileLayer(): TileLayer + getMinZoom(): number + getMaxZoom(): number + getProjection(): Projection + getTextColor(): string + getTips(): string + } + interface MapTypeOptions { + minZoom?: number + maxZoom?: number + errorImageUrl?: string + textColor?: number + tips?: string + } + interface Projection { + lngLatToPoint(lngLat: Point): Pixel + pointToLngLat(point: Pixel): Point + } + interface MercatorProjection extends Projection { + } + interface PerspectiveProjection extends Projection { + } +} +declare const BMAP_NORMAL_MAP: BMap.MapType +declare const BMAP_PERSPECTIVE_MAP: BMap.MapType +declare const BMAP_SATELLITE_MAP: BMap.MapType declare const BMAP_HYBRID_MAP: BMap.MapType \ No newline at end of file diff --git a/types/baidumap-web-sdk/baidumap.overlay.d.ts b/types/baidumap-web-sdk/baidumap.overlay.d.ts index 295c30ff8a..d723ac5e48 100644 --- a/types/baidumap-web-sdk/baidumap.overlay.d.ts +++ b/types/baidumap-web-sdk/baidumap.overlay.d.ts @@ -1,438 +1,438 @@ -// Type definitions for BaiduMap v2.0 -// Project: http://lbsyun.baidu.com/index.php?title=jspopular -// Definitions by: Codemonk -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/* ***************************************************************************** -Copyright [Codemonk] [Codemonk@live.cn] - -This project is licensed under the MIT license. -Copyrights are respective of each contributor listed at the beginning of each definition file. - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -***************************************************************************** */ - -/// -/// -/// -declare namespace BMap { - interface Overlay { - initialize?(map: Map): HTMLElement - isVisible?(): boolean - draw?(): void - show?(): void - hide?(): void - } - type SymbolShapeType = number - interface PolylineOptions { - strokeColor?: string - strokeWeight?: number - strokeOpacity?: number - strokeStyle?: string - enableMassClear?: boolean - enableEditing?: boolean - enableClicking?: boolean - } - interface GroundOverlayOptions { - opacity?: number - imageURL?: string - displayOnMinLevel?: number - displayOnMaxLevel?: number - } - class Marker implements Overlay { - constructor(point: Point, opts?: MarkerOptions) - openInfoWindow(infoWnd: InfoWindow): void - closeInfoWindow(): void - setIcon(icon: Icon): void - getIcon(): Icon - setPosition(position: Point): void - getPosition(): Point - setOffset(offset: Size): void - getOffset(): Size - setLabel(label: Label): void - getLabel(): Label - setTitle(title: string): void - getTitle(): string - setTop(isTop: boolean): void - enableDragging(): void - disableDragging(): void - enableMassClear(): void - disableMassClear(): void - setZIndex(zIndex: number): void - getMap(): Map - addContextMenu(menu: ContextMenu): void - removeContextMenu(menu: ContextMenu): void - setAnimation(animation?: Animation): void - setRotation(rotation: number): void - getRotation(): number - setShadow(shadow: Icon): void - getShadow(): void - addEventListener(event: string, handler: Function): void - removeEventListener(event: string, handler: Function): void - onclick: (event: { type: string, target: any }) => void - ondblclick: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onmousedown: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onmouseup: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onmouseout: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onmouseover: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onremove: (event: { type: string, target: any }) => void - oninfowindowclose: (event: { type: string, target: any }) => void - oninfowindowopen: (event: { type: string, target: any }) => void - ondragstart: (event: { type: string, target: any }) => void - ondragging: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - ondragend: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onrightclick: (event: { type: string, target: any }) => void - } - interface SymbolOptions { - anchor?: Size - fillColor?: string - fillOpacity?: number - scale?: number - rotation?: number - strokeColor?: string - strokeOpacity?: number - strokeWeight?: number - } - class IconSequence { - constructor(symbol: Symbol, offset?: string, repeat?: string, fixedRotation?: boolean) - } - class PointCollection implements Overlay { - constructor(points: Point[], opts?: PointCollectionOption) - setPoints(points: Point[]): void - setStyles(styles: PointCollectionOption): void - clear(): void - onclick: (event: { type: string, target: any, point: Point }) => void - onmouseover: (event: { type: string, target: any, point: Point }) => void - onmouseout: (event: { type: string, target: any, point: Point }) => void - } - interface MarkerOptions { - offset?: Size - icon?: Icon - enableMassClear?: boolean - enableDragging?: boolean - enableClicking?: boolean - raiseOnDrag?: boolean - draggingCursor?: string - rotation?: number - shadow?: Icon - title?: string - } - class InfoWindow implements Overlay { - constructor(content: string | HTMLElement, opts?: InfoWindowOptions) - setWidth(width: number): void - setHeight(height: number): void - redraw(): void - setTitle(title: string | HTMLElement): void - getTitle(): string | HTMLElement - setContent(content: string | HTMLElement): void - getContent(): string | HTMLElement - getPosition(): Point - enableMaximize(): void - disableMaximize(): void - isOpen(): boolean - setMaxContent(content: string): void - maximize(): void - restore(): void - enableAutoPan(): void - disableAutoPan(): void - enableCloseOnClick(): void - disableCloseOnClick(): void - addEventListener(event: string, handler: Function): void - removeEventListener(event: string, handler: Function): void - onclose: (event: { type: string, target: any, point: Point }) => void - onopen: (event: { type: string, target: any, point: Point }) => void - onmaximize: (event: { type: string, target: any }) => void - onrestore: (event: { type: string, target: any }) => void - onclickclose: (event: { type: string, target: any }) => void - } - class Polygon implements Overlay { - constructor(points: Array, opts?: PolygonOptions) - setPath(path: Point[]): void - getPath(): Point[] - setStrokeColor(color: string): void - getStrokeColor(): string - setFillColor(color: string): void - getFillColor(): string - setStrokeOpacity(opacity: number): void - getStrokeOpacity(): number - setFillOpacity(opacity: number): void - getFillOpacity(): number - setStrokeWeight(weight: number): void - getStrokeWeight(): number - setStrokeStyle(style: string): void - getStrokeStyle(): string - getBounds(): Bounds - enableEditing(): void - disableEditing(): void - enableMassClear(): void - disableMassClear(): void - setPointAt(index: number, point: Point): void - setPositionAt(index: number, point: Point): void - getMap(): Map - addEventListener(event: string, handler: Function): void - removeEventListener(event: string, handler: Function): void - onclick: (event: { type: string, target: any }) => void - ondblclick: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onmousedown: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onmouseup: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onmouseout: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onmouseover: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onremove: (event: { type: string, target: any }) => void - onlineupdate: (event: { type: string, target: any }) => void - } - interface PointCollectionOption { - shape?: ShapeType - color?: string - size?: SizeType - } - type Animation = number - interface InfoWindowOptions { - width?: number - height?: number - maxWidth?: number - offset?: Size - title?: string - enableAutoPan?: boolean - enableCloseOnClick?: boolean - enableMessage?: boolean - message?: string - } - interface PolygonOptions { - strokeColor?: string - fillColor?: string - strokeWeight?: number - strokeOpacity?: number - fillOpacity?: number - strokeStyle?: number - enableMassClear?: boolean - enableEditing?: boolean - enableClicking?: boolean - } - type ShapeType = number - class Icon implements Overlay { - constructor(url: string, size: Size, opts?: IconOptions) - anchor: Size - size: Size - imageOffset: Size - imageSize: Size - imageUrl: Size - infoWindowAnchor: Size - printImageUrl: string - setImageUrl(imageUrl: string): void - setSize(size: Size): void - setImageSize(offset: Size): void - setAnchor(anchor: Size): void - setImageOffset(offset: Size): void - setInfoWindowAnchor(anchor: Size): void - setPrintImageUrl(url: string): void - } - class Label implements Overlay { - constructor(content: string, opts?: LabelOptions) - setStyle(styles: Object): void - setContent(content: string): void - setPosition(position: Point): void - getPosition(): Point - setOffset(offset: Size): void - getOffset(): Size - setTitle(title: string): void - getTitle(): string - enableMassClear(): void - disableMassClear(): void - setZIndex(zIndex: number): void - setPosition(position: Point): void - getMap(): Map - addEventListener(event: string, handler: Function): void - removeEventListener(event: string, handler: Function): void - onclick: (event: { type: string, target: any }) => void - ondblclick: (event: { type: string, target: any }) => void - onmousedown: (event: { type: string, target: any }) => void - onmouseup: (event: { type: string, target: any }) => void - onmouseout: (event: { type: string, target: any }) => void - onmouseover: (event: { type: string, target: any }) => void - onremove: (event: { type: string, target: any }) => void - onrightclick: (event: { type: string, target: any }) => void - } - class Circle implements Overlay { - constructor(center: Point, radius: number, opts?: CircleOptions) - setCenter(center: Point): void - getCenter(): Point - setRadius(radius: number): void - getRadius(): number - getBounds(): Bounds - setStrokeColor(color: string): void - getStrokeColor(): string - setFillColor(color: string): void - getFillColor(): string - setStrokeOpacity(opacity: number): void - getStrokeOpacity(): number - setFillOpacity(opacity: number): void - getFillOpacity(): number - setStrokeWeight(weight: number): void - getStrokeWeight(): number - setStrokeStyle(style: string): void - getStrokeStyle(): string - getBounds(): Bounds - enableEditing(): void - disableEditing(): void - enableMassClear(): void - disableMassClear(): void - getMap(): Map - addEventListener(event: string, handler: Function): void - removeEventListener(event: string, handler: Function): void - onclick: (event: { type: string, target: any }) => void - ondblclick: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onmousedown: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onmouseup: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onmouseout: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onmouseover: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onremove: (event: { type: string, target: any }) => void - onlineupdate: (event: { type: string, target: any }) => void - } - type SizeType = number - interface IconOptions { - anchor?: Size - imageOffset?: Size - infoWindowAnchor?: Size - printImageUrl?: string - } - interface LabelOptions { - offset?: Size - position?: Point - enableMassClear?: boolean - } - interface CircleOptions { - strokeColor?: string - fillColor?: string - strokeWeight?: number - strokeOpacity?: number - fillOpacity?: number - strokeStyle?: string - enableMassClear?: boolean - enableEditing?: boolean - enableClicking?: boolean - } - class Hotspot implements Overlay { - constructor(position: Point, opts?: HotspotOptions) - setPosition(position: Point): void - getPosition(): Point - setText(text: string): void - getText(): string - setUserData(data: any): void - getUserData(): any - } - class Symbol implements Overlay { - constructor(path: string | SymbolShapeType, opts?: SymbolOptions) - setPath(path: string | SymbolShapeType): void - setAnchor(anchor: Size): void - setRotation(rotation: number): void - setScale(scale: number): void - setStrokeWeight(strokeWeight: number): void - setStrokeColor(color: string): void - setStrokeOpacity(opacity: number): void - setFillOpacity(opacity: number): void - setFillColor(color: string): void - } - class Polyline implements Overlay { - constructor(points: Point[], opts?: PolylineOptions) - setPath(path: Point[]): void - getPath(): Point[] - setStrokeColor(color: string): void - getStrokeColor(): string - setFillColor(color: string): void - getFillColor(): string - setStrokeOpacity(opacity: number): void - getStrokeOpacity(): number - setFillOpacity(opacity: number): void - getFillOpacity(): number - setStrokeWeight(weight: number): void - getStrokeWeight(): number - setStrokeStyle(style: string): void - getStrokeStyle(): string - getBounds(): Bounds - enableEditing(): void - disableEditing(): void - enableMassClear(): void - disableMassClear(): void - setPointAt(index: number, point: Point): void - setPositionAt(index: number, point: Point): void - getMap(): Map - addEventListener(event: string, handler: Function): void - removeEventListener(event: string, handler: Function): void - onclick: (event: { type: string, target: any }) => void - ondblclick: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onmousedown: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onmouseup: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onmouseout: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onmouseover: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onremove: (event: { type: string, target: any }) => void - onlineupdate: (event: { type: string, target: any }) => void - } - class GroundOverlay implements Overlay { - constructor(bounds: Bounds, opts?: GroundOverlayOptions) - setBounds(bounds: Bounds): void - getBounds(): Bounds - setOpacity(opcity: number): void - getOpacity(): number - setImageURL(url: string): void - getImageURL(): string - setDisplayOnMinLevel(level: number): void - getDisplayOnMinLevel(): number - setDispalyOnMaxLevel(level: number): void - getDispalyOnMaxLevel(): number - onclick: (event: { type: string, target: any }) => void - ondblclick: (event: { type: string, target: any }) => void - } - interface HotspotOptions { - text?: string - offsets?: number[] - userData?: any - minZoom?: number - maxZoom?: number - } - interface MapPanes { - floatPane?: HTMLElement - markerMouseTarget?: HTMLElement - floatShadow?: HTMLElement - labelPane?: HTMLElement - markerPane?: HTMLElement - markerShadow?: HTMLElement - mapPane?: HTMLElement - } -} - -declare const BMap_Symbol_SHAPE_CIRCLE: BMap.SymbolShapeType -declare const BMap_Symbol_SHAPE_RECTANGLE: BMap.SymbolShapeType -declare const BMap_Symbol_SHAPE_RHOMBUS: BMap.SymbolShapeType -declare const BMap_Symbol_SHAPE_STAR: BMap.SymbolShapeType -declare const BMap_Symbol_SHAPE_BACKWARD_CLOSED_ARROW: BMap.SymbolShapeType -declare const BMap_Symbol_SHAPE_FORWARD_CLOSED_ARROW: BMap.SymbolShapeType -declare const BMap_Symbol_SHAPE_BACKWARD_OPEN_ARROW: BMap.SymbolShapeType -declare const BMap_Symbol_SHAPE_FORWARD_OPEN_ARROW: BMap.SymbolShapeType -declare const BMap_Symbol_SHAPE_POINT: BMap.SymbolShapeType -declare const BMap_Symbol_SHAPE_PLANE: BMap.SymbolShapeType -declare const BMap_Symbol_SHAPE_CAMERA: BMap.SymbolShapeType -declare const BMap_Symbol_SHAPE_WARNING: BMap.SymbolShapeType -declare const BMap_Symbol_SHAPE_SMILE: BMap.SymbolShapeType -declare const BMap_Symbol_SHAPE_CLOCK: BMap.SymbolShapeType - - -declare const BMAP_ANIMATION_DROP: BMap.Animation -declare const BMAP_ANIMATION_BOUNCE: BMap.Animation - -declare const BMAP_POINT_SHAPE_CIRCLE: BMap.ShapeType -declare const APE_STAR: BMap.ShapeType -declare const APE_SQUARE: BMap.ShapeType -declare const APE_RHOMBUS: BMap.ShapeType -declare const APE_WATERDROP: BMap.ShapeType - -declare const BMAP_POINT_SIZE_TINY: BMap.SizeType -declare const BMAP_POINT_SIZE_SMALLER: BMap.SizeType -declare const BMAP_POINT_SIZE_SMALL: BMap.SizeType -declare const BMAP_POINT_SIZE_NORMAL: BMap.SizeType -declare const BMAP_POINT_SIZE_BIG: BMap.SizeType -declare const BMAP_POINT_SIZE_BIGGER: BMap.SizeType +// Type definitions for BaiduMap v2.0 +// Project: http://lbsyun.baidu.com/index.php?title=jspopular +// Definitions by: Codemonk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/* ***************************************************************************** +Copyright [Codemonk] [Codemonk@live.cn] + +This project is licensed under the MIT license. +Copyrights are respective of each contributor listed at the beginning of each definition file. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************** */ + +/// +/// +/// +declare namespace BMap { + interface Overlay { + initialize?(map: Map): HTMLElement + isVisible?(): boolean + draw?(): void + show?(): void + hide?(): void + } + type SymbolShapeType = number + interface PolylineOptions { + strokeColor?: string + strokeWeight?: number + strokeOpacity?: number + strokeStyle?: string + enableMassClear?: boolean + enableEditing?: boolean + enableClicking?: boolean + } + interface GroundOverlayOptions { + opacity?: number + imageURL?: string + displayOnMinLevel?: number + displayOnMaxLevel?: number + } + class Marker implements Overlay { + constructor(point: Point, opts?: MarkerOptions) + openInfoWindow(infoWnd: InfoWindow): void + closeInfoWindow(): void + setIcon(icon: Icon): void + getIcon(): Icon + setPosition(position: Point): void + getPosition(): Point + setOffset(offset: Size): void + getOffset(): Size + setLabel(label: Label): void + getLabel(): Label + setTitle(title: string): void + getTitle(): string + setTop(isTop: boolean): void + enableDragging(): void + disableDragging(): void + enableMassClear(): void + disableMassClear(): void + setZIndex(zIndex: number): void + getMap(): Map + addContextMenu(menu: ContextMenu): void + removeContextMenu(menu: ContextMenu): void + setAnimation(animation?: Animation): void + setRotation(rotation: number): void + getRotation(): number + setShadow(shadow: Icon): void + getShadow(): void + addEventListener(event: string, handler: Function): void + removeEventListener(event: string, handler: Function): void + onclick: (event: { type: string, target: any }) => void + ondblclick: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onmousedown: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onmouseup: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onmouseout: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onmouseover: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onremove: (event: { type: string, target: any }) => void + oninfowindowclose: (event: { type: string, target: any }) => void + oninfowindowopen: (event: { type: string, target: any }) => void + ondragstart: (event: { type: string, target: any }) => void + ondragging: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + ondragend: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onrightclick: (event: { type: string, target: any }) => void + } + interface SymbolOptions { + anchor?: Size + fillColor?: string + fillOpacity?: number + scale?: number + rotation?: number + strokeColor?: string + strokeOpacity?: number + strokeWeight?: number + } + class IconSequence { + constructor(symbol: Symbol, offset?: string, repeat?: string, fixedRotation?: boolean) + } + class PointCollection implements Overlay { + constructor(points: Point[], opts?: PointCollectionOption) + setPoints(points: Point[]): void + setStyles(styles: PointCollectionOption): void + clear(): void + onclick: (event: { type: string, target: any, point: Point }) => void + onmouseover: (event: { type: string, target: any, point: Point }) => void + onmouseout: (event: { type: string, target: any, point: Point }) => void + } + interface MarkerOptions { + offset?: Size + icon?: Icon + enableMassClear?: boolean + enableDragging?: boolean + enableClicking?: boolean + raiseOnDrag?: boolean + draggingCursor?: string + rotation?: number + shadow?: Icon + title?: string + } + class InfoWindow implements Overlay { + constructor(content: string | HTMLElement, opts?: InfoWindowOptions) + setWidth(width: number): void + setHeight(height: number): void + redraw(): void + setTitle(title: string | HTMLElement): void + getTitle(): string | HTMLElement + setContent(content: string | HTMLElement): void + getContent(): string | HTMLElement + getPosition(): Point + enableMaximize(): void + disableMaximize(): void + isOpen(): boolean + setMaxContent(content: string): void + maximize(): void + restore(): void + enableAutoPan(): void + disableAutoPan(): void + enableCloseOnClick(): void + disableCloseOnClick(): void + addEventListener(event: string, handler: Function): void + removeEventListener(event: string, handler: Function): void + onclose: (event: { type: string, target: any, point: Point }) => void + onopen: (event: { type: string, target: any, point: Point }) => void + onmaximize: (event: { type: string, target: any }) => void + onrestore: (event: { type: string, target: any }) => void + onclickclose: (event: { type: string, target: any }) => void + } + class Polygon implements Overlay { + constructor(points: Array, opts?: PolygonOptions) + setPath(path: Point[]): void + getPath(): Point[] + setStrokeColor(color: string): void + getStrokeColor(): string + setFillColor(color: string): void + getFillColor(): string + setStrokeOpacity(opacity: number): void + getStrokeOpacity(): number + setFillOpacity(opacity: number): void + getFillOpacity(): number + setStrokeWeight(weight: number): void + getStrokeWeight(): number + setStrokeStyle(style: string): void + getStrokeStyle(): string + getBounds(): Bounds + enableEditing(): void + disableEditing(): void + enableMassClear(): void + disableMassClear(): void + setPointAt(index: number, point: Point): void + setPositionAt(index: number, point: Point): void + getMap(): Map + addEventListener(event: string, handler: Function): void + removeEventListener(event: string, handler: Function): void + onclick: (event: { type: string, target: any }) => void + ondblclick: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onmousedown: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onmouseup: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onmouseout: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onmouseover: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onremove: (event: { type: string, target: any }) => void + onlineupdate: (event: { type: string, target: any }) => void + } + interface PointCollectionOption { + shape?: ShapeType + color?: string + size?: SizeType + } + type Animation = number + interface InfoWindowOptions { + width?: number + height?: number + maxWidth?: number + offset?: Size + title?: string + enableAutoPan?: boolean + enableCloseOnClick?: boolean + enableMessage?: boolean + message?: string + } + interface PolygonOptions { + strokeColor?: string + fillColor?: string + strokeWeight?: number + strokeOpacity?: number + fillOpacity?: number + strokeStyle?: number + enableMassClear?: boolean + enableEditing?: boolean + enableClicking?: boolean + } + type ShapeType = number + class Icon implements Overlay { + constructor(url: string, size: Size, opts?: IconOptions) + anchor: Size + size: Size + imageOffset: Size + imageSize: Size + imageUrl: Size + infoWindowAnchor: Size + printImageUrl: string + setImageUrl(imageUrl: string): void + setSize(size: Size): void + setImageSize(offset: Size): void + setAnchor(anchor: Size): void + setImageOffset(offset: Size): void + setInfoWindowAnchor(anchor: Size): void + setPrintImageUrl(url: string): void + } + class Label implements Overlay { + constructor(content: string, opts?: LabelOptions) + setStyle(styles: Object): void + setContent(content: string): void + setPosition(position: Point): void + getPosition(): Point + setOffset(offset: Size): void + getOffset(): Size + setTitle(title: string): void + getTitle(): string + enableMassClear(): void + disableMassClear(): void + setZIndex(zIndex: number): void + setPosition(position: Point): void + getMap(): Map + addEventListener(event: string, handler: Function): void + removeEventListener(event: string, handler: Function): void + onclick: (event: { type: string, target: any }) => void + ondblclick: (event: { type: string, target: any }) => void + onmousedown: (event: { type: string, target: any }) => void + onmouseup: (event: { type: string, target: any }) => void + onmouseout: (event: { type: string, target: any }) => void + onmouseover: (event: { type: string, target: any }) => void + onremove: (event: { type: string, target: any }) => void + onrightclick: (event: { type: string, target: any }) => void + } + class Circle implements Overlay { + constructor(center: Point, radius: number, opts?: CircleOptions) + setCenter(center: Point): void + getCenter(): Point + setRadius(radius: number): void + getRadius(): number + getBounds(): Bounds + setStrokeColor(color: string): void + getStrokeColor(): string + setFillColor(color: string): void + getFillColor(): string + setStrokeOpacity(opacity: number): void + getStrokeOpacity(): number + setFillOpacity(opacity: number): void + getFillOpacity(): number + setStrokeWeight(weight: number): void + getStrokeWeight(): number + setStrokeStyle(style: string): void + getStrokeStyle(): string + getBounds(): Bounds + enableEditing(): void + disableEditing(): void + enableMassClear(): void + disableMassClear(): void + getMap(): Map + addEventListener(event: string, handler: Function): void + removeEventListener(event: string, handler: Function): void + onclick: (event: { type: string, target: any }) => void + ondblclick: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onmousedown: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onmouseup: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onmouseout: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onmouseover: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onremove: (event: { type: string, target: any }) => void + onlineupdate: (event: { type: string, target: any }) => void + } + type SizeType = number + interface IconOptions { + anchor?: Size + imageOffset?: Size + infoWindowAnchor?: Size + printImageUrl?: string + } + interface LabelOptions { + offset?: Size + position?: Point + enableMassClear?: boolean + } + interface CircleOptions { + strokeColor?: string + fillColor?: string + strokeWeight?: number + strokeOpacity?: number + fillOpacity?: number + strokeStyle?: string + enableMassClear?: boolean + enableEditing?: boolean + enableClicking?: boolean + } + class Hotspot implements Overlay { + constructor(position: Point, opts?: HotspotOptions) + setPosition(position: Point): void + getPosition(): Point + setText(text: string): void + getText(): string + setUserData(data: any): void + getUserData(): any + } + class Symbol implements Overlay { + constructor(path: string | SymbolShapeType, opts?: SymbolOptions) + setPath(path: string | SymbolShapeType): void + setAnchor(anchor: Size): void + setRotation(rotation: number): void + setScale(scale: number): void + setStrokeWeight(strokeWeight: number): void + setStrokeColor(color: string): void + setStrokeOpacity(opacity: number): void + setFillOpacity(opacity: number): void + setFillColor(color: string): void + } + class Polyline implements Overlay { + constructor(points: Point[], opts?: PolylineOptions) + setPath(path: Point[]): void + getPath(): Point[] + setStrokeColor(color: string): void + getStrokeColor(): string + setFillColor(color: string): void + getFillColor(): string + setStrokeOpacity(opacity: number): void + getStrokeOpacity(): number + setFillOpacity(opacity: number): void + getFillOpacity(): number + setStrokeWeight(weight: number): void + getStrokeWeight(): number + setStrokeStyle(style: string): void + getStrokeStyle(): string + getBounds(): Bounds + enableEditing(): void + disableEditing(): void + enableMassClear(): void + disableMassClear(): void + setPointAt(index: number, point: Point): void + setPositionAt(index: number, point: Point): void + getMap(): Map + addEventListener(event: string, handler: Function): void + removeEventListener(event: string, handler: Function): void + onclick: (event: { type: string, target: any }) => void + ondblclick: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onmousedown: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onmouseup: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onmouseout: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onmouseover: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onremove: (event: { type: string, target: any }) => void + onlineupdate: (event: { type: string, target: any }) => void + } + class GroundOverlay implements Overlay { + constructor(bounds: Bounds, opts?: GroundOverlayOptions) + setBounds(bounds: Bounds): void + getBounds(): Bounds + setOpacity(opcity: number): void + getOpacity(): number + setImageURL(url: string): void + getImageURL(): string + setDisplayOnMinLevel(level: number): void + getDisplayOnMinLevel(): number + setDispalyOnMaxLevel(level: number): void + getDispalyOnMaxLevel(): number + onclick: (event: { type: string, target: any }) => void + ondblclick: (event: { type: string, target: any }) => void + } + interface HotspotOptions { + text?: string + offsets?: number[] + userData?: any + minZoom?: number + maxZoom?: number + } + interface MapPanes { + floatPane?: HTMLElement + markerMouseTarget?: HTMLElement + floatShadow?: HTMLElement + labelPane?: HTMLElement + markerPane?: HTMLElement + markerShadow?: HTMLElement + mapPane?: HTMLElement + } +} + +declare const BMap_Symbol_SHAPE_CIRCLE: BMap.SymbolShapeType +declare const BMap_Symbol_SHAPE_RECTANGLE: BMap.SymbolShapeType +declare const BMap_Symbol_SHAPE_RHOMBUS: BMap.SymbolShapeType +declare const BMap_Symbol_SHAPE_STAR: BMap.SymbolShapeType +declare const BMap_Symbol_SHAPE_BACKWARD_CLOSED_ARROW: BMap.SymbolShapeType +declare const BMap_Symbol_SHAPE_FORWARD_CLOSED_ARROW: BMap.SymbolShapeType +declare const BMap_Symbol_SHAPE_BACKWARD_OPEN_ARROW: BMap.SymbolShapeType +declare const BMap_Symbol_SHAPE_FORWARD_OPEN_ARROW: BMap.SymbolShapeType +declare const BMap_Symbol_SHAPE_POINT: BMap.SymbolShapeType +declare const BMap_Symbol_SHAPE_PLANE: BMap.SymbolShapeType +declare const BMap_Symbol_SHAPE_CAMERA: BMap.SymbolShapeType +declare const BMap_Symbol_SHAPE_WARNING: BMap.SymbolShapeType +declare const BMap_Symbol_SHAPE_SMILE: BMap.SymbolShapeType +declare const BMap_Symbol_SHAPE_CLOCK: BMap.SymbolShapeType + + +declare const BMAP_ANIMATION_DROP: BMap.Animation +declare const BMAP_ANIMATION_BOUNCE: BMap.Animation + +declare const BMAP_POINT_SHAPE_CIRCLE: BMap.ShapeType +declare const APE_STAR: BMap.ShapeType +declare const APE_SQUARE: BMap.ShapeType +declare const APE_RHOMBUS: BMap.ShapeType +declare const APE_WATERDROP: BMap.ShapeType + +declare const BMAP_POINT_SIZE_TINY: BMap.SizeType +declare const BMAP_POINT_SIZE_SMALLER: BMap.SizeType +declare const BMAP_POINT_SIZE_SMALL: BMap.SizeType +declare const BMAP_POINT_SIZE_NORMAL: BMap.SizeType +declare const BMAP_POINT_SIZE_BIG: BMap.SizeType +declare const BMAP_POINT_SIZE_BIGGER: BMap.SizeType declare const BMAP_POINT_SIZE_HUGE: BMap.SizeType \ No newline at end of file diff --git a/types/baidumap-web-sdk/baidumap.panorama.d.ts b/types/baidumap-web-sdk/baidumap.panorama.d.ts index 6b3e10f6b2..f087732fb4 100644 --- a/types/baidumap-web-sdk/baidumap.panorama.d.ts +++ b/types/baidumap-web-sdk/baidumap.panorama.d.ts @@ -1,121 +1,121 @@ -// Type definitions for BaiduMap v2.0 -// Project: http://lbsyun.baidu.com/index.php?title=jspopular -// Definitions by: Codemonk -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/* ***************************************************************************** -Copyright [Codemonk] [Codemonk@live.cn] - -This project is licensed under the MIT license. -Copyrights are respective of each contributor listed at the beginning of each definition file. - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -***************************************************************************** */ - -/// -/// -declare namespace BMap { - class Panorama { - constructor(container: string | HTMLElement, opts?: PanoramaOptions) - getLinks(): PanoramaLink[] - getId(): string - getPosition(): Point - getPov(): PanoramaPov - getZoom(): number - setId(id: string): void - setPosition(position: Point): void - setPov(pov: PanoramaPov): void - setZoom(zoom: number): void - enableScrollWheelZoom(): void - disableScrollWheelZoom(): void - show(): void - hide(): void - addOverlay(overlay: PanoramaLabel): void - removeOverlay(overlay: PanoramaLabel): void - getSceneType(): PanoramaSceneType - setOptions(opts?: PanoramaOptions): void - setPanoramaPOIType(): PanoramaPOIType - onposition_changed: () => void - onlinks_changed: () => void - onpov_changed: () => void - onzoom_changed: () => void - onscene_type_changed: () => void - } - - interface PanoramaOptions { - navigationControl?: boolean - linksControl?: boolean - indoorSceneSwitchControl?: boolean - albumsControl?: boolean - albumsControlOptions?: AlbumsControlOptions - } - interface PanoramaLink { - description: string - heading: string - id: string - } - interface PanoramaPov { - heading: number - pitch: number - } - class PanoramaService { - constructor() - getPanoramaById(id: string, callback: (data: PanoramaData) => void): void - getPanoramaByLocation(point: Point, radius?: number, callback?: (data: PanoramaData) => void): void - } - interface PanoramaData { - id: string - description: string - links: PanoramaLink[] - position: Point - tiles: PanoramaTileData - } - interface PanoramaTileData { - centerHeading: number - tileSize: Size - worldSize: Size - } - class PanoramaLabel { - constructor(content: string, opts?: PanoramaLabelOptions) - setPosition(position: Point): void - getPosition(): Point - getPov(): PanoramaPov - setContent(content: string): void - getContent(): string - show(): void - hide(): void - setAltitude(altitude: number): void - getAltitude(): number - addEventListener(event: string, handler: Function): void - removeEventListener(event: string, handler: Function): void - onclick: (event: { type: string, target: any }) => void - onmouseover: (event: { type: string, target: any }) => void - onmouseout: (event: { type: string, target: any }) => void - onremove: (event: { type: string, target: any }) => void - } - interface PanoramaLabelOptions { - position?: Point - altitude?: number - } - interface AlbumsControlOptions { - anchor?: ControlAnchor - offset?: Size - maxWidth?: number | string - imageHeight?: number - } - type PanoramaSceneType = string - type PanoramaPOIType = string -} -declare const BMAP_PANORAMA_INDOOR_SCENE: string -declare const BMAP_PANORAMA_STREET_SCENE: string - -declare const BMAP_PANORAMA_POI_HOTEL: string -declare const BMAP_PANORAMA_POI_CATERING: string -declare const BMAP_PANORAMA_POI_MOVIE: string -declare const BMAP_PANORAMA_POI_TRANSIT: string -declare const BMAP_PANORAMA_POI_INDOOR_SCENE: string -declare const BMAP_PANORAMA_POI_NONE: string +// Type definitions for BaiduMap v2.0 +// Project: http://lbsyun.baidu.com/index.php?title=jspopular +// Definitions by: Codemonk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/* ***************************************************************************** +Copyright [Codemonk] [Codemonk@live.cn] + +This project is licensed under the MIT license. +Copyrights are respective of each contributor listed at the beginning of each definition file. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************** */ + +/// +/// +declare namespace BMap { + class Panorama { + constructor(container: string | HTMLElement, opts?: PanoramaOptions) + getLinks(): PanoramaLink[] + getId(): string + getPosition(): Point + getPov(): PanoramaPov + getZoom(): number + setId(id: string): void + setPosition(position: Point): void + setPov(pov: PanoramaPov): void + setZoom(zoom: number): void + enableScrollWheelZoom(): void + disableScrollWheelZoom(): void + show(): void + hide(): void + addOverlay(overlay: PanoramaLabel): void + removeOverlay(overlay: PanoramaLabel): void + getSceneType(): PanoramaSceneType + setOptions(opts?: PanoramaOptions): void + setPanoramaPOIType(): PanoramaPOIType + onposition_changed: () => void + onlinks_changed: () => void + onpov_changed: () => void + onzoom_changed: () => void + onscene_type_changed: () => void + } + + interface PanoramaOptions { + navigationControl?: boolean + linksControl?: boolean + indoorSceneSwitchControl?: boolean + albumsControl?: boolean + albumsControlOptions?: AlbumsControlOptions + } + interface PanoramaLink { + description: string + heading: string + id: string + } + interface PanoramaPov { + heading: number + pitch: number + } + class PanoramaService { + constructor() + getPanoramaById(id: string, callback: (data: PanoramaData) => void): void + getPanoramaByLocation(point: Point, radius?: number, callback?: (data: PanoramaData) => void): void + } + interface PanoramaData { + id: string + description: string + links: PanoramaLink[] + position: Point + tiles: PanoramaTileData + } + interface PanoramaTileData { + centerHeading: number + tileSize: Size + worldSize: Size + } + class PanoramaLabel { + constructor(content: string, opts?: PanoramaLabelOptions) + setPosition(position: Point): void + getPosition(): Point + getPov(): PanoramaPov + setContent(content: string): void + getContent(): string + show(): void + hide(): void + setAltitude(altitude: number): void + getAltitude(): number + addEventListener(event: string, handler: Function): void + removeEventListener(event: string, handler: Function): void + onclick: (event: { type: string, target: any }) => void + onmouseover: (event: { type: string, target: any }) => void + onmouseout: (event: { type: string, target: any }) => void + onremove: (event: { type: string, target: any }) => void + } + interface PanoramaLabelOptions { + position?: Point + altitude?: number + } + interface AlbumsControlOptions { + anchor?: ControlAnchor + offset?: Size + maxWidth?: number | string + imageHeight?: number + } + type PanoramaSceneType = string + type PanoramaPOIType = string +} +declare const BMAP_PANORAMA_INDOOR_SCENE: string +declare const BMAP_PANORAMA_STREET_SCENE: string + +declare const BMAP_PANORAMA_POI_HOTEL: string +declare const BMAP_PANORAMA_POI_CATERING: string +declare const BMAP_PANORAMA_POI_MOVIE: string +declare const BMAP_PANORAMA_POI_TRANSIT: string +declare const BMAP_PANORAMA_POI_INDOOR_SCENE: string +declare const BMAP_PANORAMA_POI_NONE: string diff --git a/types/baidumap-web-sdk/baidumap.rightmenu.d.ts b/types/baidumap-web-sdk/baidumap.rightmenu.d.ts index ef79b71641..b760c73561 100644 --- a/types/baidumap-web-sdk/baidumap.rightmenu.d.ts +++ b/types/baidumap-web-sdk/baidumap.rightmenu.d.ts @@ -1,47 +1,47 @@ -// Type definitions for BaiduMap v2.0 -// Project: http://lbsyun.baidu.com/index.php?title=jspopular -// Definitions by: Codemonk -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/* ***************************************************************************** -Copyright [Codemonk] [Codemonk@live.cn] - -This project is licensed under the MIT license. -Copyrights are respective of each contributor listed at the beginning of each definition file. - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -***************************************************************************** */ - -/// - -declare namespace BMap { - type ContextMenuIcon = string - interface MenuItemOptions { - width?: number - id?: string - iconUrl?: string - } - class MenuItem { - constructor(text: string, callback: (point: Point) => void, opts?: MenuItemOptions) - setText(text: string): void - setIcon(iconUrl: string): void - enable(): void - disable(): void - } - class ContextMenu { - constructor() - addItem(item: MenuItem): void - getItem(index: number): MenuItem - removeItem(item: MenuItem): void - addSeparator(): void - removeSeparator(index: number): void - onopen: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - onclose: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void - } -} -declare const BMAP_CONTEXT_MENU_ICON_ZOOMIN: string +// Type definitions for BaiduMap v2.0 +// Project: http://lbsyun.baidu.com/index.php?title=jspopular +// Definitions by: Codemonk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/* ***************************************************************************** +Copyright [Codemonk] [Codemonk@live.cn] + +This project is licensed under the MIT license. +Copyrights are respective of each contributor listed at the beginning of each definition file. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************** */ + +/// + +declare namespace BMap { + type ContextMenuIcon = string + interface MenuItemOptions { + width?: number + id?: string + iconUrl?: string + } + class MenuItem { + constructor(text: string, callback: (point: Point) => void, opts?: MenuItemOptions) + setText(text: string): void + setIcon(iconUrl: string): void + enable(): void + disable(): void + } + class ContextMenu { + constructor() + addItem(item: MenuItem): void + getItem(index: number): MenuItem + removeItem(item: MenuItem): void + addSeparator(): void + removeSeparator(index: number): void + onopen: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + onclose: (event: { type: string, target: any, point: Point, pixel: Pixel }) => void + } +} +declare const BMAP_CONTEXT_MENU_ICON_ZOOMIN: string declare const BMAP_CONTEXT_MENU_ICON_ZOOMOUT: string \ No newline at end of file diff --git a/types/baidumap-web-sdk/baidumap.service.d.ts b/types/baidumap-web-sdk/baidumap.service.d.ts index 54ca6f7e1d..dbff0b7dfe 100644 --- a/types/baidumap-web-sdk/baidumap.service.d.ts +++ b/types/baidumap-web-sdk/baidumap.service.d.ts @@ -1,432 +1,432 @@ -// Type definitions for BaiduMap v2.0 -// Project: http://lbsyun.baidu.com/index.php?title=jspopular -// Definitions by: Codemonk -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/* ***************************************************************************** -Copyright [Codemonk] [Codemonk@live.cn] - -This project is licensed under the MIT license. -Copyrights are respective of each contributor listed at the beginning of each definition file. - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -***************************************************************************** */ - -/// -/// -declare namespace BMap { - class LocalSearch { - constructor(location: Map | Point | string, opts?: LocalSearchOptions) - search(keyword: string | Array, option?: Object): void - searchInBounds(keyword: string | Array, bounds: Bounds, option?: Object): void - searchNearby(keyword: string | Array, center: LocalResultPoi | string | Point, radius: number, option?: Object): void - getResults(): LocalResult | LocalResult[] - clearResults(): void - gotoPage(page: number): void - enableAutoViewport(): void - disableAutoViewport(): void - enableFirstResultSelection(): void - disableFirstResultSelection(): void - setLocation(location: Map | Point | string): void - setPageCapacity(capacity: number): void - getPageCapacity(): number - setSearchCompleteCallback(callback: (results: LocalResult | LocalResult[]) => void): void - setMarkersSetCallback(callback: (pois: LocalResultPoi[]) => void): void - setInfoHtmlSetCallback(callback: (poi: LocalResultPoi, html: HTMLElement) => void): void - setResultsHtmlSetCallback(callback: (container: HTMLElement) => void): void - getStatus(): ServiceStatusCode - } - type LineType = number - interface WalkingRouteResult { - city: string - getStart(): LocalResultPoi - getEnd(): LocalResultPoi - getNumPlans(): number - getPlan(i: number): RoutePlan - } - class BusLineSearch { - constructor(location: Map | Point | string, opts?: BusLineSearchOptions) - getBusList(keyword: string): void - getBusLine(busLstItem: BusListItem): void - clearResults(): void - enableAutoViewport(): void - disableAutoViewport(): void - setLocation(location: Map | Point | string): void - getStatus(): ServiceStatusCode - toString(): string - setGetBusListCompleteCallback(callback: (rs: BusListResult) => void): void - setGetBusLineCompleteCallback(callback: (rs: BusLine) => void): void - setBusListHtmlSetCallback(callback: (container: HTMLElement) => void): void - setBusLineHtmlSetCallback(callback: (container: HTMLElement) => void): void - setPolylinesSetCallback(callback: (ply: Polyline) => void): void - setMarkersSetCallback(callback: (markers: Marker[]) => void): void - } - interface LocalSearchOptions { - renderOptions?: RenderOptions - onMarkersSet?: (pois: LocalResultPoi[]) => void - onInfoHtmlSet?: (poi: LocalResultPoi, html: HTMLElement) => void - onResultsHtmlSet?: (container: HTMLElement) => void - pageCapacity?: number - onSearchComplete?: (results: LocalResult[]) => void - } - class DrivingRoute { - constructor(location: Map | Point | string, opts?: DrivingRouteOptions) - search(start: string | Point | LocalResultPoi, end: string | Point | LocalResultPoi, opts?: Object): void - getResults(): DrivingRouteResult - clearResults(): void - enableAutoViewport(): void - disableAutoViewport(): void - setLocation(location: Map | Point | string): void - setPolicy(policy: DrivingPolicy): void - setSearchCompleteCallback(callback: (results: DrivingRouteResult) => void): void - setMarkersSetCallback(callback: (pois: LocalResultPoi[]) => void): void - setInfoHtmlSetCallback(callback: (poi: LocalResultPoi, html: HTMLElement) => void): void - setPolylinesSetCallback(callback: (routes: Route[]) => void): void - setResultsHtmlSetCallback(callback: (container: HTMLElement) => void): void - getStatus(): ServiceStatusCode - toString(): string - } - class Geocoder { - constructor() - getPoint(address: string, callback: (point: Point) => void, city: string): void - getLocation(point: Point, callback: (result: GeocoderResult) => void, opts?: LocationOptions): void - } - interface BusLineSearchOptions { - renderOptions?: RenderOptions - onGetBusListComplete?: (rs: BusListResult) => void - onGetBusLineComplete?: (rs: BusLine) => void - onBusListHtmlSet?: (container: HTMLElement) => void - onBusLineHtmlSet?: (container: HTMLElement) => void - onPolylinesSet?: (ply: Polyline) => void - onMarkersSet?: (sts: Marker[]) => void - } - interface CustomData { - geotableId: number - tags: string - filter: string - } - interface DrivingRouteOptions { - renderOptions?: RenderOptions - policy?: DrivingPolicy - onSearchComplete?: (results: DrivingRouteResult) => void - onMarkersSet?: (pois: LocalResultPoi[]) => void - onInfoHtmlSet?: (poi: LocalResultPoi, html: HTMLElement) => void - onPolylinesSet?: (routes: Route[]) => void - onResultsHtmlSet?: (container: HTMLElement) => void - } - interface GeocoderResult { - point: Point - address: string - addressComponents: AddressComponent - surroundingPoi: LocalResultPoi[] - business: string - } - interface BusListResult { - keyword: string - city: string - moreResultsUrl: string - getNumBusList(): number - getBusListItem(i: number): BusListItem - } - interface RenderOptions { - map: Map - panel?: string | HTMLElement - selectFirstResult?: boolean - autoViewport?: boolean - highlightMode?: HighlightModes - } - type DrivingPolicy = number - interface AddressComponent { - streetNumber: string - street: string - district: string - city: string - province: string - } - interface BusLine { - name: string - startTime: string - endTime: string - company: string - getNumBusStations(): string - getBusStation(i: number): BusStation - getPath(): Point[] - getPolyline(): Polyline - } - interface LocalResult { - keyword: string - center: LocalResultPoi - radius: number - bounds: Bounds - city: string - moreResultsUrl: string - province: string - suggestions: string[] - getPoi(i: number): LocalResultPoi - getCurrentNumPois(): number - getNumPois(): number - getNumPages(): number - getPageIndex(): number - getCityList(): any[] - } - - interface DrivingRouteResult { - policy: DrivingPolicy - city: string - moreResultsUrl: string - taxiFare: TaxiFare - getStart(): LocalResultPoi - getEnd(): LocalResultPoi - getNumPlans(): number - getPlan(i: number): RoutePlan - } - interface LocationOptions { - poiRadius?: number - numPois?: number - } - interface BusListItem { - name: string - } - interface LocalResultPoi { - title: string - point: Point - url: string - address: string - city: string - phoneNumber: string - postcode: string - type: PoiType - isAccurate: boolean - province: string - tags: string[] - detailUrl: string - } - interface TaxiFare { - day: TaxiFareDetail - night: TaxiFareDetail - distance: number - remark: string - } - class LocalCity { - constructor(opts?: LocalCityOptions) - get(callback: (result: LocalCityResult) => void): void - } - interface BusStation { - name: string - position: Point - } - type PoiType = number - interface TaxiFareDetail { - initialFare: number - unitFare: number - totalFare: number - } - interface LocalCityOptions { - renderOptions?: RenderOptions - } - class Autocomplete { - constructor(opts?: AutocompleteOptions) - show(): void - hide(): void - setTypes(types: string[]): void - setLocation(location: string | Map | Point): void - search(keywords: string): void - getResults(): AutocompleteResult - setInputValue(keyword: string): void - dispose(): void - onconfirm: (event: { type: string, target: any, item: any }) => void - onhighlight: (event: { type: string, target: any, fromitem: any, toitem: any }) => void - } - class TransitRoute { - constructor(location: Map | Point | string, opts?: TransitRouteOptions) - search(start: string | Point | LocalResultPoi, end: string | Point | LocalResultPoi): void - getResults(): TransitRouteResult - clearResults(): void - enableAutoViewport(): void - disableAutoViewport(): void - setPageCapacity(capacity: number): void - setLocation(location: Map | Point | string): void - setPolicy(policy: TransitPolicy): void - setSearchCompleteCallback(callback: (results: TransitRouteResult) => void): void - setMarkersSetCallback(callback: (pois: LocalResultPoi[]) => void): void - setInfoHtmlSetCallback(callback: (poi: LocalResultPoi, html: HTMLElement) => void): void - setPolylinesSetCallback(callback: (lines: Line[], routes: Route[]) => void): void - setResultsHtmlSetCallback(callback: (container: HTMLElement) => void): void - getStatus(): ServiceStatusCode - toString(): string - } - interface RoutePlan { - getNumRoutes(): number - getRoute(i: number): Route - getDistance(format?: boolean): string | number - getDuration(format?: boolean): string | number - getDragPois(): LocalResultPoi[] - } - interface LocalCityResult { - center: Point - level: number - name: string - } - interface AutocompleteOptions { - location?: string | Map | Point - types?: string[] - onSearchComplete?: (result: AutocompleteResult) => void - input?: string | HTMLElement - } - interface TransitRouteOptions { - renderOptions?: RenderOptions - policy?: TransitPolicy - pageCapacity?: number - onSearchComplete?: (result: TransitRouteResult) => void - onMarkersSet?: (pois: LocalResultPoi[], transfers: LocalResultPoi[]) => void - onInfoHtmlSet?: (poi: LocalResultPoi, html: HTMLElement) => void - onPolylinesSet?: (lines: Line[]) => void - onResultsHtmlSet?: (container: HTMLElement) => void - } - interface Route { - getNumRoutes(): number - getStep(i: number): Step - getDistance(format?: boolean): string | number - getIndex(): number - getPolyline(): Polyline - getPoints(): Point[] - getPath(): Point[] - getRouteType(): RouteType - } - class TrafficControl { - constructor() - setPanelOffset(offset: Size): void - show(): void - hide(): void - } - interface AutocompleteResultPoi { - province: string - City: string//wtf - district: string - street: string - streetNumber: string - business: string - } - type TransitPolicy = number - type RouteType = number - class Geolocation { - constructor() - getCurrentPosition(callback: (result: GeolocationResult) => void, opts?: PositionOptions): void - getStatus(): ServiceStatusCode - } - interface AutocompleteResult { - keyword: string - getPoi(i: number): AutocompleteResultPoi - getNumPois(): number - } - interface TransitRouteResult { - policy: TransitPolicy - city: string - moreResultsUrl: string - getStart(): LocalResultPoi - getEnd(): LocalResultPoi - getNumPlans(): number - getPlan(i: number): TransitRoutePlan - } - interface Step { - getPoint(): Point - getPosition(): Point - getIndex(): number - getDescription(includeHtml: boolean): string - getDistance(format?: boolean): string | number - } - interface GeolocationResult { - point: Point - accuracy: number - } - class Boundary { - constructor() - get(name: string, callback: (result: string[]) => void): void - } - interface TransitRoutePlan { - getNumLines(): number - getLine(i: number): Line - getNumRoutes(): number - getRoute(i: number): Route - getDistance(format?: boolean): string | number - getDuration(format?: boolean): string | number - getDescription(includeHtml: boolean): string - } - class WalkingRoute { - constructor(location: Map | Point | string, opts?: WalkingRouteOptions) - search(start: string | Point | LocalResultPoi, end: string | Point | LocalResultPoi): void - getResults(): WalkingRouteResult - clearResults(): void - enableAutoViewport(): void - disableAutoViewport(): void - setLocation(location: Map | Point | string): void - setSearchCompleteCallback(callback: (result: WalkingRouteResult) => void): void - setMarkersSetCallback(callback: (pois: LocalResultPoi[]) => void): void - setInfoHtmlSetCallback(callback: (poi: LocalResultPoi, html: HTMLElement) => void): void - setPolylinesSetCallback(callback: (routes: Route[]) => void): void - setResultsHtmlSetCallback(callback: (container: HTMLElement) => void): void - getStatus(): ServiceStatusCode - toString(): string - } - interface PositionOptions { - enableHighAccuracy?: boolean - timeout?: number - maximumAge?: number - } - interface Line { - title: string - type: LineType - getNumViaStops(): number - getGetOnStop(): LocalResultPoi - getGetOffStop(): LocalResultPoi - getPoints(): Point[] - getPath(): Point[] - getPolyline(): Polyline - getDistance(format?: boolean): string | number - } - interface WalkingRouteOptions { - renderOptions?: RenderOptions, - onSearchComplete?: (result: WalkingRouteResult) => void, - onMarkersSet?: (pois: LocalResultPoi[]) => void, - onPolylinesSet?: (routes: Route[]) => void, - onInfoHtmlSet?: (poi: LocalResultPoi, html: HTMLElement) => void, - onResultsHtmlSet?: (container: HTMLElement) => void - } - type HighlightModes = number - type ServiceStatusCode = number -} - -declare const BMAP_LINE_TYPE_BUS: BMap.LineType -declare const BMAP_LINE_TYPE_SUBWAY: BMap.LineType -declare const BMAP_LINE_TYPE_FERRY: BMap.LineType - -declare const BMAP_DRIVING_POLICY_LEAST_TIME: BMap.DrivingPolicy -declare const BMAP_DRIVING_POLICY_LEAST_DISTANCE: BMap.DrivingPolicy -declare const BMAP_DRIVING_POLICY_AVOID_HIGHWAYS: BMap.DrivingPolicy - -declare const BMAP_POI_TYPE_NORMAL: BMap.PoiType -declare const BMAP_POI_TYPE_BUSSTOP: BMap.PoiType -declare const BMAP_POI_TYPE_SUBSTOP: BMap.PoiType - - -declare const BMAP_TRANSIT_POLICY_LEAST_TIME: BMap.TransitPolicy -declare const BMAP_TRANSIT_POLICY_LEAST_TRANSFER: BMap.TransitPolicy -declare const BMAP_TRANSIT_POLICY_LEAST_WALKING: BMap.TransitPolicy -declare const BMAP_TRANSIT_POLICY_AVOID_SUBWAYS: BMap.TransitPolicy - -declare const BMAP_ROUTE_TYPE_DRIVING: BMap.RouteType -declare const BMAP_ROUTE_TYPE_WALKING: BMap.RouteType - -declare const BMAP_HIGHLIGHT_STEP: BMap.HighlightModes -declare const BMAP_HIGHLIGHT_ROUTE: BMap.HighlightModes - -declare const BMAP_STATUS_SUCCESS: BMap.ServiceStatusCode -declare const BMAP_STATUS_CITY_LIST: BMap.ServiceStatusCode -declare const BMAP_STATUS_UNKNOWN_LOCATION: BMap.ServiceStatusCode -declare const BMAP_STATUS_UNKNOWN_ROUTE: BMap.ServiceStatusCode -declare const BMAP_STATUS_INVALID_KEY: BMap.ServiceStatusCode -declare const BMAP_STATUS_INVALID_REQUEST: BMap.ServiceStatusCode \ No newline at end of file +// Type definitions for BaiduMap v2.0 +// Project: http://lbsyun.baidu.com/index.php?title=jspopular +// Definitions by: Codemonk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/* ***************************************************************************** +Copyright [Codemonk] [Codemonk@live.cn] + +This project is licensed under the MIT license. +Copyrights are respective of each contributor listed at the beginning of each definition file. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************** */ + +/// +/// +declare namespace BMap { + class LocalSearch { + constructor(location: Map | Point | string, opts?: LocalSearchOptions) + search(keyword: string | Array, option?: Object): void + searchInBounds(keyword: string | Array, bounds: Bounds, option?: Object): void + searchNearby(keyword: string | Array, center: LocalResultPoi | string | Point, radius: number, option?: Object): void + getResults(): LocalResult | LocalResult[] + clearResults(): void + gotoPage(page: number): void + enableAutoViewport(): void + disableAutoViewport(): void + enableFirstResultSelection(): void + disableFirstResultSelection(): void + setLocation(location: Map | Point | string): void + setPageCapacity(capacity: number): void + getPageCapacity(): number + setSearchCompleteCallback(callback: (results: LocalResult | LocalResult[]) => void): void + setMarkersSetCallback(callback: (pois: LocalResultPoi[]) => void): void + setInfoHtmlSetCallback(callback: (poi: LocalResultPoi, html: HTMLElement) => void): void + setResultsHtmlSetCallback(callback: (container: HTMLElement) => void): void + getStatus(): ServiceStatusCode + } + type LineType = number + interface WalkingRouteResult { + city: string + getStart(): LocalResultPoi + getEnd(): LocalResultPoi + getNumPlans(): number + getPlan(i: number): RoutePlan + } + class BusLineSearch { + constructor(location: Map | Point | string, opts?: BusLineSearchOptions) + getBusList(keyword: string): void + getBusLine(busLstItem: BusListItem): void + clearResults(): void + enableAutoViewport(): void + disableAutoViewport(): void + setLocation(location: Map | Point | string): void + getStatus(): ServiceStatusCode + toString(): string + setGetBusListCompleteCallback(callback: (rs: BusListResult) => void): void + setGetBusLineCompleteCallback(callback: (rs: BusLine) => void): void + setBusListHtmlSetCallback(callback: (container: HTMLElement) => void): void + setBusLineHtmlSetCallback(callback: (container: HTMLElement) => void): void + setPolylinesSetCallback(callback: (ply: Polyline) => void): void + setMarkersSetCallback(callback: (markers: Marker[]) => void): void + } + interface LocalSearchOptions { + renderOptions?: RenderOptions + onMarkersSet?: (pois: LocalResultPoi[]) => void + onInfoHtmlSet?: (poi: LocalResultPoi, html: HTMLElement) => void + onResultsHtmlSet?: (container: HTMLElement) => void + pageCapacity?: number + onSearchComplete?: (results: LocalResult[]) => void + } + class DrivingRoute { + constructor(location: Map | Point | string, opts?: DrivingRouteOptions) + search(start: string | Point | LocalResultPoi, end: string | Point | LocalResultPoi, opts?: Object): void + getResults(): DrivingRouteResult + clearResults(): void + enableAutoViewport(): void + disableAutoViewport(): void + setLocation(location: Map | Point | string): void + setPolicy(policy: DrivingPolicy): void + setSearchCompleteCallback(callback: (results: DrivingRouteResult) => void): void + setMarkersSetCallback(callback: (pois: LocalResultPoi[]) => void): void + setInfoHtmlSetCallback(callback: (poi: LocalResultPoi, html: HTMLElement) => void): void + setPolylinesSetCallback(callback: (routes: Route[]) => void): void + setResultsHtmlSetCallback(callback: (container: HTMLElement) => void): void + getStatus(): ServiceStatusCode + toString(): string + } + class Geocoder { + constructor() + getPoint(address: string, callback: (point: Point) => void, city: string): void + getLocation(point: Point, callback: (result: GeocoderResult) => void, opts?: LocationOptions): void + } + interface BusLineSearchOptions { + renderOptions?: RenderOptions + onGetBusListComplete?: (rs: BusListResult) => void + onGetBusLineComplete?: (rs: BusLine) => void + onBusListHtmlSet?: (container: HTMLElement) => void + onBusLineHtmlSet?: (container: HTMLElement) => void + onPolylinesSet?: (ply: Polyline) => void + onMarkersSet?: (sts: Marker[]) => void + } + interface CustomData { + geotableId: number + tags: string + filter: string + } + interface DrivingRouteOptions { + renderOptions?: RenderOptions + policy?: DrivingPolicy + onSearchComplete?: (results: DrivingRouteResult) => void + onMarkersSet?: (pois: LocalResultPoi[]) => void + onInfoHtmlSet?: (poi: LocalResultPoi, html: HTMLElement) => void + onPolylinesSet?: (routes: Route[]) => void + onResultsHtmlSet?: (container: HTMLElement) => void + } + interface GeocoderResult { + point: Point + address: string + addressComponents: AddressComponent + surroundingPoi: LocalResultPoi[] + business: string + } + interface BusListResult { + keyword: string + city: string + moreResultsUrl: string + getNumBusList(): number + getBusListItem(i: number): BusListItem + } + interface RenderOptions { + map: Map + panel?: string | HTMLElement + selectFirstResult?: boolean + autoViewport?: boolean + highlightMode?: HighlightModes + } + type DrivingPolicy = number + interface AddressComponent { + streetNumber: string + street: string + district: string + city: string + province: string + } + interface BusLine { + name: string + startTime: string + endTime: string + company: string + getNumBusStations(): string + getBusStation(i: number): BusStation + getPath(): Point[] + getPolyline(): Polyline + } + interface LocalResult { + keyword: string + center: LocalResultPoi + radius: number + bounds: Bounds + city: string + moreResultsUrl: string + province: string + suggestions: string[] + getPoi(i: number): LocalResultPoi + getCurrentNumPois(): number + getNumPois(): number + getNumPages(): number + getPageIndex(): number + getCityList(): any[] + } + + interface DrivingRouteResult { + policy: DrivingPolicy + city: string + moreResultsUrl: string + taxiFare: TaxiFare + getStart(): LocalResultPoi + getEnd(): LocalResultPoi + getNumPlans(): number + getPlan(i: number): RoutePlan + } + interface LocationOptions { + poiRadius?: number + numPois?: number + } + interface BusListItem { + name: string + } + interface LocalResultPoi { + title: string + point: Point + url: string + address: string + city: string + phoneNumber: string + postcode: string + type: PoiType + isAccurate: boolean + province: string + tags: string[] + detailUrl: string + } + interface TaxiFare { + day: TaxiFareDetail + night: TaxiFareDetail + distance: number + remark: string + } + class LocalCity { + constructor(opts?: LocalCityOptions) + get(callback: (result: LocalCityResult) => void): void + } + interface BusStation { + name: string + position: Point + } + type PoiType = number + interface TaxiFareDetail { + initialFare: number + unitFare: number + totalFare: number + } + interface LocalCityOptions { + renderOptions?: RenderOptions + } + class Autocomplete { + constructor(opts?: AutocompleteOptions) + show(): void + hide(): void + setTypes(types: string[]): void + setLocation(location: string | Map | Point): void + search(keywords: string): void + getResults(): AutocompleteResult + setInputValue(keyword: string): void + dispose(): void + onconfirm: (event: { type: string, target: any, item: any }) => void + onhighlight: (event: { type: string, target: any, fromitem: any, toitem: any }) => void + } + class TransitRoute { + constructor(location: Map | Point | string, opts?: TransitRouteOptions) + search(start: string | Point | LocalResultPoi, end: string | Point | LocalResultPoi): void + getResults(): TransitRouteResult + clearResults(): void + enableAutoViewport(): void + disableAutoViewport(): void + setPageCapacity(capacity: number): void + setLocation(location: Map | Point | string): void + setPolicy(policy: TransitPolicy): void + setSearchCompleteCallback(callback: (results: TransitRouteResult) => void): void + setMarkersSetCallback(callback: (pois: LocalResultPoi[]) => void): void + setInfoHtmlSetCallback(callback: (poi: LocalResultPoi, html: HTMLElement) => void): void + setPolylinesSetCallback(callback: (lines: Line[], routes: Route[]) => void): void + setResultsHtmlSetCallback(callback: (container: HTMLElement) => void): void + getStatus(): ServiceStatusCode + toString(): string + } + interface RoutePlan { + getNumRoutes(): number + getRoute(i: number): Route + getDistance(format?: boolean): string | number + getDuration(format?: boolean): string | number + getDragPois(): LocalResultPoi[] + } + interface LocalCityResult { + center: Point + level: number + name: string + } + interface AutocompleteOptions { + location?: string | Map | Point + types?: string[] + onSearchComplete?: (result: AutocompleteResult) => void + input?: string | HTMLElement + } + interface TransitRouteOptions { + renderOptions?: RenderOptions + policy?: TransitPolicy + pageCapacity?: number + onSearchComplete?: (result: TransitRouteResult) => void + onMarkersSet?: (pois: LocalResultPoi[], transfers: LocalResultPoi[]) => void + onInfoHtmlSet?: (poi: LocalResultPoi, html: HTMLElement) => void + onPolylinesSet?: (lines: Line[]) => void + onResultsHtmlSet?: (container: HTMLElement) => void + } + interface Route { + getNumRoutes(): number + getStep(i: number): Step + getDistance(format?: boolean): string | number + getIndex(): number + getPolyline(): Polyline + getPoints(): Point[] + getPath(): Point[] + getRouteType(): RouteType + } + class TrafficControl { + constructor() + setPanelOffset(offset: Size): void + show(): void + hide(): void + } + interface AutocompleteResultPoi { + province: string + City: string//wtf + district: string + street: string + streetNumber: string + business: string + } + type TransitPolicy = number + type RouteType = number + class Geolocation { + constructor() + getCurrentPosition(callback: (result: GeolocationResult) => void, opts?: PositionOptions): void + getStatus(): ServiceStatusCode + } + interface AutocompleteResult { + keyword: string + getPoi(i: number): AutocompleteResultPoi + getNumPois(): number + } + interface TransitRouteResult { + policy: TransitPolicy + city: string + moreResultsUrl: string + getStart(): LocalResultPoi + getEnd(): LocalResultPoi + getNumPlans(): number + getPlan(i: number): TransitRoutePlan + } + interface Step { + getPoint(): Point + getPosition(): Point + getIndex(): number + getDescription(includeHtml: boolean): string + getDistance(format?: boolean): string | number + } + interface GeolocationResult { + point: Point + accuracy: number + } + class Boundary { + constructor() + get(name: string, callback: (result: string[]) => void): void + } + interface TransitRoutePlan { + getNumLines(): number + getLine(i: number): Line + getNumRoutes(): number + getRoute(i: number): Route + getDistance(format?: boolean): string | number + getDuration(format?: boolean): string | number + getDescription(includeHtml: boolean): string + } + class WalkingRoute { + constructor(location: Map | Point | string, opts?: WalkingRouteOptions) + search(start: string | Point | LocalResultPoi, end: string | Point | LocalResultPoi): void + getResults(): WalkingRouteResult + clearResults(): void + enableAutoViewport(): void + disableAutoViewport(): void + setLocation(location: Map | Point | string): void + setSearchCompleteCallback(callback: (result: WalkingRouteResult) => void): void + setMarkersSetCallback(callback: (pois: LocalResultPoi[]) => void): void + setInfoHtmlSetCallback(callback: (poi: LocalResultPoi, html: HTMLElement) => void): void + setPolylinesSetCallback(callback: (routes: Route[]) => void): void + setResultsHtmlSetCallback(callback: (container: HTMLElement) => void): void + getStatus(): ServiceStatusCode + toString(): string + } + interface PositionOptions { + enableHighAccuracy?: boolean + timeout?: number + maximumAge?: number + } + interface Line { + title: string + type: LineType + getNumViaStops(): number + getGetOnStop(): LocalResultPoi + getGetOffStop(): LocalResultPoi + getPoints(): Point[] + getPath(): Point[] + getPolyline(): Polyline + getDistance(format?: boolean): string | number + } + interface WalkingRouteOptions { + renderOptions?: RenderOptions, + onSearchComplete?: (result: WalkingRouteResult) => void, + onMarkersSet?: (pois: LocalResultPoi[]) => void, + onPolylinesSet?: (routes: Route[]) => void, + onInfoHtmlSet?: (poi: LocalResultPoi, html: HTMLElement) => void, + onResultsHtmlSet?: (container: HTMLElement) => void + } + type HighlightModes = number + type ServiceStatusCode = number +} + +declare const BMAP_LINE_TYPE_BUS: BMap.LineType +declare const BMAP_LINE_TYPE_SUBWAY: BMap.LineType +declare const BMAP_LINE_TYPE_FERRY: BMap.LineType + +declare const BMAP_DRIVING_POLICY_LEAST_TIME: BMap.DrivingPolicy +declare const BMAP_DRIVING_POLICY_LEAST_DISTANCE: BMap.DrivingPolicy +declare const BMAP_DRIVING_POLICY_AVOID_HIGHWAYS: BMap.DrivingPolicy + +declare const BMAP_POI_TYPE_NORMAL: BMap.PoiType +declare const BMAP_POI_TYPE_BUSSTOP: BMap.PoiType +declare const BMAP_POI_TYPE_SUBSTOP: BMap.PoiType + + +declare const BMAP_TRANSIT_POLICY_LEAST_TIME: BMap.TransitPolicy +declare const BMAP_TRANSIT_POLICY_LEAST_TRANSFER: BMap.TransitPolicy +declare const BMAP_TRANSIT_POLICY_LEAST_WALKING: BMap.TransitPolicy +declare const BMAP_TRANSIT_POLICY_AVOID_SUBWAYS: BMap.TransitPolicy + +declare const BMAP_ROUTE_TYPE_DRIVING: BMap.RouteType +declare const BMAP_ROUTE_TYPE_WALKING: BMap.RouteType + +declare const BMAP_HIGHLIGHT_STEP: BMap.HighlightModes +declare const BMAP_HIGHLIGHT_ROUTE: BMap.HighlightModes + +declare const BMAP_STATUS_SUCCESS: BMap.ServiceStatusCode +declare const BMAP_STATUS_CITY_LIST: BMap.ServiceStatusCode +declare const BMAP_STATUS_UNKNOWN_LOCATION: BMap.ServiceStatusCode +declare const BMAP_STATUS_UNKNOWN_ROUTE: BMap.ServiceStatusCode +declare const BMAP_STATUS_INVALID_KEY: BMap.ServiceStatusCode +declare const BMAP_STATUS_INVALID_REQUEST: BMap.ServiceStatusCode \ No newline at end of file diff --git a/types/baidumap-web-sdk/baidumap.tools.d.ts b/types/baidumap-web-sdk/baidumap.tools.d.ts index cd3ba6b619..c1bc6bf929 100644 --- a/types/baidumap-web-sdk/baidumap.tools.d.ts +++ b/types/baidumap-web-sdk/baidumap.tools.d.ts @@ -1,61 +1,61 @@ -// Type definitions for BaiduMap v2.0 -// Project: http://lbsyun.baidu.com/index.php?title=jspopular -// Definitions by: Codemonk -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/* ***************************************************************************** -Copyright [Codemonk] [Codemonk@live.cn] - -This project is licensed under the MIT license. -Copyrights are respective of each contributor listed at the beginning of each definition file. - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -***************************************************************************** */ - -/// -/// -/// -declare namespace BMap { - class PushpinTool { - constructor(map: Map, opts?: PushpinToolOptions) - open(): boolean - close(): boolean - setIcon(icon: Icon): Icon - getIcon(): Icon - setCursor(cursor: string): string - getCursor(): string - toString(): string - onmarkend: (event: { type: string, target: any, marker: Marker }) => void - } - interface PushpinToolOptions { - icon?: Icon - cursor?: string - followText?: string - } - class DistanceTool { - constructor(map: Map) - open(): boolean - close(): void - toString(): string - ondrawend: (event: { type: string, target: any, points: Point[], polylines: Polyline[], distance: number }) => void - } - class DragAndZoomTool { - constructor(map: Map, opts?: DragAndZoomToolOptions) - open(): boolean - close(): void - toString(): string - ondrawend: (event: { type: string, target: any, bounds: Bounds[] }) => void - } - interface DragAndZoomToolOptions { - zoomType?: ZoomType, - autoClose?: boolean, - followText?: string - } - type ZoomType = number -} -declare const BMAP_ZOOM_IN: BMap.ZoomType +// Type definitions for BaiduMap v2.0 +// Project: http://lbsyun.baidu.com/index.php?title=jspopular +// Definitions by: Codemonk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/* ***************************************************************************** +Copyright [Codemonk] [Codemonk@live.cn] + +This project is licensed under the MIT license. +Copyrights are respective of each contributor listed at the beginning of each definition file. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************** */ + +/// +/// +/// +declare namespace BMap { + class PushpinTool { + constructor(map: Map, opts?: PushpinToolOptions) + open(): boolean + close(): boolean + setIcon(icon: Icon): Icon + getIcon(): Icon + setCursor(cursor: string): string + getCursor(): string + toString(): string + onmarkend: (event: { type: string, target: any, marker: Marker }) => void + } + interface PushpinToolOptions { + icon?: Icon + cursor?: string + followText?: string + } + class DistanceTool { + constructor(map: Map) + open(): boolean + close(): void + toString(): string + ondrawend: (event: { type: string, target: any, points: Point[], polylines: Polyline[], distance: number }) => void + } + class DragAndZoomTool { + constructor(map: Map, opts?: DragAndZoomToolOptions) + open(): boolean + close(): void + toString(): string + ondrawend: (event: { type: string, target: any, bounds: Bounds[] }) => void + } + interface DragAndZoomToolOptions { + zoomType?: ZoomType, + autoClose?: boolean, + followText?: string + } + type ZoomType = number +} +declare const BMAP_ZOOM_IN: BMap.ZoomType declare const BMAP_ZOOM_OUT: BMap.ZoomType \ No newline at end of file diff --git a/types/baidumap-web-sdk/index.d.ts b/types/baidumap-web-sdk/index.d.ts index cfab71e884..ac8f27c87b 100644 --- a/types/baidumap-web-sdk/index.d.ts +++ b/types/baidumap-web-sdk/index.d.ts @@ -1,28 +1,28 @@ -// Type definitions for BaiduMap v2.0 -// Project: http://lbsyun.baidu.com/index.php?title=jspopular -// Definitions by: Codemonk -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/* ***************************************************************************** -Copyright [Codemonk] [Codemonk@live.cn] - -This project is licensed under the MIT license. -Copyrights are respective of each contributor listed at the beginning of each definition file. - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -***************************************************************************** */ - -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// \ No newline at end of file +// Type definitions for BaiduMap v2.0 +// Project: http://lbsyun.baidu.com/index.php?title=jspopular +// Definitions by: Codemonk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/* ***************************************************************************** +Copyright [Codemonk] [Codemonk@live.cn] + +This project is licensed under the MIT license. +Copyrights are respective of each contributor listed at the beginning of each definition file. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************** */ + +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// \ No newline at end of file diff --git a/types/baidumap-web-sdk/tslint.json b/types/baidumap-web-sdk/tslint.json new file mode 100644 index 0000000000..aab43caa1d --- /dev/null +++ b/types/baidumap-web-sdk/tslint.json @@ -0,0 +1,15 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // All are TODOs + "eofline": false, + "comment-format": false, + "dt-header": false, + "max-line-length": false, + "member-access": false, + "no-namespace": false, + "no-useless-files": false, + "no-var": false, + "semicolon": false + } +} diff --git a/types/bittorrent-protocol/index.d.ts b/types/bittorrent-protocol/index.d.ts index b5ef1a4a44..7c205edc33 100644 --- a/types/bittorrent-protocol/index.d.ts +++ b/types/bittorrent-protocol/index.d.ts @@ -81,7 +81,7 @@ declare namespace BittorrentProtocol { // TODO: bitfield is a bitfield instance on(event: 'bitfield', listener: (bitfield: any) => void): this; - on(event: string | 'keep-alive' | 'choke' | 'unchoke' | 'interested' | 'uninterested' | 'timeout', listener: () => void): this; + on(event: 'keep-alive' | 'choke' | 'unchoke' | 'interested' | 'uninterested' | 'timeout', listener: () => void): this; on(event: 'upload' | 'have' | 'download' | 'port', listener: (length: number) => void): this; on(event: 'handshake', listener: (infoHash: string, peerId: string, extensions: Extension[]) => void): this; on(event: 'request', listener: (index: number, offset: number, length: number, respond: () => void) => void): this; @@ -89,6 +89,7 @@ declare namespace BittorrentProtocol { on(event: 'cancel', listener: (index: number, offset: number, length: number) => void): this; on(event: 'extended', listener: (ext: 'handshake' | string, buf: any) => void): void; on(event: 'unknownmessage', listener: (buffer: Buffer) => void): this; + on(event: string, listener: (...args: any[]) => void): this; } } diff --git a/types/blue-tape/index.d.ts b/types/blue-tape/index.d.ts index 133968a165..c2d2d50ab5 100644 --- a/types/blue-tape/index.d.ts +++ b/types/blue-tape/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/spion/blue-tape // Definitions by: Haoqun Jiang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/bluebird-global/index.d.ts b/types/bluebird-global/index.d.ts index 835bc59c31..c0e220ce07 100644 --- a/types/bluebird-global/index.d.ts +++ b/types/bluebird-global/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/petkaantonov/bluebird // Definitions by: d-ph // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /* * 1. Why use `bluebird-global` instead of `bluebird`? @@ -117,19 +118,19 @@ declare global { * * @todo Duplication of code is never ideal. See whether there's a better way of achieving this. */ - catch(predicate: (error: any) => boolean, onReject: (error: any) => T | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; - catch(predicate: (error: any) => boolean, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; - catch(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => T | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; - catch(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => U | Bluebird.Thenable): Bluebird; - catch(predicate: Object, onReject: (error: any) => T | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; - catch(predicate: Object, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; + catch(predicate: (error: any) => boolean, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Bluebird; + catch(predicate: (error: any) => boolean, onReject: (error: any) => U | PromiseLike): Bluebird; + catch(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => T | PromiseLike | void | PromiseLike): Bluebird; + catch(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => U | PromiseLike): Bluebird; + catch(predicate: Object, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Bluebird; + catch(predicate: Object, onReject: (error: any) => U | PromiseLike): Bluebird; } /* * Patch all static methods and the constructor */ interface PromiseConstructor { - new (callback: (resolve: (thenableOrResult?: T | Bluebird.Thenable) => void, reject: (error?: any) => void, onCancel?: (callback: () => void) => void) => void): Promise; + new (callback: (resolve: (thenableOrResult?: T | PromiseLike) => void, reject: (error?: any) => void, onCancel?: (callback: () => void) => void) => void): Promise; // all: typeof Bluebird.all; any: typeof Bluebird.any; diff --git a/types/bluebird-retry/index.d.ts b/types/bluebird-retry/index.d.ts index 63adc1476d..97d756524b 100644 --- a/types/bluebird-retry/index.d.ts +++ b/types/bluebird-retry/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/jut-io/bluebird-retry // Definitions by: Pascal Vomhoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/bluebird/bluebird-tests.ts b/types/bluebird/bluebird-tests.ts index c8fab7d57e..e616ae3f85 100644 --- a/types/bluebird/bluebird-tests.ts +++ b/types/bluebird/bluebird-tests.ts @@ -373,6 +373,30 @@ fooProm = fooProm.catch(CustomError, reason => { fooProm = fooProm.catch(CustomError1, CustomError2, CustomError3, error => {}); fooProm = fooProm.catch(CustomError1, CustomError2, CustomError3, CustomError4, error => {}); fooProm = fooProm.catch(CustomError1, CustomError2, CustomError3, CustomError4, CustomError5, error => {}); + + const booPredicate1 = (error: CustomError1) => true; + const booPredicate2 = (error: [number]) => true; + const booPredicate3 = (error: string) => true; + const booPredicate4 = (error: Object) => true; + const booPredicate5 = (error: any) => true; + + fooProm = fooProm.catch(booPredicate1, error => {}); + fooProm = fooProm.catch(booPredicate1, booPredicate2, error => {}); + fooProm = fooProm.catch(booPredicate1, booPredicate2, booPredicate3, error => {}); + fooProm = fooProm.catch(booPredicate1, booPredicate2, booPredicate3, booPredicate4, error => {}); + fooProm = fooProm.catch(booPredicate1, booPredicate2, booPredicate3, booPredicate4, booPredicate5, error => {}); + + const booObject1 = new CustomError1(); + const booObject2 = [400, 500]; + const booObject3 = ["Error1", "Error2"]; + const booObject4 = {code: 400}; + const booObject5: any = null; + + fooProm = fooProm.catch(booObject1, error => {}); + fooProm = fooProm.catch(booObject1, booObject2, error => {}); + fooProm = fooProm.catch(booObject1, booObject2, booObject3, error => {}); + fooProm = fooProm.catch(booObject1, booObject2, booObject3, booObject4, error => {}); + fooProm = fooProm.catch(booObject1, booObject2, booObject3, booObject4, booObject5, error => {}); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/types/bluebird/index.d.ts b/types/bluebird/index.d.ts index 5d1d5cfc81..8482e5fe6e 100644 --- a/types/bluebird/index.d.ts +++ b/types/bluebird/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/petkaantonov/bluebird // Definitions by: Leonard Hecker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /*! * The code following this comment originates from: @@ -34,30 +35,29 @@ * THE SOFTWARE. */ -declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection { +declare class Bluebird implements PromiseLike, Bluebird.Inspection { /** * Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise. * If promise cancellation is enabled, passed in function will receive one more function argument `onCancel` that allows to register an optional cancellation callback. */ - constructor(callback: (resolve: (thenableOrResult?: R | Bluebird.Thenable) => void, reject: (error?: any) => void, onCancel?: (callback: () => void) => void) => void); + constructor(callback: (resolve: (thenableOrResult?: R | PromiseLike) => void, reject: (error?: any) => void, onCancel?: (callback: () => void) => void) => void); /** * Promises/A+ `.then()`. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. */ - then(onFulfill: (value: R) => U1 | Bluebird.Thenable, onReject: (error: any) => U2 | Bluebird.Thenable): Bluebird; - then(onFulfill: (value: R) => U | Bluebird.Thenable, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; - then(onFulfill: (value: R) => U | Bluebird.Thenable): Bluebird; - then(): Bluebird; + // Based on PromiseLike.then, but returns a Bluebird instance. + then(onFulfill?: (value: R) => U | Bluebird.Thenable, onReject?: (error: any) => U | Bluebird.Thenable): Bluebird; // For simpler signature help. + then(onfulfilled?: ((value: R) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): Bluebird; /** * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. * * Alias `.caught();` for compatibility with earlier ECMAScript version. */ - catch(onReject?: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; - caught(onReject?: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; - catch(onReject?: (error: any) => U | Bluebird.Thenable): Bluebird; - caught(onReject?: (error: any) => U | Bluebird.Thenable): Bluebird; + catch(onReject?: (error: any) => R | PromiseLike | void | PromiseLike): Bluebird; + caught(onReject?: (error: any) => R | PromiseLike | void | PromiseLike): Bluebird; + catch(onReject?: (error: any) => U | PromiseLike): Bluebird; + caught(onReject?: (error: any) => U | PromiseLike): Bluebird; /** * This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called. @@ -69,143 +69,263 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, - filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object, - filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object, - filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object, - filter5: (new (...args: any[]) => E5) | ((error: any) => boolean) | Object, - onReject: (error: E1 | E2 | E3 | E4 | E5) => R | Bluebird.Thenable | void | Bluebird.Thenable, + filter1: (new (...args: any[]) => E1), + filter2: (new (...args: any[]) => E2), + filter3: (new (...args: any[]) => E3), + filter4: (new (...args: any[]) => E4), + filter5: (new (...args: any[]) => E5), + onReject: (error: E1 | E2 | E3 | E4 | E5) => R | PromiseLike | void | PromiseLike, + ): Bluebird; + catch( + filter1: ((error: E1) => boolean) | (E1 & object), + filter2: ((error: E2) => boolean) | (E2 & object), + filter3: ((error: E3) => boolean) | (E3 & object), + filter4: ((error: E4) => boolean) | (E4 & object), + filter5: ((error: E5) => boolean) | (E5 & object), + onReject: (error: E1 | E2 | E3 | E4 | E5) => R | PromiseLike | void | PromiseLike, ): Bluebird; caught( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, - filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object, - filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object, - filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object, - filter5: (new (...args: any[]) => E5) | ((error: any) => boolean) | Object, - onReject: (error: E1 | E2 | E3 | E4 | E5) => R | Bluebird.Thenable | void | Bluebird.Thenable, + filter1: (new (...args: any[]) => E1), + filter2: (new (...args: any[]) => E2), + filter3: (new (...args: any[]) => E3), + filter4: (new (...args: any[]) => E4), + filter5: (new (...args: any[]) => E5), + onReject: (error: E1 | E2 | E3 | E4 | E5) => R | PromiseLike | void | PromiseLike, + ): Bluebird; + caught( + filter1: ((error: E1) => boolean) | (E1 & object), + filter2: ((error: E2) => boolean) | (E2 & object), + filter3: ((error: E3) => boolean) | (E3 & object), + filter4: ((error: E4) => boolean) | (E4 & object), + filter5: ((error: E5) => boolean) | (E5 & object), + onReject: (error: E1 | E2 | E3 | E4 | E5) => R | PromiseLike | void | PromiseLike, ): Bluebird; catch( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, - filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object, - filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object, - filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object, - filter5: (new (...args: any[]) => E5) | ((error: any) => boolean) | Object, - onReject: (error: E1 | E2 | E3 | E4 | E5) => U | Bluebird.Thenable, + filter1: (new (...args: any[]) => E1), + filter2: (new (...args: any[]) => E2), + filter3: (new (...args: any[]) => E3), + filter4: (new (...args: any[]) => E4), + filter5: (new (...args: any[]) => E5), + onReject: (error: E1 | E2 | E3 | E4 | E5) => U | PromiseLike | void | PromiseLike, + ): Bluebird; + catch( + filter1: ((error: E1) => boolean) | (E1 & object), + filter2: ((error: E2) => boolean) | (E2 & object), + filter3: ((error: E3) => boolean) | (E3 & object), + filter4: ((error: E4) => boolean) | (E4 & object), + filter5: ((error: E5) => boolean) | (E5 & object), + onReject: (error: E1 | E2 | E3 | E4 | E5) => U | PromiseLike, ): Bluebird; caught( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, - filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object, - filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object, - filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object, - filter5: (new (...args: any[]) => E5) | ((error: any) => boolean) | Object, - onReject: (error: E1 | E2 | E3 | E4 | E5) => U | Bluebird.Thenable, + filter1: (new (...args: any[]) => E1), + filter2: (new (...args: any[]) => E2), + filter3: (new (...args: any[]) => E3), + filter4: (new (...args: any[]) => E4), + filter5: (new (...args: any[]) => E5), + onReject: (error: E1 | E2 | E3 | E4 | E5) => U | PromiseLike, + ): Bluebird; + caught( + filter1: ((error: E1) => boolean) | (E1 & object), + filter2: ((error: E2) => boolean) | (E2 & object), + filter3: ((error: E3) => boolean) | (E3 & object), + filter4: ((error: E4) => boolean) | (E4 & object), + filter5: ((error: E5) => boolean) | (E5 & object), + onReject: (error: E1 | E2 | E3 | E4 | E5) => U | PromiseLike, ): Bluebird; catch( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, - filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object, - filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object, - filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object, - onReject: (error: E1 | E2 | E3 | E4) => R | Bluebird.Thenable | void | Bluebird.Thenable, + filter1: (new (...args: any[]) => E1), + filter2: (new (...args: any[]) => E2), + filter3: (new (...args: any[]) => E3), + filter4: (new (...args: any[]) => E4), + onReject: (error: E1 | E2 | E3 | E4) => R | PromiseLike | void | PromiseLike, + ): Bluebird; + catch( + filter1: ((error: E1) => boolean) | (E1 & object), + filter2: ((error: E2) => boolean) | (E2 & object), + filter3: ((error: E3) => boolean) | (E3 & object), + filter4: ((error: E4) => boolean) | (E4 & object), + onReject: (error: E1 | E2 | E3 | E4) => R | PromiseLike | void | PromiseLike, ): Bluebird; caught( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, - filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object, - filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object, - filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object, - onReject: (error: E1 | E2 | E3 | E4) => R | Bluebird.Thenable | void | Bluebird.Thenable, + filter1: (new (...args: any[]) => E1), + filter2: (new (...args: any[]) => E2), + filter3: (new (...args: any[]) => E3), + filter4: (new (...args: any[]) => E4), + onReject: (error: E1 | E2 | E3 | E4) => R | PromiseLike | void | PromiseLike, + ): Bluebird; + caught( + filter1: ((error: E1) => boolean) | (E1 & object), + filter2: ((error: E2) => boolean) | (E2 & object), + filter3: ((error: E3) => boolean) | (E3 & object), + filter4: ((error: E4) => boolean) | (E4 & object), + onReject: (error: E1 | E2 | E3 | E4) => R | PromiseLike | void | PromiseLike, ): Bluebird; catch( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, - filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object, - filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object, - filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object, - onReject: (error: E1 | E2 | E3 | E4) => U | Bluebird.Thenable, + filter1: (new (...args: any[]) => E1), + filter2: (new (...args: any[]) => E2), + filter3: (new (...args: any[]) => E3), + filter4: (new (...args: any[]) => E4), + onReject: (error: E1 | E2 | E3 | E4) => U | PromiseLike, + ): Bluebird; + catch( + filter1: ((error: E1) => boolean) | (E1 & object), + filter2: ((error: E2) => boolean) | (E2 & object), + filter3: ((error: E3) => boolean) | (E3 & object), + filter4: ((error: E4) => boolean) | (E4 & object), + onReject: (error: E1 | E2 | E3 | E4) => U | PromiseLike, ): Bluebird; caught( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, - filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object, - filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object, - filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object, - onReject: (error: E1 | E2 | E3 | E4) => U | Bluebird.Thenable, + filter1: (new (...args: any[]) => E1), + filter2: (new (...args: any[]) => E2), + filter3: (new (...args: any[]) => E3), + filter4: (new (...args: any[]) => E4), + onReject: (error: E1 | E2 | E3 | E4) => U | PromiseLike, + ): Bluebird; + caught( + filter1: ((error: E1) => boolean) | (E1 & object), + filter2: ((error: E2) => boolean) | (E2 & object), + filter3: ((error: E3) => boolean) | (E3 & object), + filter4: ((error: E4) => boolean) | (E4 & object), + onReject: (error: E1 | E2 | E3 | E4) => U | PromiseLike, ): Bluebird; catch( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, - filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object, - filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object, - onReject: (error: E1 | E2 | E3) => R | Bluebird.Thenable | void | Bluebird.Thenable, + filter1: (new (...args: any[]) => E1), + filter2: (new (...args: any[]) => E2), + filter3: (new (...args: any[]) => E3), + onReject: (error: E1 | E2 | E3) => R | PromiseLike | void | PromiseLike, + ): Bluebird; + catch( + filter1: ((error: E1) => boolean) | (E1 & object), + filter2: ((error: E2) => boolean) | (E2 & object), + filter3: ((error: E3) => boolean) | (E3 & object), + onReject: (error: E1 | E2 | E3) => R | PromiseLike | void | PromiseLike, ): Bluebird; caught( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, - filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object, - filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object, - onReject: (error: E1 | E2 | E3) => R | Bluebird.Thenable | void | Bluebird.Thenable, + filter1: (new (...args: any[]) => E1), + filter2: (new (...args: any[]) => E2), + filter3: (new (...args: any[]) => E3), + onReject: (error: E1 | E2 | E3) => R | PromiseLike | void | PromiseLike, + ): Bluebird; + caught( + filter1: ((error: E1) => boolean) | (E1 & object), + filter2: ((error: E2) => boolean) | (E2 & object), + filter3: ((error: E3) => boolean) | (E3 & object), + onReject: (error: E1 | E2 | E3) => R | PromiseLike | void | PromiseLike, ): Bluebird; catch( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, - filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object, - filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object, - onReject: (error: E1 | E2 | E3) => U | Bluebird.Thenable, + filter1: (new (...args: any[]) => E1), + filter2: (new (...args: any[]) => E2), + filter3: (new (...args: any[]) => E3), + onReject: (error: E1 | E2 | E3) => U | PromiseLike, + ): Bluebird; + catch( + filter1: ((error: E1) => boolean) | (E1 & object), + filter2: ((error: E2) => boolean) | (E2 & object), + filter3: ((error: E3) => boolean) | (E3 & object), + onReject: (error: E1 | E2 | E3) => U | PromiseLike, ): Bluebird; caught( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, - filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object, - filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object, - onReject: (error: E1 | E2 | E3) => U | Bluebird.Thenable, + filter1: (new (...args: any[]) => E1), + filter2: (new (...args: any[]) => E2), + filter3: (new (...args: any[]) => E3), + onReject: (error: E1 | E2 | E3) => U | PromiseLike, + ): Bluebird; + caught( + filter1: ((error: E1) => boolean) | (E1 & object), + filter2: ((error: E2) => boolean) | (E2 & object), + filter3: ((error: E3) => boolean) | (E3 & object), + onReject: (error: E1 | E2 | E3) => U | PromiseLike, ): Bluebird; catch( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, - filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object, - onReject: (error: E1 | E2) => R | Bluebird.Thenable | void | Bluebird.Thenable, + filter1: (new (...args: any[]) => E1), + filter2: (new (...args: any[]) => E2), + onReject: (error: E1 | E2) => R | PromiseLike | void | PromiseLike, + ): Bluebird; + catch( + filter1: ((error: E1) => boolean) | (E1 & object), + filter2: ((error: E2) => boolean) | (E2 & object), + onReject: (error: E1 | E2) => R | PromiseLike | void | PromiseLike, ): Bluebird; caught( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, - filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object, - onReject: (error: E1 | E2) => R | Bluebird.Thenable | void | Bluebird.Thenable, + filter1: (new (...args: any[]) => E1), + filter2: (new (...args: any[]) => E2), + onReject: (error: E1 | E2) => R | PromiseLike | void | PromiseLike, + ): Bluebird; + caught( + filter1: ((error: E1) => boolean) | (E1 & object), + filter2: ((error: E2) => boolean) | (E2 & object), + onReject: (error: E1 | E2) => R | PromiseLike | void | PromiseLike, ): Bluebird; catch( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, - filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object, - onReject: (error: E1 | E2) => U | Bluebird.Thenable, + filter1: (new (...args: any[]) => E1), + filter2: (new (...args: any[]) => E2), + onReject: (error: E1 | E2) => U | PromiseLike, + ): Bluebird; + catch( + filter1: ((error: E1) => boolean) | (E1 & object), + filter2: ((error: E2) => boolean) | (E2 & object), + onReject: (error: E1 | E2) => U | PromiseLike, ): Bluebird; caught( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, - filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object, - onReject: (error: E1 | E2) => U | Bluebird.Thenable, + filter1: (new (...args: any[]) => E1), + filter2: (new (...args: any[]) => E2), + onReject: (error: E1 | E2) => U | PromiseLike, + ): Bluebird; + caught( + filter1: ((error: E1) => boolean) | (E1 & object), + filter2: ((error: E2) => boolean) | (E2 & object), + onReject: (error: E1 | E2) => U | PromiseLike, ): Bluebird; catch( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, - onReject: (error: E1) => R | Bluebird.Thenable | void | Bluebird.Thenable, + filter1: (new (...args: any[]) => E1), + onReject: (error: E1) => R | PromiseLike | void | PromiseLike, + ): Bluebird; + catch( + filter1: ((error: E1) => boolean) | (E1 & object), + onReject: (error: E1) => R | PromiseLike | void | PromiseLike, ): Bluebird; caught( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, - onReject: (error: E1) => R | Bluebird.Thenable | void | Bluebird.Thenable, + filter1: (new (...args: any[]) => E1), + onReject: (error: E1) => R | PromiseLike | void | PromiseLike, + ): Bluebird; + caught( + filter1: ((error: E1) => boolean) | (E1 & object), + onReject: (error: E1) => R | PromiseLike | void | PromiseLike, ): Bluebird; catch( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, - onReject: (error: E1) => U | Bluebird.Thenable, + filter1: (new (...args: any[]) => E1), + onReject: (error: E1) => U | PromiseLike, + ): Bluebird; + catch( + filter1: ((error: E1) => boolean) | (E1 & object), + onReject: (error: E1) => U | PromiseLike, ): Bluebird; caught( - filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, - onReject: (error: E1) => U | Bluebird.Thenable, + filter1: (new (...args: any[]) => E1), + onReject: (error: E1) => U | PromiseLike, + ): Bluebird; + caught( + filter1: ((error: E1) => boolean) | (E1 & object), + onReject: (error: E1) => U | PromiseLike, ): Bluebird; /** * Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections. */ - error(onReject: (reason: any) => U | Bluebird.Thenable): Bluebird; + error(onReject: (reason: any) => U | PromiseLike): Bluebird; /** * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler. * * Alias `.lastly();` for compatibility with earlier ECMAScript version. */ - finally(handler: () => U | Bluebird.Thenable): Bluebird; + finally(handler: () => U | PromiseLike): Bluebird; - lastly(handler: () => U | Bluebird.Thenable): Bluebird; + lastly(handler: () => U | PromiseLike): Bluebird; /** * Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise. @@ -215,19 +335,19 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection(onFulfilled?: (value: R) => U | Bluebird.Thenable, onRejected?: (error: any) => U | Bluebird.Thenable): void; + done(onFulfilled?: (value: R) => U | PromiseLike, onRejected?: (error: any) => U | PromiseLike): void; /** * Like `.finally()`, but not called for rejections. */ - tap(onFulFill: (value: R) => Bluebird.Thenable): Bluebird; + tap(onFulFill: (value: R) => PromiseLike): Bluebird; tap(onFulfill: (value: R) => U): Bluebird; /** * Like `.catch()` but rethrows the error * TODO: disallow non-objects */ - tapCatch(onReject: (error?: any) => U | Bluebird.Thenable): Bluebird; + tapCatch(onReject: (error?: any) => U | PromiseLike): Bluebird; tapCatch( filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, @@ -235,29 +355,29 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection E3) | ((error: any) => boolean) | Object, filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object, filter5: (new (...args: any[]) => E5) | ((error: any) => boolean) | Object, - onReject: (error: E1 | E2 | E3 | E4 | E5) => U | Bluebird.Thenable, + onReject: (error: E1 | E2 | E3 | E4 | E5) => U | PromiseLike, ): Bluebird; tapCatch( filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object, filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object, filter4: (new (...args: any[]) => E4) | ((error: any) => boolean) | Object, - onReject: (error: E1 | E2 | E3 | E4) => U | Bluebird.Thenable, + onReject: (error: E1 | E2 | E3 | E4) => U | PromiseLike, ): Bluebird; tapCatch( filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object, filter3: (new (...args: any[]) => E3) | ((error: any) => boolean) | Object, - onReject: (error: E1 | E2 | E3) => U | Bluebird.Thenable, + onReject: (error: E1 | E2 | E3) => U | PromiseLike, ): Bluebird; tapCatch( filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, filter2: (new (...args: any[]) => E2) | ((error: any) => boolean) | Object, - onReject: (error: E1 | E2) => U | Bluebird.Thenable, + onReject: (error: E1 | E2) => U | PromiseLike, ): Bluebird; tapCatch( filter1: (new (...args: any[]) => E1) | ((error: any) => boolean) | Object, - onReject: (error: E1) => U | Bluebird.Thenable, + onReject: (error: E1) => U | PromiseLike, ): Bluebird; /** @@ -488,7 +608,7 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection(fulfilledHandler: (...values: W[]) => U | Bluebird.Thenable): Bluebird; + spread(fulfilledHandler: (...values: W[]) => U | PromiseLike): Bluebird; spread(fulfilledHandler: Function): Bluebird; /** @@ -525,29 +645,29 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection(mapper: (item: Q, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + map(mapper: (item: Q, index: number, arrayLength: number) => U | PromiseLike, options?: Bluebird.ConcurrencyOption): Bluebird; /** * Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ // TODO type inference from array-resolving promise? - reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; + reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Bluebird; /** * Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ // TODO type inference from array-resolving promise? - filter(filterer: (item: U, index: number, arrayLength: number) => boolean | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + filter(filterer: (item: U, index: number, arrayLength: number) => boolean | PromiseLike, options?: Bluebird.ConcurrencyOption): Bluebird; /** * Same as calling ``Bluebird.each(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ - each(iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + each(iterator: (item: R, index: number, arrayLength: number) => U | PromiseLike): Bluebird; /** * Same as calling ``Bluebird.mapSeries(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ - mapSeries(iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + mapSeries(iterator: (item: R, index: number, arrayLength: number) => U | PromiseLike): Bluebird; /** * Cancel this `promise`. Will not do anything if this promise is already settled or if the cancellation feature has not been enabled @@ -568,8 +688,8 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection(fn: () => R | Bluebird.Thenable): Bluebird; - static attempt(fn: () => R | Bluebird.Thenable): Bluebird; + static try(fn: () => R | PromiseLike): Bluebird; + static attempt(fn: () => R | PromiseLike): Bluebird; /** * Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. @@ -581,7 +701,7 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection; - static resolve(value: R | Bluebird.Thenable): Bluebird; + static resolve(value: R | PromiseLike): Bluebird; /** * Create a promise that is rejected with the given `reason`. @@ -597,7 +717,7 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection(value: R | Bluebird.Thenable): Bluebird; + static cast(value: R | PromiseLike): Bluebird; /** * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. @@ -619,7 +739,7 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection(ms: number, value: R | Bluebird.Thenable): Bluebird; + static delay(ms: number, value: R | PromiseLike): Bluebird; static delay(ms: number): Bluebird; /** @@ -671,13 +791,13 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection(values: [Bluebird.Thenable | T1, Bluebird.Thenable | T2, Bluebird.Thenable | T3, Bluebird.Thenable | T4, Bluebird.Thenable | T5]): Bluebird<[T1, T2, T3, T4, T5]>; - static all(values: [Bluebird.Thenable | T1, Bluebird.Thenable | T2, Bluebird.Thenable | T3, Bluebird.Thenable | T4]): Bluebird<[T1, T2, T3, T4]>; - static all(values: [Bluebird.Thenable | T1, Bluebird.Thenable | T2, Bluebird.Thenable | T3]): Bluebird<[T1, T2, T3]>; - static all(values: [Bluebird.Thenable | T1, Bluebird.Thenable | T2]): Bluebird<[T1, T2]>; - static all(values: [Bluebird.Thenable | T1]): Bluebird<[T1]>; + static all(values: [PromiseLike | T1, PromiseLike | T2, PromiseLike | T3, PromiseLike | T4, PromiseLike | T5]): Bluebird<[T1, T2, T3, T4, T5]>; + static all(values: [PromiseLike | T1, PromiseLike | T2, PromiseLike | T3, PromiseLike | T4]): Bluebird<[T1, T2, T3, T4]>; + static all(values: [PromiseLike | T1, PromiseLike | T2, PromiseLike | T3]): Bluebird<[T1, T2, T3]>; + static all(values: [PromiseLike | T1, PromiseLike | T2]): Bluebird<[T1, T2]>; + static all(values: [PromiseLike | T1]): Bluebird<[T1]>; // array with values - static all(values: Bluebird.Thenable<(Bluebird.Thenable | R)[]> | (Bluebird.Thenable | R)[]): Bluebird; + static all(values: PromiseLike<(PromiseLike | R)[]> | (PromiseLike | R)[]): Bluebird; /** * Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason. @@ -695,14 +815,14 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection(values: Bluebird.Thenable<(Bluebird.Thenable | R)[]> | (Bluebird.Thenable | R)[]): Bluebird; + static any(values: PromiseLike<(PromiseLike | R)[]> | (PromiseLike | R)[]): Bluebird; /** * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value. * * **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending. */ - static race(values: Bluebird.Thenable<(Bluebird.Thenable | R)[]> | (Bluebird.Thenable | R)[]): Bluebird; + static race(values: PromiseLike<(PromiseLike | R)[]> | (PromiseLike | R)[]): Bluebird; /** * Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution. @@ -712,11 +832,11 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection(values: Bluebird.Thenable[]>, count: number): Bluebird; + static some(values: PromiseLike[]>, count: number): Bluebird; // promise of array with values - static some(values: Bluebird.Thenable, count: number): Bluebird; + static some(values: PromiseLike, count: number): Bluebird; // array with promises of value - static some(values: Bluebird.Thenable[], count: number): Bluebird; + static some(values: PromiseLike[], count: number): Bluebird; // array with values static some(values: R[], count: number): Bluebird; @@ -729,15 +849,15 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection(arg1: A1 | Bluebird.Thenable, handler: (arg1: A1) => R | Bluebird.Thenable): Bluebird; - static join(arg1: A1 | Bluebird.Thenable, arg2: A2 | Bluebird.Thenable, handler: (arg1: A1, arg2: A2) => R | Bluebird.Thenable): Bluebird; - static join(arg1: A1 | Bluebird.Thenable, arg2: A2 | Bluebird.Thenable, arg3: A3 | Bluebird.Thenable, handler: (arg1: A1, arg2: A2, arg3: A3) => R | Bluebird.Thenable): Bluebird; - static join(arg1: A1 | Bluebird.Thenable, arg2: A2 | Bluebird.Thenable, arg3: A3 | Bluebird.Thenable, arg4: A4 | Bluebird.Thenable, handler: (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => R | Bluebird.Thenable): Bluebird; - static join(arg1: A1 | Bluebird.Thenable, arg2: A2 | Bluebird.Thenable, arg3: A3 | Bluebird.Thenable, arg4: A4 | Bluebird.Thenable, arg5: A5 | Bluebird.Thenable, handler: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => R | Bluebird.Thenable): Bluebird; + static join(arg1: A1 | PromiseLike, handler: (arg1: A1) => R | PromiseLike): Bluebird; + static join(arg1: A1 | PromiseLike, arg2: A2 | PromiseLike, handler: (arg1: A1, arg2: A2) => R | PromiseLike): Bluebird; + static join(arg1: A1 | PromiseLike, arg2: A2 | PromiseLike, arg3: A3 | PromiseLike, handler: (arg1: A1, arg2: A2, arg3: A3) => R | PromiseLike): Bluebird; + static join(arg1: A1 | PromiseLike, arg2: A2 | PromiseLike, arg3: A3 | PromiseLike, arg4: A4 | PromiseLike, handler: (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => R | PromiseLike): Bluebird; + static join(arg1: A1 | PromiseLike, arg2: A2 | PromiseLike, arg3: A3 | PromiseLike, arg4: A4 | PromiseLike, arg5: A5 | PromiseLike, handler: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => R | PromiseLike): Bluebird; // variadic array /** @deprecated use .all instead */ - static join(...values: (R | Bluebird.Thenable)[]): Bluebird; + static join(...values: (R | PromiseLike)[]): Bluebird; /** * Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. @@ -747,16 +867,16 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection(values: Bluebird.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + static map(values: PromiseLike[]>, mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike, options?: Bluebird.ConcurrencyOption): Bluebird; // promise of array with values - static map(values: Bluebird.Thenable, mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + static map(values: PromiseLike, mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike, options?: Bluebird.ConcurrencyOption): Bluebird; // array with promises of value - static map(values: Bluebird.Thenable[], mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + static map(values: PromiseLike[], mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike, options?: Bluebird.ConcurrencyOption): Bluebird; // array with values - static map(values: R[], mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + static map(values: R[], mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike, options?: Bluebird.ConcurrencyOption): Bluebird; /** * Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. @@ -766,16 +886,16 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection(values: Bluebird.Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; + static reduce(values: PromiseLike[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Bluebird; // promise of array with values - static reduce(values: Bluebird.Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; + static reduce(values: PromiseLike, reducer: (total: U, current: R, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Bluebird; // array with promises of value - static reduce(values: Bluebird.Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; + static reduce(values: PromiseLike[], reducer: (total: U, current: R, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Bluebird; // array with values - static reduce(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; + static reduce(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Bluebird; /** * Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. @@ -785,16 +905,16 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection(values: Bluebird.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; + static filter(values: PromiseLike[]>, filterer: (item: R, index: number, arrayLength: number) => boolean | PromiseLike, option?: Bluebird.ConcurrencyOption): Bluebird; // promise of array with values - static filter(values: Bluebird.Thenable, filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; + static filter(values: PromiseLike, filterer: (item: R, index: number, arrayLength: number) => boolean | PromiseLike, option?: Bluebird.ConcurrencyOption): Bluebird; // array with promises of value - static filter(values: Bluebird.Thenable[], filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; + static filter(values: PromiseLike[], filterer: (item: R, index: number, arrayLength: number) => boolean | PromiseLike, option?: Bluebird.ConcurrencyOption): Bluebird; // array with values - static filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; + static filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean | PromiseLike, option?: Bluebird.ConcurrencyOption): Bluebird; /** * Iterate over an array, or a promise of an array, which contains promises (or a mix of promises and values) with the given iterator function with the signature (item, index, value) where item is the resolved value of a respective promise in the input array. Iteration happens serially. If any promise in the input array is rejected the returned promise is rejected as well. @@ -802,11 +922,11 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection(values: Bluebird.Thenable[]>, iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + static each(values: PromiseLike[]>, iterator: (item: R, index: number, arrayLength: number) => U | PromiseLike): Bluebird; // array with promises of value - static each(values: Bluebird.Thenable[], iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + static each(values: PromiseLike[], iterator: (item: R, index: number, arrayLength: number) => U | PromiseLike): Bluebird; // array with values OR promise of array with values - static each(values: R[] | Bluebird.Thenable, iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + static each(values: R[] | PromiseLike, iterator: (item: R, index: number, arrayLength: number) => U | PromiseLike): Bluebird; /** * Given an Iterable(arrays are Iterable), or a promise of an Iterable, which produces promises (or a mix of promises and values), iterate over all the values in the Iterable into an array and iterate over the array serially, in-order. @@ -815,7 +935,7 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection(values: (R | Bluebird.Thenable)[] | Bluebird.Thenable<(R | Bluebird.Thenable)[]>, iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + static mapSeries(values: (R | PromiseLike)[] | PromiseLike<(R | PromiseLike)[]>, iterator: (item: R, index: number, arrayLength: number) => U | PromiseLike): Bluebird; /** * A meta method used to specify the disposer method that cleans up a resource when using `Promise.using`. @@ -827,16 +947,16 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection) => void | Bluebird.Thenable): Bluebird.Disposer; + disposer(disposeFn: (arg: R, promise: Bluebird) => void | PromiseLike): Bluebird.Disposer; /** * In conjunction with `.disposer`, using will make sure that no matter what, the specified disposer * will be called when the promise returned by the callback passed to using has settled. The disposer is * necessary because there is no standard interface in node for disposing resources. */ - static using(disposer: Bluebird.Disposer, executor: (transaction: R) => Bluebird.Thenable): Bluebird; - static using(disposer: Bluebird.Disposer, disposer2: Bluebird.Disposer, executor: (transaction1: R1, transaction2: R2) => Bluebird.Thenable): Bluebird; - static using(disposer: Bluebird.Disposer, disposer2: Bluebird.Disposer, disposer3: Bluebird.Disposer, executor: (transaction1: R1, transaction2: R2, transaction3: R3) => Bluebird.Thenable): Bluebird; + static using(disposer: Bluebird.Disposer, executor: (transaction: R) => PromiseLike): Bluebird; + static using(disposer: Bluebird.Disposer, disposer2: Bluebird.Disposer, executor: (transaction1: R1, transaction2: R2) => PromiseLike): Bluebird; + static using(disposer: Bluebird.Disposer, disposer2: Bluebird.Disposer, disposer3: Bluebird.Disposer, executor: (transaction1: R1, transaction2: R2, transaction3: R3) => PromiseLike): Bluebird; /** * Add handler as the handler to call when there is a possibly unhandled rejection. @@ -891,7 +1011,7 @@ declare namespace Bluebird { suffix?: string; filter?: (name: string, func: Function, target?: any, passesDefaultFilter?: boolean) => boolean; // The promisifier gets a reference to the original method and should return a function which returns a promise - promisifier?: (originalMethod: Function) => () => Thenable; + promisifier?: (originalMethod: Function) => () => PromiseLike; } /** @@ -951,10 +1071,8 @@ declare namespace Bluebird { export class Disposer { } - export interface Thenable { - then(onFulfilled: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; - then(onFulfilled: (value: R) => U | Thenable, onRejected?: (error: any) => void | Thenable): Thenable; - } + /** @deprecated Use PromiseLike directly. */ + export type Thenable = PromiseLike; export interface Resolver { /** diff --git a/types/body-parser/index.d.ts b/types/body-parser/index.d.ts index 54a9b463ed..be10668973 100644 --- a/types/body-parser/index.d.ts +++ b/types/body-parser/index.d.ts @@ -21,7 +21,7 @@ declare namespace bodyParser { } interface OptionsJson extends Options { - reviever?(key: string, value: any): any; + reviver?(key: string, value: any): any; strict?: boolean; } diff --git a/types/bookshelf/index.d.ts b/types/bookshelf/index.d.ts index a7c0a90536..55be61ba9e 100644 --- a/types/bookshelf/index.d.ts +++ b/types/bookshelf/index.d.ts @@ -2,7 +2,7 @@ // Project: http://bookshelfjs.org/ // Definitions by: Andrew Schurman , Vesa Poikajärvi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import Knex = require('knex'); import knex = require('knex'); diff --git a/types/bootstrap-slider/bootstrap-slider-tests.ts b/types/bootstrap-slider/bootstrap-slider-tests.ts index 0f5af284ea..8b59a25a36 100644 --- a/types/bootstrap-slider/bootstrap-slider-tests.ts +++ b/types/bootstrap-slider/bootstrap-slider-tests.ts @@ -1,119 +1,146 @@ import $ = require('jquery'); -$(function() { +$(() => { // examples from http://seiyria.github.io/bootstrap-slider/ $('#ex1').slider({ - formatter: function(value) { + formatter(value) { return 'Current value: ' + value; } }); + $('#ex2').slider({}); - - $("#ex2").slider({}); - - var RGBChange = function() { - $('#RGB').css('background', 'rgb('+r.getValue()+','+g.getValue()+','+b.getValue()+')') + const RGBChange = () => { + $('#RGB').css('background', 'rgb(' + r.getValue() + ',' + g.getValue() + ',' + b.getValue() + ')'); }; - var r = $('#R').slider() - .on('slide', RGBChange) - .data('slider'); - var g = $('#G').slider() - .on('slide', RGBChange) - .data('slider'); - var b = $('#B').slider() - .on('slide', RGBChange) - .data('slider'); + const r = $('#R').slider() + .on('slide', RGBChange) + .data('slider'); + const g = $('#G').slider() + .on('slide', RGBChange) + .data('slider'); + const b = $('#B').slider() + .on('slide', RGBChange) + .data('slider'); - - - $("#ex4").slider({ - reversed : true + $('#ex4').slider({ + reversed: true }); + $('#ex5').slider(); - - $("#ex5").slider(); - - $("#destroyEx5Slider").click(function() { - $("#ex5").slider('destroy'); + $('#destroyEx5Slider').click(() => { + $('#ex5').slider('destroy'); }); - - - $("#ex6").slider(); - $("#ex6").on("slide", function(slideEvt) { - $("#ex6SliderVal").text(slideEvt.value); + $('#ex6').slider(); + $('#ex6').on('slide', (slideEvt) => { + $('#ex6SliderVal').text( slideEvt.value); }); + $('#ex7').slider(); - - $("#ex7").slider(); - - $("#ex7-enabled").click(function() { - if((this as HTMLInputElement).checked) { + $('#ex7-enabled').click(function(this: HTMLInputElement) { + if (this.checked) { // With JQuery - $("#ex7").slider("enable"); - } - else { + $('#ex7').slider('enable'); + } else { // With JQuery - $("#ex7").slider("disable"); + $('#ex7').slider('disable'); } }); - - - $("#ex8").slider({ + $('#ex8').slider({ tooltip: 'always' }); - - - $("#ex9").slider({ + $('#ex9').slider({ precision: 2, value: 8.115 // Slider will instantiate showing 8.12 due to specified precision }); + $('#ex11').slider({ step: 20000, min: 0, max: 200000 }); + $('#ex12a').slider({ id: 'slider12a', min: 0, max: 10, value: 5 }); + $('#ex12b').slider({ id: 'slider12b', min: 0, max: 10, range: true, value: [3, 7] }); + $('#ex12c').slider({ id: 'slider12c', min: 0, max: 10, range: true, value: [3, 7] }); - $("#ex11").slider({step: 20000, min: 0, max: 200000}); - - - - $("#ex12a").slider({ id: "slider12a", min: 0, max: 10, value: 5 }); - $("#ex12b").slider({ id: "slider12b", min: 0, max: 10, range: true, value: [3, 7] }); - $("#ex12c").slider({ id: "slider12c", min: 0, max: 10, range: true, value: [3, 7] }); - - - - $("#ex13").slider({ + $('#ex13').slider({ ticks: [0, 100, 200, 300, 400], ticks_labels: ['$0', '$100', '$200', '$300', '$400'], ticks_snap_bounds: 30 }); - - - $("#ex14").slider({ + $('#ex14').slider({ ticks: [0, 100, 200, 300, 400], ticks_positions: [0, 30, 60, 70, 90, 100], ticks_labels: ['$0', '$100', '$200', '$300', '$400'], ticks_snap_bounds: 30 }); - - - $("#ex15").slider({ + $('#ex15').slider({ min: 1000, max: 10000000, scale: 'logarithmic', step: 10 }); + $('#ex16a').slider({ min: 0, max: 10, value: 0, focus: true }); + $('#ex16b').slider({ min: 0, max: 10, value: [0, 10], focus: true }); + // examples from https://github.com/seiyria/bootstrap-slider/blob/master/README.md - $("#ex16a").slider({ min: 0, max: 10, value: 0, focus: true }); - $("#ex16b").slider({ min: 0, max: 10, value: [0, 10], focus: true }); + { + // Instantiate a slider + const mySlider = $('input.slider').slider(); + + // Call a method on the slider + const value = mySlider.slider('getValue'); + + // For non-getter methods, you can chain together commands + mySlider + .slider('setValue', 5) + .slider('setValue', 7); + } + + { // Instantiate a slider + const mySlider = $('input.slider').bootstrapSlider(); + + // Call a method on the slider + const value = mySlider.bootstrapSlider('getValue'); + + // For non-getter methods, you can chain together commands + mySlider + .bootstrapSlider('setValue', 5) + .bootstrapSlider('setValue', 7); + } + + { + // Instantiate a slider + const mySlider = $('input.slider').bootstrapSlider(); + + // Call a method on the slider + const value = mySlider.bootstrapSlider('getValue'); + + // For non-getter methods, you can chain together commands + mySlider + .bootstrapSlider('setValue', 5) + .bootstrapSlider('setValue', 7); + } + + { // Instantiate a slider + const mySlider = new Slider('input.slider', { + // initial options object + }); + + // Call a method on the slider + const value = mySlider.getValue(); + + // For non-getter methods, you can chain together commands + mySlider + .setValue(5) + .setValue(7); + } }); diff --git a/types/bootstrap-slider/index.d.ts b/types/bootstrap-slider/index.d.ts index f2fc21c9df..557c7aa5ad 100644 --- a/types/bootstrap-slider/index.d.ts +++ b/types/bootstrap-slider/index.d.ts @@ -1,7 +1,11 @@ -// Type definitions for bootstrap-slider.js 4.8.3 +// Type definitions for bootstrap-slider.js 9.8 // Project: https://github.com/seiyria/bootstrap-slider // Definitions by: Daniel Beckwith +// Leonard Thieu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// interface SliderOptions { /** @@ -38,7 +42,7 @@ interface SliderOptions { * Default: 5 * initial value. Use array to have a range slider. */ - value?: number|number[]; + value?: number | number[]; /** * Default: false * make range slider. Optional if initial value is an array. If initial value is scalar, max will be used for second value. @@ -79,10 +83,12 @@ interface SliderOptions { * formatter callback. Return the value wanted to be displayed in the tooltip * @param val the current value to display */ - formatter?(val:number): string; + formatter?(val: number): string; /** * Default: false - * The natural order is used for the arrow keys. Arrow up select the upper slider value for vertical sliders, arrow right the righter slider value for a horizontal slider - no matter if the slider was reversed or not. By default the arrow keys are oriented by arrow up/right to the higher slider value, arrow down/left to the lower slider value. + * The natural order is used for the arrow keys. Arrow up select the upper slider value for vertical sliders, + * arrow right the righter slider value for a horizontal slider - no matter if the slider was reversed or not. + * By default the arrow keys are oriented by arrow up/right to the higher slider value, arrow down/left to the lower slider value. */ natural_arrow_keys?: boolean; /** @@ -118,12 +124,19 @@ interface SliderOptions { } interface JQuery { + slider: SliderPlugin; + bootstrapSlider: SliderPlugin; + + on(event: 'slide', handler: (slideEvt: SliderEvent) => false | void): this; +} + +interface SliderPlugin { + (methodName: string, ...args: any[]): TJQuery; /** * Creates a slider from the current element. * @param options */ - slider(options?:SliderOptions): JQuery; - slider(methodName:string, ...args:any[]): JQuery; + (options?: SliderOptions): TJQuery; } interface ChangeValue { @@ -131,46 +144,42 @@ interface ChangeValue { newValue: number; } -interface JQueryEventObject { - value: number|ChangeValue; +interface SliderEvent extends JQuery.Event { + value: number | ChangeValue; } -interface SliderStatics { - new (selector: string, opts: SliderOptions): Slider; - prototype: Slider; -} - -declare var Slider: SliderStatics; - /** * This class is actually not used when using the jQuery version of bootstrap-slider * The method documentation is still here thouh. * When using jQuery, slider methods like setValue(3, true) have to be called like $slider.slider('setValue', 3, true) */ -interface Slider extends JQuery { +declare class Slider { + constructor(selector: string, opts: SliderOptions); + /** * Get the current value from the slider */ getValue(): number; /** - * Set a new value for the slider. If optional triggerSlideEvent parameter is true, 'slide' events will be triggered. If optional triggerChangeEvent parameter is true, 'change' events will be triggered. + * Set a new value for the slider. If optional triggerSlideEvent parameter is true, 'slide' events will be triggered. + * If optional triggerChangeEvent parameter is true, 'change' events will be triggered. * @param newValue * @param triggerSlideEvent * @param triggerChangeEvent */ - setValue(newValue:number, triggerSlideEvent?:boolean, triggerChangeEvent?:boolean): void; + setValue(newValue: number, triggerSlideEvent?: boolean, triggerChangeEvent?: boolean): this; /** * Properly clean up and remove the slider instance */ - destroy(): void; + destroy(): this; /** * Disables the slider and prevents the user from changing the value */ - disable(): void; + disable(): this; /** * Enables the slider */ - enable(): void; + enable(): this; /** * Returns true if enabled, false if disabled */ @@ -180,26 +189,18 @@ interface Slider extends JQuery { * @param attribute * @param value */ - setAttribute(attribute:string, value:any): void; + setAttribute(attribute: string, value: any): this; /** * Get the slider's attributes * @param attribute */ - getAttribute(attribute:string): any; + getAttribute(attribute: string): any; /** * Refreshes the current slider */ - refresh(): void; + refresh(): this; /** * Renders the tooltip again, after initialization. Useful in situations when the slider and tooltip are initially hidden. */ - relayout(): void; - on: { - (eventType:string, callback:(eventObject:JQueryEventObject, ...args:any[]) => any): Slider; - (eventType:string, data:any, callback:(eventObject:JQueryEventObject, ...args:any[]) => any): Slider; - (eventType:string, selector:string, callback:(eventObject:JQueryEventObject, ...eventData:any[]) => any): Slider; - (eventType:string, selector:string, data:any, callback:(eventObject:JQueryEventObject, ...eventData:any[]) => any): Slider; - (eventType:{ [key: string]: any; }, selector?:string, data?:any): Slider; - (eventType:{ [key: string]: any; }, data?:any): Slider; - } + relayout(): this; } diff --git a/types/bootstrap-slider/tsconfig.json b/types/bootstrap-slider/tsconfig.json index f5e65153f5..a793a1d164 100644 --- a/types/bootstrap-slider/tsconfig.json +++ b/types/bootstrap-slider/tsconfig.json @@ -6,17 +6,12 @@ "dom" ], "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, + "noImplicitThis": true, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" ], - "paths": { - "jquery": [ - "jquery/v2" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/bootstrap-slider/tslint.json b/types/bootstrap-slider/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/bootstrap-slider/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/browserify/index.d.ts b/types/browserify/index.d.ts index 6d03c76efe..8b51a34dd5 100644 --- a/types/browserify/index.d.ts +++ b/types/browserify/index.d.ts @@ -36,13 +36,22 @@ interface FileOptions { // for each file in a bundle. type InputFile = string | NodeJS.ReadableStream | FileOptions; +/** + * Core options pertaining to a Browserify instance, extended by user options + */ +interface CustomOptions { + /** + * Custom properties can be defined on Options. + * These options are forwarded along to module-deps and browser-pack directly. + */ + [propName: string]: any; + /** the directory that Browserify starts bundling from for filenames that start with .. */ + basedir?: string; +} /** * Options pertaining to a Browserify instance. */ -interface Options { - // Custom properties can be defined on Options. - // These options are forwarded along to module-deps and browser-pack directly. - [propName: string]: any; +interface Options extends CustomOptions { // String, file object, or array of those types (they may be mixed) specifying entry file(s). entries?: InputFile | InputFile[]; // an array which will skip all require() and global parsing for each file in the array. @@ -51,8 +60,6 @@ interface Options { // an array of optional extra extensions for the module lookup machinery to use when the extension has not been specified. // By default Browserify considers only .js and .json files in such cases. extensions?: string[]; - // the directory that Browserify starts bundling from for filenames that start with .. - basedir?: string; // an array of directories that Browserify searches when looking for modules which are not referenced using relative path. // Can be absolute or relative to basedir. Equivalent of setting NODE_PATH environmental variable when calling Browserify command. paths?: string[]; @@ -115,32 +122,32 @@ interface BrowserifyObject extends NodeJS.EventEmitter { * If file is an array, each item in file will be externalized. * If file is another bundle, that bundle's contents will be read and excluded from the current bundle as the bundle in file gets bundled. */ - external(file: string[], opts?: { basedir?: string }): BrowserifyObject; - external(file: string, opts?: { basedir?: string }): BrowserifyObject; + external(file: string[], opts?: CustomOptions): BrowserifyObject; + external(file: string, opts?: CustomOptions): BrowserifyObject; external(file: BrowserifyObject): BrowserifyObject; /** * Prevent the module name or file at file from showing up in the output bundle. * Instead you will get a file with module.exports = {}. */ - ignore(file: string, opts?: { basedir?: string }): BrowserifyObject; + ignore(file: string, opts?: CustomOptions): BrowserifyObject; /** * Prevent the module name or file at file from showing up in the output bundle. * If your code tries to require() that file it will throw unless you've provided another mechanism for loading it. */ - exclude(file: string, opts?: { basedir?: string }): BrowserifyObject; + exclude(file: string, opts?: CustomOptions): BrowserifyObject; /** * Transform source code before parsing it for require() calls with the transform function or module name tr. * If tr is a function, it will be called with tr(file) and it should return a through-stream that takes the raw file contents and produces the transformed source. * If tr is a string, it should be a module name or file path of a transform module */ - transform(tr: string, opts?: T): BrowserifyObject; - transform(tr: (file: string, opts: T) => NodeJS.ReadWriteStream, opts?: T): BrowserifyObject; + transform(tr: string, opts?: T): BrowserifyObject; + transform(tr: (file: string, opts: T) => NodeJS.ReadWriteStream, opts?: T): BrowserifyObject; /** * Register a plugin with opts. Plugins can be a string module name or a function the same as transforms. * plugin(b, opts) is called with the Browserify instance b. */ - plugin(plugin: string, opts?: T): BrowserifyObject; - plugin(plugin: (b: BrowserifyObject, opts: T) => any, opts?: T): BrowserifyObject; + plugin(plugin: string, opts?: T): BrowserifyObject; + plugin(plugin: (b: BrowserifyObject, opts: T) => any, opts?: T): BrowserifyObject; /** * Reset the pipeline back to a normal state. This function is called automatically when bundle() is called multiple times. * This function triggers a 'reset' event. diff --git a/types/bunyan-config/index.d.ts b/types/bunyan-config/index.d.ts index 49b642eaa1..0ff84fd9d2 100644 --- a/types/bunyan-config/index.d.ts +++ b/types/bunyan-config/index.d.ts @@ -7,6 +7,23 @@ declare module "bunyan-config" { import * as bunyan from "bunyan"; + interface StreamConfiguration { + name: string, + params?: { + host: string, + port: number + } + } + + interface Stream { + type?: string; + level?: bunyan.LogLevel; + path?: string; + stream?: string | StreamConfiguration + closeOnExit?: boolean; + period?: string; + count?: number; + } /** * Configuration. @@ -14,7 +31,7 @@ declare module "bunyan-config" { */ interface Configuration { name: string; - streams?: bunyan.Stream[]; + streams?: Stream[]; level?: string | number; stream?: NodeJS.WritableStream; serializers?: {}; diff --git a/types/chai-enzyme/chai-enzyme-tests.tsx b/types/chai-enzyme/chai-enzyme-tests.tsx index 8fc64e2711..77ad5a0169 100644 --- a/types/chai-enzyme/chai-enzyme-tests.tsx +++ b/types/chai-enzyme/chai-enzyme-tests.tsx @@ -5,7 +5,7 @@ import { shallow } from "enzyme"; const Test = () =>
; -class Test2 extends React.Component<{}, {}> { +class Test2 extends React.Component { render() { return
; } diff --git a/types/chai-enzyme/index.d.ts b/types/chai-enzyme/index.d.ts index 92c5817504..86b6f6f7b3 100644 --- a/types/chai-enzyme/index.d.ts +++ b/types/chai-enzyme/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/producthunt/chai-enzyme // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 /// diff --git a/types/chai/chai-tests.ts b/types/chai/chai-tests.ts index 69353163cd..31802ca303 100644 --- a/types/chai/chai-tests.ts +++ b/types/chai/chai-tests.ts @@ -1017,6 +1017,24 @@ function sameDeepMembers() { assert.sameDeepMembers([{ id: 5 }, { id: 4 }], [{ id: 4 }, { id: 5 }]); } +function orderedMembers() { + expect([1, 2]).to.have.ordered.members([1, 2]).but.not.have.ordered.members([2, 1]); + expect([1, 2, 3]).to.include.ordered.members([1, 2]).but.not.include.ordered.members([2, 3]); + expect([1, 2, 3]).to.have.ordered.members([1, 2, 3]); + expect([1, 2, 3]).to.have.members([2, 1, 3]).but.not.ordered.members([2, 1, 3]); + expect([{a: 1}, {b: 2}, {c: 3}]).to.include.deep.ordered.members([{a: 1}, {b: 2}]).but.not.include.deep.ordered.members([{b: 2}, {c: 3}]); + + assert.sameOrderedMembers([ 1, 2, 3 ], [ 1, 2, 3 ], 'same ordered members'); + assert.notSameOrderedMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'not same ordered members'); + assert.sameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 }, { c: 3 } ], 'same deep ordered members'); + assert.notSameDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { a: 1 }, { c: 3 } ], 'not same deep ordered members'); + + assert.includeOrderedMembers([ 1, 2, 3 ], [ 1, 2 ], 'include ordered members'); + assert.notIncludeOrderedMembers([ 1, 2, 3 ], [ 2, 1 ], 'not include ordered members'); + assert.includeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { a: 1 }, { b: 2 } ], 'include deep ordered members'); + assert.notIncludeDeepOrderedMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { c: 3 } ], 'not include deep ordered members'); +} + function members() { expect([5, 4]).members([4, 5]); expect([5, 4]).members([5, 4]); diff --git a/types/chai/index.d.ts b/types/chai/index.d.ts index b9a079af86..20f3c2b7df 100644 --- a/types/chai/index.d.ts +++ b/types/chai/index.d.ts @@ -61,6 +61,7 @@ declare namespace Chai { interface Assertion extends LanguageChains, NumericComparison, TypeComparison { not: Assertion; deep: Deep; + ordered: Ordered; nested: Nested; any: KeyFilter; all: KeyFilter; @@ -134,6 +135,8 @@ declare namespace Chai { at: Assertion; of: Assertion; same: Assertion; + but: Assertion; + does: Assertion; } interface NumericComparison { @@ -181,6 +184,11 @@ declare namespace Chai { include: Include; property: Property; members: Members; + ordered: Ordered; + } + + interface Ordered { + members: Members; } interface KeyFilter { @@ -213,6 +221,8 @@ declare namespace Chai { (value: string, message?: string): Assertion; (value: number, message?: string): Assertion; keys: Keys; + deep: Deep; + ordered: Ordered; members: Members; any: KeyFilter; all: KeyFilter; @@ -999,6 +1009,94 @@ declare namespace Chai { */ sameDeepMembers(set1: T[], set2: T[], message?: string): void; + /** + * Asserts that set1 and set2 have the same members in the same order. + * Uses a strict equality check (===). + * + * @type T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + sameOrderedMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 don’t have the same members in the same order. + * Uses a strict equality check (===). + * + * @type T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + notSameOrderedMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 have the same members in the same order. + * Uses a deep equality check. + * + * @type T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + sameDeepOrderedMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 don’t have the same members in the same order. + * Uses a deep equality check. + * + * @type T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + notSameDeepOrderedMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that subset is included in superset in the same order beginning with the first element in superset. + * Uses a strict equality check (===). + * + * @type T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + includeOrderedMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset isn’t included in superset in the same order beginning with the first element in superset. + * Uses a strict equality check (===). + * + * @type T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + notIncludeOrderedMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset is included in superset in the same order beginning with the first element in superset. + * Uses a deep equality check. + * + * @type T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + includeDeepOrderedMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset isn’t included in superset in the same order beginning with the first element in superset. + * Uses a deep equality check. + * + * @type T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + notIncludeDeepOrderedMembers(superset: T[], subset: T[], message?: string): void; + /** * Asserts that subset is included in superset. Order is not take into account. * diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index f56623e7b4..d567492602 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -358,7 +358,7 @@ declare namespace Chart { max?: number; } - type ChartColor = string | CanvasGradient | CanvasPattern; + type ChartColor = string | CanvasGradient | CanvasPattern | string[]; interface ChartDataSets { backgroundColor?: ChartColor | ChartColor[]; @@ -384,6 +384,10 @@ declare namespace Chart { pointStyle?: string | string[] | HTMLImageElement | HTMLImageElement[]; xAxisID?: string; yAxisID?: string; + type?: string; + hidden?: boolean; + hideInLegendAndTooltip?: boolean; + stack?: string; } interface ChartScales { diff --git a/types/codemirror/index.d.ts b/types/codemirror/index.d.ts index 9a74dc1e53..b42ebabae3 100644 --- a/types/codemirror/index.d.ts +++ b/types/codemirror/index.d.ts @@ -1097,7 +1097,7 @@ declare namespace CodeMirror { * Both modes get to parse all of the text, but when both assign a non-null style to a piece of code, the overlay wins, unless * the combine argument was true and not overridden, or state.overlay.combineTokens was true, in which case the styles are combined. */ - function overlayMode(base: Mode, overlay: Mode, combine?: boolean): Mode + function overlayMode(base: Mode, overlay: Mode, combine?: boolean): Mode; /** * async specifies that the lint process runs asynchronously. hasGutters specifies that lint errors should be displayed in the CodeMirror @@ -1114,13 +1114,20 @@ declare namespace CodeMirror { * linter. */ interface LintOptions extends LintStateOptions { - getAnnotations: AnnotationsCallback; + getAnnotations: Linter | AsyncLinter; + } + + /** + * A function that return errors found during the linting process. + */ + interface Linter { + (content: string, options: LintStateOptions, codeMirror: Editor): Annotation[] | PromiseLike; } /** * A function that calls the updateLintingCallback with any errors found during the linting process. */ - interface AnnotationsCallback { + interface AsyncLinter { (content: string, updateLintingCallback: UpdateLintingCallback, options: LintStateOptions, codeMirror: Editor): void; } diff --git a/types/codemirror/test/index.ts b/types/codemirror/test/index.ts index 41b7170fd1..e283abe974 100644 --- a/types/codemirror/test/index.ts +++ b/types/codemirror/test/index.ts @@ -28,7 +28,7 @@ var lintStateOptions: CodeMirror.LintStateOptions = { hasGutters: true }; -var lintOptions: CodeMirror.LintOptions = { +var asyncLintOptions: CodeMirror.LintOptions = { async: true, hasGutters: true, getAnnotations: (content: string, @@ -37,6 +37,14 @@ var lintOptions: CodeMirror.LintOptions = { codeMirror: CodeMirror.Editor) => {} }; +var syncLintOptions: CodeMirror.LintOptions = { + async: false, + hasGutters: true, + getAnnotations: (content: string, + options: CodeMirror.LintStateOptions, + codeMirror: CodeMirror.Editor): CodeMirror.Annotation[] => { return []; } +}; + var updateLintingCallback: CodeMirror.UpdateLintingCallback = (codeMirror: CodeMirror.Editor, annotations: CodeMirror.Annotation[]) => {}; diff --git a/types/collections/collections-tests.ts b/types/collections/collections-tests.ts new file mode 100644 index 0000000000..b7feef3c05 --- /dev/null +++ b/types/collections/collections-tests.ts @@ -0,0 +1,32 @@ +import SortedSet = require('collections/sorted-set'); + +interface Person { + name: string; +} + +let set = new SortedSet( + [{name: 'John'}, {name: 'Jack'}, {name: 'Linda'}], + (a: Person, b: Person) => a.name === b.name, + (a: Person, b: Person) => { + if (a.name < b.name) { + return -1; + } + if (a.name > b.name) { + return 1; + } + return 0; + } +); + +let p1: Person | undefined = set.max(); +let p2: Person | undefined = set.min(); + + +set.push({name: 'Laurie'}, {name: 'Max'}); +set.pop(); + +set.get({name: 'Laurie'}); +set.has({name: 'John'}); + +let a = 1; +set.forEach((p: Person) => a++); \ No newline at end of file diff --git a/types/collections/index.d.ts b/types/collections/index.d.ts new file mode 100644 index 0000000000..8a92df0f2d --- /dev/null +++ b/types/collections/index.d.ts @@ -0,0 +1,133 @@ +// Type definitions for collections v5.0.6 +// Project: http://www.collectionsjs.com/ +// Definitions by: Scarabe Dore +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'collections/sorted-set' { + namespace internal { + // TODO: These methods can be similar in others collection. One's should make some + // class model. + abstract class AbstractSet { + union(...plus: any[]): any; + intersection(...plus: any[]): any; + difference(...plus: any[]): any; + symmetricDifference(...plus: any[]): any; + remove(...plus: any[]): any; + contains(...plus: any[]): any; + toggle(...plus: any[]): any; + addEach(...plus: any[]): any; + deleteEach(...plus: any[]): any; + deleteAll(...plus: any[]): any; + findValue(...plus: any[]): any; + iterator(...plus: any[]): any; + forEach(...plus: any[]): any; + map(...plus: any[]): any; + + filter(...plus: any[]): any; + group(...plus: any[]): any; + some(...plus: any[]): any; + every(...plus: any[]): any; + any(...plus: any[]): any; + all(...plus: any[]): any; + only(...plus: any[]): any; + sorted(...plus: any[]): any; + reversed(...plus: any[]): any; + join(...plus: any[]): any; + sum(...plus: any[]): any; + average(...plus: any[]): any; + zip(...plus: any[]): any; + enumerate(...plus: any[]): any; + concat(...plus: any[]): any; + flatten(...plus: any[]): any; + toArray(...plus: any[]): any; + toObject(...plus: any[]): any; + toJSON(...plus: any[]): any; + equals(...plus: any[]): any; + clone(...plus: any[]): any; + contentCompare(...plus: any[]): any; + contentEquals(...plus: any[]): any; + sortedSetLog(...plus: any[]): any; + addRangeChangeListener(...plus: any[]): any; + removeRangeChangeListener(...plus: any[]): any; + dispatchRangeChange(...plus: any[]): any; + addBeforeRangeChangeListener(...plus: any[]): any; + removeBeforeRangeChangeListener(...plus: any[]): any; + dispatchBeforeRangeChange(...plus: any[]): any; + addOwnPropertyChangeListener(...plus: any[]): any; + addBeforeOwnPropertyChangeListener(...plus: any[]): any; + removeOwnPropertyChangeListener(...plus: any[]): any; + removeBeforeOwnPropertyChangeListener(...plus: any[]): any; + dispatchOwnPropertyChange(...plus: any[]): any; + dispatchBeforeOwnPropertyChange(...plus: any[]): any; + makePropertyObservable(...plus: any[]): any; + } + + class Node { + reduce(cb: (result?: any, val?: any, key?: any, collection?: any) => any, + basis: any, index: number, thisp: any, tree: any, depth: number): any; + touch(...plus: any[]): void; + checkIntegrity(...plus: any[]): number; + getNext(...plus: any[]): Node | undefined; + getPrevious(...plus: any[]): Node | undefined; + summary(...plus: any[]): string; + log(charmap: any, logNode: any, log: any, logAbove: any): any; + } + + class Iterator { + next(): {done: true, value: T | null | undefined}; + } + + export class SortedSet extends AbstractSet { + constructor( + values?: T[], + equals?: (a: T, b: T) => boolean, + compare?: (a: T, b: T) => number, + getDefault?: any + ); + constructClone(values?: T[]): SortedSet; + + add(value: T): boolean; + clear(): void; + ['delete'](value: T): boolean; + + find(value: T): Node | undefined; + findGreatest(n?: Node | undefined): Node | undefined; + findGreatestLessThan(value: T): Node | undefined; + findGreatestLessThanOrEqual(value: T): Node | undefined; + findLeast(n?: Node | undefined): Node | undefined; + findLeastGreaterThan(value: T): Node | undefined; + findLeastGreaterThanOrEqual(value: T): Node | undefined; + max(n?: Node): T | undefined; + min(n?: Node): T | undefined; + one(): T | undefined; + + get(elt: T): T | undefined; + has(elt: T): boolean; + indexOf(value: T): number; + + pop(): T | undefined; + push(...rest: T[]): void; + + shift(): T | undefined; + unshift(...rest: T[]): void; + + slice(start?: number, end?: number): T[]; + splice(start: Node, length: number, ...values: T[]): T[]; + swap(start: number, length: number, values?: T[]): T[]; + + splay(value: T): void; + splayIndex(index: number): boolean; + + reduce(callback: (result?: any, val?: any, key?: any, collection?: any) => any, + basis?: any, thisp?: any): any; + reduceRight( + callback: (result?: any, val?: any, key?: any, collection?: any) => any, + basis?: any, thisp?: any + ): any; + + iterate(start: number, stop: number): Iterator; + } + } + + export = internal.SortedSet; +} diff --git a/types/collections/tsconfig.json b/types/collections/tsconfig.json new file mode 100644 index 0000000000..6b5293a242 --- /dev/null +++ b/types/collections/tsconfig.json @@ -0,0 +1,16 @@ +{ + "files": [ + "collections-tests.ts", + "index.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": ["es6"], + "forceConsistentCasingInFileNames": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "noEmit": true + } +} diff --git a/types/commonmark/commonmark-tests.ts b/types/commonmark/commonmark-tests.ts index d298972f89..8d3a3a5447 100644 --- a/types/commonmark/commonmark-tests.ts +++ b/types/commonmark/commonmark-tests.ts @@ -1,9 +1,6 @@ - - import commonmark = require('commonmark'); function logNode(node: commonmark.Node) { - console.log( node.destination, node.firstChild, @@ -24,12 +21,10 @@ function logNode(node: commonmark.Node) { node.sourcepos, node.title, node.type); - } -var parser = new commonmark.Parser({ smart: true, time: true }); -var node = parser.parse('# a piece of _markdown_'); - +const parser = new commonmark.Parser({ smart: true, time: true }); +const node = parser.parse('# a piece of _markdown_'); let w = node.walker(); let step = w.next(); @@ -37,11 +32,75 @@ if (step.entering) { logNode(step.node); } - let xmlRenderer = new commonmark.XmlRenderer({ sourcepos: true, time: true }); let xml = xmlRenderer.render(node); console.log(xml); -let htmlRenderer = new commonmark.HtmlRenderer({ safe: true, smart: true, sourcepos: true, time: true}); +let htmlRenderer = new commonmark.HtmlRenderer({ safe: true, smart: true, sourcepos: true, time: true }); let html = htmlRenderer.render(node); -console.log(html); \ No newline at end of file +console.log(html); + +function basic_usage() { + const reader = new commonmark.Parser(); + const writer = new commonmark.HtmlRenderer(); + const parsed = reader.parse('Hello *world*'); // parsed is a 'Node' tree + // transform parsed if you like... + const result = writer.render(parsed); // result is a String +} + +function constructor_optional_options() { + const writer = new commonmark.HtmlRenderer({ sourcepos: true }); +} + +function soft_breaks_as_hard_breaks() { + const writer = new commonmark.HtmlRenderer(); + writer.softbreak = '
'; +} + +function soft_breaks_as_spaces() { + const writer = new commonmark.HtmlRenderer(); + writer.softbreak = ' '; +} + +function text_to_ALL_CAPS(parsed: commonmark.Node) { + const walker = parsed.walker(); + let event: commonmark.NodeWalkingStep; + let node: commonmark.Node; + + event = walker.next(); + while (event) { + node = event.node; + if (event.entering && node.type === 'text') { + node.literal = node.literal!.toUpperCase(); + } + event = walker.next(); + } +} + +function emphasis_to_ALL_CAPS(parsed: commonmark.Node) { + const walker = parsed.walker(); + let event: commonmark.NodeWalkingStep; + let node: commonmark.Node; + let inEmph = false; + + event = walker.next(); + while (event) { + node = event.node; + if (node.type === 'emph') { + if (event.entering) { + inEmph = true; + } else { + inEmph = false; + // add Emph node's children as siblings + while (node.firstChild) { + node.insertBefore(node.firstChild); + } + // remove the empty Emph node + node.unlink(); + } + } else if (inEmph && node.type === 'text') { + node.literal = node.literal!.toUpperCase(); + } + event = walker.next(); + } +} diff --git a/types/commonmark/index.d.ts b/types/commonmark/index.d.ts index bba8cd7e36..01b9541efa 100644 --- a/types/commonmark/index.d.ts +++ b/types/commonmark/index.d.ts @@ -1,212 +1,221 @@ -// Type definitions for commonmark.js 0.22.1 +// Type definitions for commonmark.js 0.27 // Project: https://github.com/jgm/commonmark.js // Definitions by: Nico Jansen +// Leonard Thieu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export = commonmark; -export as namespace commonmark; - -declare namespace commonmark { - - export interface NodeWalkingStep { - /** - * a boolean, which is true when we enter a Node from a parent or sibling, and false when we reenter it from a child - */ - entering: boolean; - /** - * The node belonging to this step - */ - node: Node; - } - - export interface NodeWalker { - /** - * Returns an object with properties entering and node. Returns null when we have finished walking the tree. - */ - next(): NodeWalkingStep; - /** - * Resets the iterator to resume at the specified node and setting for entering. (Normally this isn't needed unless you do destructive updates to the Node tree.) - */ - resumeAt(node: Node, entering?: boolean): void; - } - - export interface Position extends Array> { - } - - export interface ListData { - type?: string, - tight?: boolean, - delimiter?: string, - bulletChar?: string - } - - export class Node { - constructor(nodeType: string, sourcepos?: Position); - isContainer: boolean; - - /** - * (read-only): one of Text, Softbreak, Hardbreak, Emph, Strong, Html, Link, Image, Code, Document, Paragraph, BlockQuote, Item, List, Heading, CodeBlock, HtmlBlock ThematicBreak. - */ - type: string; - /** - * (read-only): a Node or null. - */ - firstChild: Node; - /** - * (read-only): a Node or null. - */ - lastChild: Node; - /** - * (read-only): a Node or null. - */ - next: Node; - /** - * (read-only): a Node or null. - */ - prev: Node; - /** - * (read-only): a Node or null. - */ - parent: Node; - /** - * (read-only): an Array with the following form: [[startline, startcolumn], [endline, endcolumn]] - */ - sourcepos: Position; - /** - * the literal String content of the node or null. - */ - literal: string; - /** - * link or image destination (String) or null. - */ - destination: string; - /** - * link or image title (String) or null. - */ - title: string; - /** - * fenced code block info string (String) or null. - */ - info: string; - /** - * heading level (Number). - */ - level: number; - /** - * either Bullet or Ordered (or undefined). - */ - listType: string; - /** - * true if list is tight - */ - listTight: boolean; - /** - * a Number, the starting number of an ordered list. - */ - listStart: number; - /** - * a String, either ) or . for an ordered list. - */ - listDelimiter: string; - /** - * used only for CustomBlock or CustomInline. - */ - onEnter: string; - /** - * used only for CustomBlock or CustomInline. - */ - onExit: string; - /** - * Append a Node child to the end of the Node's children. - */ - appendChild(child: Node): void; - /** - * Prepend a Node child to the beginning of the Node's children. - */ - prependChild(child: Node): void; - /** - * Remove the Node from the tree, severing its links with siblings and parents, and closing up gaps as needed. - */ - unlink(): void; - /** - * Insert a Node sibling after the Node. - */ - insertAfter(sibling: Node): void; - /** - * Insert a Node sibling before the Node. - */ - insertBefore(sibling: Node): void; - /** - * Returns a NodeWalker that can be used to iterate through the Node tree rooted in the Node - */ - walker(): NodeWalker; - /** - * Setting the backing object of listType, listTight, listStat and listDelimiter directly. - * Not needed unless creating list nodes directly. Should be fixed from v>0.22.1 - * https://github.com/jgm/commonmark.js/issues/74 - */ - _listData: ListData; - } +export class Node { + constructor(nodeType: string, sourcepos?: Position); /** - * Instead of converting Markdown directly to HTML, as most converters do, commonmark.js parses Markdown to an AST (abstract syntax tree), and then renders this AST as HTML. - * This opens up the possibility of manipulating the AST between parsing and rendering. For example, one could transform emphasis into ALL CAPS. + * (read-only): a String, one of text, softbreak, linebreak, emph, strong, html_inline, link, image, code, document, paragraph, + * block_quote, item, list, heading, code_block, html_block, thematic_break. */ - export class Parser { - /** - * Constructs a new Parser - */ - constructor(options?: ParserOptions); - parse(input: string): Node; - } + readonly type: 'text' | 'softbreak' | 'linebreak' | 'emph' | 'strong' | 'html_inline' | 'link' | 'image' | 'code' | 'document' | 'paragraph' | + 'block_quote' | 'item' | 'list' | 'heading' | 'code_block' | 'html_block' | 'thematic_break' | 'custom_inline' | 'custom_block'; + /** + * (read-only): a Node or null. + */ + readonly firstChild: Node | null; + /** + * (read-only): a Node or null. + */ + readonly lastChild: Node | null; + /** + * (read-only): a Node or null. + */ + readonly next: Node | null; + /** + * (read-only): a Node or null. + */ + readonly prev: Node | null; + /** + * (read-only): a Node or null. + */ + readonly parent: Node | null; + /** + * (read-only): an Array with the following form: [[startline, startcolumn], [endline, endcolumn]] + */ + readonly sourcepos: Position; + /** + * (read-only): true if the Node can contain other Nodes as children. + */ + readonly isContainer: boolean; + /** + * the literal String content of the node or null. + */ + literal: string | null; + /** + * link or image destination (String) or null. + */ + destination: string | null; + /** + * link or image title (String) or null. + */ + title: string | null; + /** + * fenced code block info string (String) or null. + */ + info: string | null; + /** + * heading level (Number). + */ + level: number; + /** + * either Bullet or Ordered (or undefined). + */ + listType: 'Bullet' | 'Ordered'; + /** + * true if list is tight + */ + listTight: boolean; + /** + * a Number, the starting number of an ordered list. + */ + listStart: number; + /** + * a String, either ) or . for an ordered list. + */ + listDelimiter: ')' | '.'; + /** + * used only for CustomBlock or CustomInline. + */ + onEnter: string; + /** + * used only for CustomBlock or CustomInline. + */ + onExit: string; - export interface ParserOptions { - /** - * if true, straight quotes will be made curly, -- will be changed to an en dash, --- will be changed to an em dash, and ... will be changed to ellipses. - */ - smart?: boolean; - time?: boolean; - } + /** + * Append a Node child to the end of the Node's children. + */ + appendChild(child: Node): void; - export interface HtmlRenderingOptions extends XmlRenderingOptions { - /** - * if true, raw HTML will not be passed through to HTML output (it will be replaced by comments), and potentially unsafe URLs in links and images (those beginning with javascript:, vbscript:, file:, and with a few exceptions data:) will be replaced with empty strings. - */ - safe?: boolean; - /** - * if true, straight quotes will be made curly, -- will be changed to an en dash, --- will be changed to an em dash, and ... will be changed to ellipses. - */ - smart?: boolean; - /** - * if true, source position information for block-level elements will be rendered in the data-sourcepos attribute (for HTML) or the sourcepos attribute (for XML). - */ - sourcepos?: boolean; - } + /** + * Prepend a Node child to the beginning of the Node's children. + */ + prependChild(child: Node): void; - export class HtmlRenderer { - constructor(options?: HtmlRenderingOptions) - render(root: Node): string; - /** - * Let's you override the softbreak properties of a renderer. So, to make soft breaks render as hard breaks in HTML: - * writer.softbreak = "
"; - */ - softbreak: string; - /** - * Override the function that will be used to escape (sanitize) the html output. Return value is used to add to the html output - * @param input the input to escape - * @param isAttributeValue indicates wheter or not the input value will be used as value of an html attribute. - */ - escape: (input: string, isAttributeValue: boolean) => string; - } + /** + * Remove the Node from the tree, severing its links with siblings and parents, and closing up gaps as needed. + */ + unlink(): void; - export interface XmlRenderingOptions { - time?: boolean; - sourcepos?: boolean; - } + /** + * Insert a Node sibling after the Node. + */ + insertAfter(sibling: Node): void; - export class XmlRenderer { - constructor(options?: XmlRenderingOptions) - render(root: Node): string; - } + /** + * Insert a Node sibling before the Node. + */ + insertBefore(sibling: Node): void; + /** + * Returns a NodeWalker that can be used to iterate through the Node tree rooted in the Node + */ + walker(): NodeWalker; + + /** + * Setting the backing object of listType, listTight, listStat and listDelimiter directly. + * Not needed unless creating list nodes directly. Should be fixed from v>0.22.1 + * https://github.com/jgm/commonmark.js/issues/74 + */ + _listData: ListData; +} + +/** + * Instead of converting Markdown directly to HTML, as most converters do, commonmark.js parses Markdown to an AST (abstract syntax tree), and then renders this AST as HTML. + * This opens up the possibility of manipulating the AST between parsing and rendering. For example, one could transform emphasis into ALL CAPS. + */ +export class Parser { + /** + * Constructs a new Parser + */ + constructor(options?: ParserOptions); + + parse(input: string): Node; +} + +export class HtmlRenderer { + constructor(options?: HtmlRenderingOptions) + + render(root: Node): string; + + /** + * Let's you override the softbreak properties of a renderer. So, to make soft breaks render as hard breaks in HTML: + * writer.softbreak = "
"; + */ + softbreak: string; + /** + * Override the function that will be used to escape (sanitize) the html output. Return value is used to add to the html output + * @param input the input to escape + * @param isAttributeValue indicates wheter or not the input value will be used as value of an html attribute. + */ + escape: (input: string, isAttributeValue: boolean) => string; +} + +export class XmlRenderer { + constructor(options?: XmlRenderingOptions) + + render(root: Node): string; +} +export interface NodeWalkingStep { + /** + * a boolean, which is true when we enter a Node from a parent or sibling, and false when we reenter it from a child + */ + entering: boolean; + /** + * The node belonging to this step + */ + node: Node; +} + +export interface NodeWalker { + /** + * Returns an object with properties entering and node. Returns null when we have finished walking the tree. + */ + next(): NodeWalkingStep; + /** + * Resets the iterator to resume at the specified node and setting for entering. (Normally this isn't needed unless you do destructive updates to the Node tree.) + */ + resumeAt(node: Node, entering?: boolean): void; +} + +export type Position = [[number, number], [number, number]]; + +export interface ListData { + type?: string; + tight?: boolean; + delimiter?: string; + bulletChar?: string; +} + +export interface ParserOptions { + /** + * if true, straight quotes will be made curly, -- will be changed to an en dash, --- will be changed to an em dash, and ... will be changed to ellipses. + */ + smart?: boolean; + time?: boolean; +} + +export interface HtmlRenderingOptions extends XmlRenderingOptions { + /** + * if true, raw HTML will not be passed through to HTML output (it will be replaced by comments), and potentially unsafe URLs in links and images + * (those beginning with javascript:, vbscript:, file:, and with a few exceptions data:) will be replaced with empty strings. + */ + safe?: boolean; + /** + * if true, straight quotes will be made curly, -- will be changed to an en dash, --- will be changed to an em dash, and ... will be changed to ellipses. + */ + smart?: boolean; + /** + * if true, source position information for block-level elements will be rendered in the data-sourcepos attribute (for HTML) or the sourcepos attribute (for XML). + */ + sourcepos?: boolean; +} + +export interface XmlRenderingOptions { + time?: boolean; + sourcepos?: boolean; } diff --git a/types/commonmark/tsconfig.json b/types/commonmark/tsconfig.json index e424e972ca..82e3004b78 100644 --- a/types/commonmark/tsconfig.json +++ b/types/commonmark/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -20,4 +20,4 @@ "index.d.ts", "commonmark-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/commonmark/tslint.json b/types/commonmark/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/commonmark/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/consolidate/index.d.ts b/types/consolidate/index.d.ts index 2a0adb1db9..bfe432214f 100644 --- a/types/consolidate/index.d.ts +++ b/types/consolidate/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/visionmedia/consolidate.js // Definitions by: Carlos Ballesteros Velasco , Theo Sherry , Nicolas Henry // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 // Imported from: https://github.com/soywiz/typescript-node-definitions/consolidate.d.ts diff --git a/types/content-type/content-type-tests.ts b/types/content-type/content-type-tests.ts index f173a1efbb..0705d440c1 100644 --- a/types/content-type/content-type-tests.ts +++ b/types/content-type/content-type-tests.ts @@ -1,19 +1,18 @@ import contentType = require('content-type'); import express = require('express'); -var obj = contentType.parse('image/svg+xml; charset=utf-8'); +let obj = contentType.parse('image/svg+xml; charset=utf-8'); console.log(obj.type); // => 'image/svg+xml' console.log(obj.parameters.charset); // => 'utf-8' - -var req: express.Request; +let req: express.Request; obj = contentType.parse(req); -var res: express.Response; +let res: express.Response; obj = contentType.parse(res); -var str: string = contentType.format({type: 'image/svg+xml'}); +let str: string = contentType.format({type: 'image/svg+xml'}); -var media: contentType.MediaType; +let media: contentType.MediaType; contentType.format(media); diff --git a/types/content-type/index.d.ts b/types/content-type/index.d.ts index 3dd39182f4..ec60de446f 100644 --- a/types/content-type/index.d.ts +++ b/types/content-type/index.d.ts @@ -1,16 +1,16 @@ -// Type definitions for content-type v1.0.1 +// Type definitions for content-type 1.1 // Project: https://www.npmjs.com/package/content-type // Definitions by: Hiroki Horiuchi // Definitions: https://github.com/borisyankov/DefinitelyTyped +import * as express from 'express'; + declare var ct: ct.StaticFunctions; export = ct; declare namespace ct { interface StaticFunctions { - parse(string: string): MediaType; - parse(req: { headers: any; }): MediaType; - parse(res: { getHeader(key: string): string; }): MediaType; + parse(input: express.Request | express.Response | string): MediaType; format(obj: MediaType): string; } diff --git a/types/content-type/tslint.json b/types/content-type/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/content-type/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cordova-plugin-inappbrowser/cordova-plugin-inappbrowser-tests.ts b/types/cordova-plugin-inappbrowser/cordova-plugin-inappbrowser-tests.ts index d717e85ea4..1497eec386 100644 --- a/types/cordova-plugin-inappbrowser/cordova-plugin-inappbrowser-tests.ts +++ b/types/cordova-plugin-inappbrowser/cordova-plugin-inappbrowser-tests.ts @@ -1,10 +1,10 @@ // InAppBrowser plugin -//---------------------------------------------------------------------- +// ---------------------------------------------------------------------- // signature of window.open() added by InAppBrowser plugin // is similar to native window.open signature, so the compiler can's // select proper overload, but we cast result to InAppBrowser manually. -var iab = window.open('google.com', '_self'); +const iab = window.open('google.com', '_self'); iab.addEventListener('loadstart', (ev: InAppBrowserEvent) => { console.log('Start opening ' + ev.url); }); iab.addEventListener('loadstart', (ev) => { console.log('loadstart' + ev.url); }); @@ -30,5 +30,5 @@ iab.removeEventListener('exit', inAppBrowserCallBack); iab.show(); iab.executeScript( { code: "console.log('Injected script in action')" }, - ()=> { console.log('Script is executed'); } -); \ No newline at end of file + () => { console.log('Script is executed'); } +); diff --git a/types/cordova-plugin-inappbrowser/index.d.ts b/types/cordova-plugin-inappbrowser/index.d.ts index 91dc61314f..b266fbab44 100644 --- a/types/cordova-plugin-inappbrowser/index.d.ts +++ b/types/cordova-plugin-inappbrowser/index.d.ts @@ -1,40 +1,14 @@ -// Type definitions for Apache Cordova InAppBrowser plugin +// Type definitions for Apache Cordova InAppBrowser plugin 1.7 // Project: https://github.com/apache/cordova-plugin-inappbrowser // Definitions by: Microsoft Open Technologies Inc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// +// // Copyright (c) Microsoft Open Technologies Inc // Licensed under the MIT license. // TypeScript Version: 2.3 +type channel = "loadstart" | "loadstop" | "loaderror" | "exit"; interface Window { - /** - * Opens a URL in a new InAppBrowser instance, the current browser instance, or the system browser. - * @param url The URL to load. - * @param target The target in which to load the URL, an optional parameter that defaults to _self. - * @param options Options for the InAppBrowser. Optional, defaulting to: location=yes. - * The options string must not contain any blank space, and each feature's - * name/value pairs must be separated by a comma. Feature names are case insensitive. - */ - open(url: string, target?: "_self", options?: string): InAppBrowser; - /** - * Opens a URL in a new InAppBrowser instance, the current browser instance, or the system browser. - * @param url The URL to load. - * @param target The target in which to load the URL, an optional parameter that defaults to _self. - * @param options Options for the InAppBrowser. Optional, defaulting to: location=yes. - * The options string must not contain any blank space, and each feature's - * name/value pairs must be separated by a comma. Feature names are case insensitive. - */ - open(url: string, target?: "_blank", options?: string): InAppBrowser; - /** - * Opens a URL in a new InAppBrowser instance, the current browser instance, or the system browser. - * @param url The URL to load. - * @param target The target in which to load the URL, an optional parameter that defaults to _self. - * @param options Options for the InAppBrowser. Optional, defaulting to: location=yes. - * The options string must not contain any blank space, and each feature's - * name/value pairs must be separated by a comma. Feature names are case insensitive. - */ - open(url: string, target?: "_system", options?: string): InAppBrowser; /** * Opens a URL in a new InAppBrowser instance, the current browser instance, or the system browser. * @param url The URL to load. @@ -51,10 +25,10 @@ interface Window { * NOTE: The InAppBrowser window behaves like a standard web browser, and can't access Cordova APIs. */ interface InAppBrowser extends Window { - onloadstart: (type: InAppBrowserEvent) => void; - onloadstop: (type: InAppBrowserEvent) => void; - onloaderror: (type: InAppBrowserEvent) => void; - onexit: (type: InAppBrowserEvent) => void; + onloadstart(type: InAppBrowserEvent): void; + onloadstop(type: InAppBrowserEvent): void; + onloaderror(type: InAppBrowserEvent): void; + onexit(type: InAppBrowserEvent): void; // addEventListener overloads /** * Adds a listener for an event from the InAppBrowser. @@ -65,7 +39,7 @@ interface InAppBrowser extends Window { * @param callback the function that executes when the event fires. The function is * passed an InAppBrowserEvent object as a parameter. */ - addEventListener(type: "loadstart" | "loadstop" | "loaderror" | "exit", callback: (event: InAppBrowserEvent) => void): void; + addEventListener(type: channel, callback: (event: InAppBrowserEvent) => void): void; // removeEventListener overloads /** * Removes a listener for an event from the InAppBrowser. @@ -77,7 +51,7 @@ interface InAppBrowser extends Window { * @param callback the function that executes when the event fires. The function is * passed an InAppBrowserEvent object as a parameter. */ - removeEventListener(type: "loadstart" | "loadstop" | "loaderror" | "exit", callback: (event: InAppBrowserEvent) => void): void; + removeEventListener(type: channel, callback: (event: InAppBrowserEvent) => void): void; /** Closes the InAppBrowser window. */ close(): void; /** Hides the InAppBrowser window. Calling this has no effect if the InAppBrowser was already hidden. */ @@ -96,29 +70,13 @@ interface InAppBrowser extends Window { * For multi-line scripts, this is the return value of the last statement, * or the last expression evaluated. */ - executeScript(script: { code: string }, callback: (result: any) => void): void; - /** - * Injects JavaScript code into the InAppBrowser window. - * @param script Details of the script to run, specifying either a file or code key. - * @param callback The function that executes after the JavaScript code is injected. - * If the injected script is of type code, the callback executes with - * a single parameter, which is the return value of the script, wrapped in an Array. - * For multi-line scripts, this is the return value of the last statement, - * or the last expression evaluated. - */ - executeScript(script: { file: string }, callback: (result: any) => void): void; + executeScript(script: { code: string } | { file: string }, callback: (result: any) => void): void; /** * Injects CSS into the InAppBrowser window. * @param css Details of the script to run, specifying either a file or code key. * @param callback The function that executes after the CSS is injected. */ - insertCSS(css: { code: string }, callback: () => void): void; - /** - * Injects CSS into the InAppBrowser window. - * @param css Details of the script to run, specifying either a file or code key. - * @param callback The function that executes after the CSS is injected. - */ - insertCSS(css: { file: string }, callback: () => void): void; + insertCSS(css: { code: string } | { file: string }, callback: () => void): void; } interface InAppBrowserEvent extends Event { @@ -130,4 +88,8 @@ interface InAppBrowserEvent extends Event { code: number; /** the error message, only in the case of loaderror. */ message: string; -} \ No newline at end of file +} + +interface Cordova { + InAppBrowser: InAppBrowser; +} diff --git a/types/cordova-plugin-inappbrowser/tslint.json b/types/cordova-plugin-inappbrowser/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cordova-plugin-inappbrowser/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cordova-plugin-x-socialsharing/cordova-plugin-x-socialsharing-tests.ts b/types/cordova-plugin-x-socialsharing/cordova-plugin-x-socialsharing-tests.ts index 62e44e3e77..ad8fa420a9 100644 --- a/types/cordova-plugin-x-socialsharing/cordova-plugin-x-socialsharing-tests.ts +++ b/types/cordova-plugin-x-socialsharing/cordova-plugin-x-socialsharing-tests.ts @@ -60,3 +60,4 @@ window.plugins.socialsharing.shareViaFacebook("Optional message, may be ignored window.plugins.socialsharing.share("Optional message", "Optional title", ["www/manual.pdf", "https://www.google.nl/images/srpr/logo4w.png"], "http://www.myurl.com"); window.plugins.socialsharing.saveToPhotoAlbum(["https://www.google.nl/images/srpr/logo4w.png", "www/image.gif"], function () { console.log("share ok") }, function (msg) { alert("error: " + msg) }); +window.plugins.socialsharing.shareWithOptions({"message":"sharethis","subject":"thesubject","files":["",""],"url":"https: //www.website.com/foo/#bar?a=b","chooserTitle":"Pickanapp"}, function () { console.log("share ok") }, function (msg) { alert("error: " + msg) }); diff --git a/types/cordova-plugin-x-socialsharing/index.d.ts b/types/cordova-plugin-x-socialsharing/index.d.ts index e68a072ee2..4560dd3f1a 100644 --- a/types/cordova-plugin-x-socialsharing/index.d.ts +++ b/types/cordova-plugin-x-socialsharing/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for SocialSharing-PhoneGap-Plugin v5.0.12 +// Type definitions for SocialSharing-PhoneGap-Plugin v5.1.8 // Project: https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin -// Definitions by: Markus Wagner +// Definitions by: Markus Wagner , Larry Bahr // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Window { @@ -18,6 +18,7 @@ declare module SocialSharingPlugin { subject?: string; files?: string | string[]; url?: string; + chooserTitle?: string; } interface ShareResult { diff --git a/types/core-js/core-js-tests.ts b/types/core-js/core-js-tests.ts index 3f585db33e..325ff56fc1 100644 --- a/types/core-js/core-js-tests.ts +++ b/types/core-js/core-js-tests.ts @@ -243,15 +243,15 @@ promiseLikeOfPoint = promiseLikeOfPoint.then(p => promiseLikeOfPoint); promiseLikeOfPoint = promiseLikeOfPoint.then(p => point, e => point); promiseLikeOfPoint = promiseLikeOfPoint.then(p => promiseLikeOfPoint, e => point); promiseLikeOfPoint = promiseLikeOfPoint.then(p => point, e => promiseLikeOfPoint); -promiseLikeOfPoint = promiseLikeOfPoint.then(p => point, e => { }); -promiseLikeOfPoint = promiseLikeOfPoint.then(p => promiseLikeOfPoint, e => { }); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => point, e => { throw e; }); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => promiseLikeOfPoint, e => { throw e; }); promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => point3d); promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => promiseLikeOfPoint3D); promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => point3d, e => point3d); promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => promiseLikeOfPoint3D, e => point3d); promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => point3d, e => promiseLikeOfPoint3D); -promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => point3d, e => { }); -promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => promiseLikeOfPoint3D, e => { }); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => point3d, e => { throw e; }); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => promiseLikeOfPoint3D, e => { throw e; }); promiseOfPoint.then((point: Point) => { }); promiseOfPoint = promiseOfPoint.then(); promiseOfPoint = promiseOfPoint.then(p => point); @@ -262,9 +262,9 @@ promiseOfPoint = promiseOfPoint.then(p => promiseOfPoint, e => point); promiseOfPoint = promiseOfPoint.then(p => promiseLikeOfPoint, e => point); promiseOfPoint = promiseOfPoint.then(p => point, e => promiseOfPoint); promiseOfPoint = promiseOfPoint.then(p => point, e => promiseLikeOfPoint); -promiseOfPoint = promiseOfPoint.then(p => point, e => { }); -promiseOfPoint = promiseOfPoint.then(p => promiseOfPoint, e => { }); -promiseOfPoint = promiseOfPoint.then(p => promiseLikeOfPoint, e => { }); +promiseOfPoint = promiseOfPoint.then(p => point, e => { throw e; }); +promiseOfPoint = promiseOfPoint.then(p => promiseOfPoint, e => { throw e; }); +promiseOfPoint = promiseOfPoint.then(p => promiseLikeOfPoint, e => { throw e; }); promiseOfPoint3D = promiseOfPoint.then(p => point3d); promiseOfPoint3D = promiseOfPoint.then(p => promiseOfPoint3D); promiseOfPoint3D = promiseOfPoint.then(p => promiseLikeOfPoint3D); @@ -273,16 +273,16 @@ promiseOfPoint3D = promiseOfPoint.then(p => promiseOfPoint3D, e => point3d); promiseOfPoint3D = promiseOfPoint.then(p => promiseLikeOfPoint3D, e => point3d); promiseOfPoint3D = promiseOfPoint.then(p => point3d, e => promiseOfPoint3D); promiseOfPoint3D = promiseOfPoint.then(p => point3d, e => promiseLikeOfPoint3D); -promiseOfPoint3D = promiseOfPoint.then(p => point3d, e => { }); -promiseOfPoint3D = promiseOfPoint.then(p => promiseOfPoint3D, e => { }); -promiseOfPoint3D = promiseOfPoint.then(p => promiseLikeOfPoint3D, e => { }); +promiseOfPoint3D = promiseOfPoint.then(p => point3d, e => { throw e; }); +promiseOfPoint3D = promiseOfPoint.then(p => promiseOfPoint3D, e => { throw e; }); +promiseOfPoint3D = promiseOfPoint.then(p => promiseLikeOfPoint3D, e => { throw e; }); promiseOfPoint = promiseOfPoint.catch(e => point); promiseOfPoint = promiseOfPoint.catch(e => promiseOfPoint); promiseOfPoint = promiseOfPoint.catch(e => promiseLikeOfPoint); -promiseOfPoint = promiseOfPoint.catch(e => { }); -promiseOfPoint3D = promiseOfPoint.catch(e => point3d); -promiseOfPoint3D = promiseOfPoint.catch(e => promiseOfPoint3D); -promiseOfPoint3D = promiseOfPoint.catch(e => promiseLikeOfPoint3D); +promiseOfPoint = promiseOfPoint.catch(e => { throw e; }); +promiseOfPoint3D = promiseOfPoint.then(p2d => ({ ...p2d, z: 0 })).catch(e => point3d); +promiseOfPoint3D = promiseOfPoint.then(p2d => ({ ...p2d, z: 0 })).catch(e => promiseOfPoint3D); +promiseOfPoint3D = promiseOfPoint.then(p2d => ({ ...p2d, z: 0 })).catch(e => promiseLikeOfPoint3D); promiseOfPoint = new Promise((resolve, reject) => resolve(point)); promiseOfPoint = new Promise((resolve, reject) => resolve(promiseOfPoint)); promiseOfPoint = new Promise((resolve, reject) => resolve(promiseLikeOfPoint)); diff --git a/types/cote/cote-tests.ts b/types/cote/cote-tests.ts new file mode 100644 index 0000000000..3236fe83b7 --- /dev/null +++ b/types/cote/cote-tests.ts @@ -0,0 +1,185 @@ +import * as cote from 'cote'; + +/** + * Examples from https://github.com/dashersw/cote. Note some differences, such + * as stricter request shape and Promises everywhere. + */ +class Readme { + requester() { + const randomRequester = new cote.Requester({ + name: 'Random Requester', + namespace: 'rnd', + key: 'a certain key', + requests: ['randomRequest'] + }); + + const req = { + type: 'randomRequest', + payload: { + val: Math.floor(Math.random() * 10) + } + }; + + randomRequester.send(req) + .then(console.log) + .catch(console.log) + .then(() => process.exit()); + } + + responder() { + const randomResponder = new cote.Responder({ + name: 'Random Responder', + namespace: 'rnd', + key: 'a certain key', + respondsTo: ['randomRequest'] + }); + + randomResponder.on('randomRequest', (req: cote.Action<{ val: number }>) => { + const answer = Math.floor(Math.random() * 10); + console.log('request', req.payload.val, 'answering with', answer); + return Promise.resolve(answer); + }); + } + + mongooseResponder() { + const UserModel = require('UserModel'); // a promise-based model API + + const userResponder = new cote.Responder({ name: 'User Responder' }); + + userResponder.on('find', (req: cote.Action<{ username: string }>) => UserModel.findOne(req.payload)); + } + + mongooseRequester() { + const userRequester = new cote.Requester({ name: 'User Requester' }); + + userRequester + .send({ type: 'find', payload: { username: 'foo' } }) + .then(user => console.log(user)) + .then(() => process.exit()); + } + + publisher() { + const randomPublisher = new cote.Publisher({ + name: 'Random Publisher', + namespace: 'rnd', + key: 'a certain key', + broadcasts: ['randomUpdate'] + }); + + setInterval(() => { + const action = { + type: 'randomUpdate', + payload: { + val: Math.floor(Math.random() * 1000) + } + }; + + console.log('emitting', action); + + randomPublisher.publish('randomUpdate', action); + }, 3000); + } + + subscriber() { + const randomSubscriber = new cote.Subscriber({ + name: 'Random Subscriber', + namespace: 'rnd', + key: 'a certain key', + subscribesTo: ['randomUpdate'] + }); + + randomSubscriber.on('randomUpdate', (req) => { + console.log('notified of ', req); + }); + } + + sockend() { + const app = require('http').createServer(handler); + const io = require('socket.io').listen(app); + const fs = require('fs'); + + app.listen(process.argv[2] || 5555); + + function handler(req: any, res: any) { + fs.readFile(__dirname + '/index.html', (err: Error, data: Buffer) => { + if (err) { + res.writeHead(500); + return res.end('Error loading index.html'); + } + + res.writeHead(200); + res.end(data); + }); + } + + const sockend = new cote.Sockend(io, { + name: 'Sockend', + key: 'a certain key' + }); + } + + keys() { + const purchaseRequester = new cote.Requester({ + name: 'Purchase Requester', + key: 'purchase' + }); + + const inventoryRequester = new cote.Requester({ + name: 'Inventory Requester', + key: 'inventory' + }); + } + + namespacesFront() { + const responder = new cote.Responder({ + name: 'Conversion Sockend Responder', + namespace: 'conversion' + }); + + const conversionRequester = new cote.Requester({ + name: 'Conversion Requester', + key: 'conversion backend' + }); + + responder.on('convert', (req) => { + return conversionRequester.send(req); // proxy the request + }); + } + + namespacesBack() { + const responder = new cote.Responder({ + name: 'Conversion Responder', + key: 'conversion backend' + }); + + const rates: { [key: string]: number } = { + usd_eur: 0.91, + eur_usd: 1.10 + }; + + responder.on('convert', (req: cote.Action<{ + amount: number, + from: string, + to: string + }>) => { + const { payload } = req; + return Promise.resolve(payload.amount * rates[`${payload.from}_${payload.to}`]); + }); + } + + multicast() { + const cote = require('cote')({ multicast: '239.1.11.111' }); + } + + multicastComponent() { + const req = new cote.Requester({ name: 'req' }, { multicast: '239.1.11.111' }); + } + + broadcast() { + const cote = require('cote')({ broadcast: '255.255.255.255' }); + } + + broadcastComponent() { + const req = new cote.Requester({ name: 'req' }, { broadcast: '255.255.255.255' }); + } +} diff --git a/types/cote/index.d.ts b/types/cote/index.d.ts new file mode 100644 index 0000000000..6a59b37392 --- /dev/null +++ b/types/cote/index.d.ts @@ -0,0 +1,211 @@ +// Type definitions for cote 0.14 +// Project: https://github.com/dashersw/cote#readme +// Definitions by: makepost +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as SocketIO from "socket.io"; +import { Stream } from "stream"; +import { Server } from "http"; + +export class Requester { + constructor( + /** + * Configuration which controls the data being advertised for auto-discovery. + */ + advertisement: Advertisement, + + /** + * Controls the network-layer configuration and environments for components. + */ + discoveryOptions?: DiscoveryOptions + ); + + /** + * Queues a request until a Responder is available, and once so, delivers + * the request. Requests are dispatched to Responders in a round-robin way. + * + * @param action Request. + */ + send(action: Action): Promise; +} + +export class Responder { + constructor( + /** + * Configuration which controls the data being advertised for auto-discovery. + */ + advertisement: Advertisement, + + /** + * Controls the network-layer configuration and environments for components. + */ + discoveryOptions?: DiscoveryOptions + ); + + /** + * Responds to certain requests from a Requester. + * + * @param type Type. May be wildcarded or namespaced like in EventEmitter2. + * @param listener Callback. Should return a result. + */ + on( + type: string, + listener: (action: Action) => Promise + ): void; +} + +export class Publisher { + constructor( + /** + * Configuration which controls the data being advertised for auto-discovery. + */ + advertisement: Advertisement, + + /** + * Controls the network-layer configuration and environments for components. + */ + discoveryOptions?: DiscoveryOptions + ); + + /** + * Publishes an event to all Subscribers. Does not wait for results. If + * there are no Subscribers listening, the event is lost. + * + * @param type EventEmitter-compatible type. + * @param action Request. + */ + publish( + type: string, + action: Action + ): void; +} + +export class Subscriber { + constructor( + /** + * Configuration which controls the data being advertised for auto-discovery. + */ + advertisement: Advertisement, + + /** + * Controls the network-layer configuration and environments for components. + */ + discoveryOptions?: DiscoveryOptions + ); + + /** + * Subscribes to events emitted from a Publisher. + * + * @param type Type. May be wildcarded or namespaced like in EventEmitter2. + * @param listener Callback. Returns nothing. + */ + on( + type: string, + listener: (action: Action) => void + ): void; +} + +export class Sockend { + /** + * Exposes APIs directly to front-end. Make sure to use namespaces. + */ + constructor( + io: SocketIO.Server, + + /** + * Configuration which controls the data being advertised for auto-discovery. + */ + advertisement: Advertisement, + + /** + * Controls the network-layer configuration and environments for components. + */ + discoveryOptions?: DiscoveryOptions + ); +} + +export class Monitor { + constructor( + /** + * Configuration which controls the data being advertised for auto-discovery. + */ + advertisement: Advertisement, + + /** + * Controls the network-layer configuration and environments for components. + */ + discoveryOptions?: DiscoveryOptions, + + stream?: Stream + ) +} + +/** + * Displays the cote ecosystem running in your environment in a nice graph. + * + * @param port Open in browser to see network graph in action. + */ +export function MonitoringTool(port: number): { + monitor: Monitor, + server: Server +}; + +/** + * Flux standard action. + * @see https://github.com/acdlite/flux-standard-action + */ +export interface Action { + type: string; + payload: T; + error?: boolean; + meta?: {}; +} + +/** + * Configuration which controls the data being advertised for auto-discovery. + */ +export interface Advertisement { + name: string; + + /** + * Maps to a socket.io namespace. Shields a service from the rest of the + * system. Components with different namespaces won't recognize each other + * and try to communicate. + */ + namespace?: string; + + /** + * Tunes the performance by grouping certain components. Two components + * with exact same `environment`s with different `key`s wouldn't be able + * to communicate. Think of it as `${environment}_${key}`. + */ + key?: string; + + /** + * Request types that a Requester can send. + */ + requests?: string[]; + + /** + * Response types that a Responder can listen to. + */ + respondsTo?: string[]; + + /** + * Event types that a Publisher can publish. + */ + broadcasts?: string[]; + + /** + * Event types that a Subscriber can listen to. + */ + subscribesTo?: string[]; +} + +/** + * Controls the network-layer configuration and environments for components. + */ +export interface DiscoveryOptions { + multicast?: string; + broadcast?: string; +} diff --git a/types/cote/tsconfig.json b/types/cote/tsconfig.json new file mode 100644 index 0000000000..2f8460f53d --- /dev/null +++ b/types/cote/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cote-tests.ts" + ] +} diff --git a/types/cote/tslint.json b/types/cote/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cote/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/datatables.net/datatables.net-tests.ts b/types/datatables.net/datatables.net-tests.ts index ada38d5a21..8ec7ecb084 100644 --- a/types/datatables.net/datatables.net-tests.ts +++ b/types/datatables.net/datatables.net-tests.ts @@ -60,12 +60,35 @@ $(document).ready(function () { sort: "asc" }; - var colRenderFunc: DataTables.FunctionColumnRender = function (data, type, row, meta) { + var colRenderFunc: DataTables.FunctionColumnRender = (data: any, type: 'filter' | 'display' | 'type' | 'sort' | undefined | any, row: any, meta: DataTables.CellMetaSettings): any => { meta.col; meta.row; meta.settings; + switch (type) { + case undefined: + return data.value; + case 'filter': + return data.filterValue; + case 'display': + return data.displayValue; + case 'type': + return data.typeValue; + case 'sort': + return data.sortValue; + default: + // Extensibility: the render type can be a custom value, useful for plugins that require custom rendering. + // Custom values are declared as any. + return data.valueForPlugin; + } }; + colRenderFunc({}, 'filter', {}, null); + colRenderFunc({}, 'display', {}, null); + colRenderFunc({}, 'type', {}, null); + colRenderFunc({}, 'sort', {}, null); + colRenderFunc({}, undefined, {}, null); + colRenderFunc({}, 'custom value', {}, null); + var col: DataTables.ColumnSettings = { cellType: "th", diff --git a/types/datatables.net/index.d.ts b/types/datatables.net/index.d.ts index bb55b54722..37c57198c9 100644 --- a/types/datatables.net/index.d.ts +++ b/types/datatables.net/index.d.ts @@ -1604,7 +1604,7 @@ declare namespace DataTables { } interface FunctionColumnRender { - (data: any, t: string, row: any, meta: CellMetaSettings): void; + (data: any, type: 'filter' | 'display' | 'type' | 'sort' | undefined | any, row: any, meta: CellMetaSettings): any; } interface CellMetaSettings { diff --git a/types/db-migrate-base/index.d.ts b/types/db-migrate-base/index.d.ts index de3a4c0812..a881fa6a06 100644 --- a/types/db-migrate-base/index.d.ts +++ b/types/db-migrate-base/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/db-migrate/db-migrate-base // Definitions by: nickiannone // Definitions: https://github.com/nickiannone/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/db-migrate-pg/index.d.ts b/types/db-migrate-pg/index.d.ts index 7804f4ddad..6a72fd1109 100644 --- a/types/db-migrate-pg/index.d.ts +++ b/types/db-migrate-pg/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/db-migrate/pg // Definitions by: nickiannone // Definitions: https://github.com/nickiannone/DefinitelyTyped +// TypeScript Version: 2.3 import * as pg from "pg"; import * as DbMigrateBase from "db-migrate-base"; diff --git a/types/draft-js/draft-js-tests.tsx b/types/draft-js/draft-js-tests.tsx index 178db06a0e..4315611765 100644 --- a/types/draft-js/draft-js-tests.tsx +++ b/types/draft-js/draft-js-tests.tsx @@ -11,7 +11,7 @@ import { RichUtils, SelectionState, getDefaultKeyBinding, - ContentState, + ContentState, convertFromHTML } from 'draft-js'; @@ -183,7 +183,7 @@ function getBlockStyle(block: ContentBlock) { } } -class StyleButton extends React.Component<{key: string, active: boolean, label: string, onToggle: (blockType: string) => void, style: string}, {}> { +class StyleButton extends React.Component<{key: string, active: boolean, label: string, onToggle: (blockType: string) => void, style: string}> { constructor() { super(); } diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts index 2474ecf56a..a3c14b73b4 100644 --- a/types/draft-js/index.d.ts +++ b/types/draft-js/index.d.ts @@ -5,7 +5,7 @@ // Yale Cason // Ryan Schwers // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 import * as React from 'react'; import * as Immutable from 'immutable'; @@ -37,7 +37,7 @@ declare namespace Draft { * div, and provides a wide variety of useful function props for managing the * state of the editor. See `DraftEditorProps` for details. */ - class DraftEditor extends React.Component { + class DraftEditor extends React.Component { // Force focus back onto the editor node. focus(): void; // Remove focus from the editor node. @@ -162,7 +162,7 @@ declare namespace Draft { } namespace Components { - class DraftEditorBlock extends React.Component { + class DraftEditorBlock extends React.Component { } } diff --git a/types/electron-settings/v2/electron-settings-tests.ts b/types/electron-settings/v2/electron-settings-tests.ts index 38e37e6ba0..25404c90b3 100644 --- a/types/electron-settings/v2/electron-settings-tests.ts +++ b/types/electron-settings/v2/electron-settings-tests.ts @@ -1,4 +1,4 @@ -import * as settings from 'electron-settings'; +import settings = require('electron-settings'); function test_configure() { settings.configure({ @@ -59,6 +59,7 @@ async function test_clear() { function test_clearSync() { settings.clearSync() === undefined; } + async function test_applyDefaults() { await settings.applyDefaults({ overwrite: true }) === undefined; } @@ -100,3 +101,23 @@ function test_on_write() { console.log(); }) === settings; } + +function test_settings_type_annotation(s: typeof settings) { + s.getSettingsFilePath(); +} + +function test_observer_type_annotation(observer: settings.Observer) { + observer.dispose(); +} + +function test_options_type_annotation(options: settings.Options) { + options.atomicSaving; +} + +function test_applyDefaultOptions_type_annotation(options: settings.ApplyDefaultsOptions) { + options.overwrite; +} + +function test_changeEvent_type_annotation(e: settings.ChangeEvent) { + e.oldValue === e.newValue; +} diff --git a/types/electron-settings/v2/index.d.ts b/types/electron-settings/v2/index.d.ts index ead5250015..71677cb0df 100644 --- a/types/electron-settings/v2/index.d.ts +++ b/types/electron-settings/v2/index.d.ts @@ -6,7 +6,10 @@ /// -import * as EventEmitter from 'events'; +import { EventEmitter } from 'events'; + +declare const SettingsInstance: Settings; +export = SettingsInstance; /** * The Settings class. @@ -17,7 +20,7 @@ declare class Settings extends EventEmitter { * * @throws if options is not an object. */ - configure(options: ElectronSettings.Options | object): void; + configure(options: ElectronSettings.Options.Param): void; /** * Globally configures default settings. @@ -76,14 +79,14 @@ declare class Settings extends EventEmitter { * @throws if options is not an object. * @see setSync */ - set(keyPath: string, value: any, options?: ElectronSettings.Options | object): Promise; + set(keyPath: string, value: any, options?: ElectronSettings.Options.Param): Promise; /** * The synchronous version of set(). * * @see set */ - setSync(keyPath: string, value: any, options?: ElectronSettings.Options | object): void; + setSync(keyPath: string, value: any, options?: ElectronSettings.Options.Param): void; /** * Deletes the key and value at the chosen key path. @@ -94,14 +97,14 @@ declare class Settings extends EventEmitter { * @throws if options is not an object. * @see deleteSync */ - delete(keyPath: string, options?: ElectronSettings.Options | object): Promise; + delete(keyPath: string, options?: ElectronSettings.Options.Param): Promise; /** * The synchronous version of delete(). * * @see delete */ - deleteSync(keyPath: string, options?: ElectronSettings.Options | object): void; + deleteSync(keyPath: string, options?: ElectronSettings.Options.Param): void; /** * Clears the entire settings object. @@ -110,14 +113,14 @@ declare class Settings extends EventEmitter { * @throws if options is not an object. * @see clearSync */ - clear(options?: ElectronSettings.Options | object): Promise; + clear(options?: ElectronSettings.Options.Param): Promise; /** * The synchronous version of clear(). * * @see clear */ - clearSync(options?: ElectronSettings.Options | object): void; + clearSync(options?: ElectronSettings.Options.Param): void; /** * Applies defaults to the current settings object (deep). @@ -130,14 +133,14 @@ declare class Settings extends EventEmitter { * @see defaults * @see applyDefaultsSync */ - applyDefaults(options?: ElectronSettings.ApplyDefaultsOptions | object): Promise; + applyDefaults(options?: ElectronSettings.ApplyDefaultsOptions.Param): Promise; /** * The synchronous version of applyDefaults(). * * @see applyDefaults */ - applyDefaultsSync(options?: ElectronSettings.ApplyDefaultsOptions | object): void; + applyDefaultsSync(options?: ElectronSettings.ApplyDefaultsOptions.Param): void; /** * Resets all settings to defaults. @@ -148,14 +151,14 @@ declare class Settings extends EventEmitter { * @see defaults * @see resetToDefaultsSync */ - resetToDefaults(options?: ElectronSettings.Options | object): Promise; + resetToDefaults(options?: ElectronSettings.Options.Param): Promise; /** * The synchronous version of resetToDefaults(). * * @see resetToDefaults */ - resetToDefaultsSync(options?: ElectronSettings.Options | object): void; + resetToDefaultsSync(options?: ElectronSettings.Options.Param): void; /** * Observes the chosen key path for changes and calls the handler if the value changes. @@ -187,8 +190,12 @@ declare class Settings extends EventEmitter { on(event: 'write', listener: () => void): this; } -declare const SettingsInstance: Settings; -export = SettingsInstance; +declare namespace SettingsInstance { + type Observer = ElectronSettings.Observer; + type Options = ElectronSettings.Options; + type ApplyDefaultsOptions = ElectronSettings.ApplyDefaultsOptions; + type ChangeEvent = ElectronSettings.ChangeEvent; +} declare namespace ElectronSettings { /** @@ -205,6 +212,8 @@ declare namespace ElectronSettings { interface Options extends Pick { } namespace Options { + type Param = Options | object; + interface _Impl { /** * Whether electron-settings should create a tmp file during save to ensure data-write consistency. @@ -224,6 +233,8 @@ declare namespace ElectronSettings { interface ApplyDefaultsOptions extends Pick { } namespace ApplyDefaultsOptions { + type Param = ApplyDefaultsOptions | object; + interface _Impl extends Options._Impl { /** * Overwrite pre-existing settings with their respective default values. diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index 721895e522..2a7142d9b3 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -8,14 +8,14 @@ // huhuanming // MartynasZilinskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 /// import { ReactElement, Component, HTMLAttributes as ReactHTMLAttributes, SVGAttributes as ReactSVGAttributes } from "react"; export type HTMLAttributes = ReactHTMLAttributes<{}> & ReactSVGAttributes<{}>; -export class ElementClass extends Component { +export class ElementClass extends Component { } /* These are purposefully stripped down versions of React.ComponentClass and React.StatelessComponent. @@ -23,7 +23,7 @@ export class ElementClass extends Component { * all specified in the implementation. TS chooses the EnzymePropSelector overload and loses the generics */ export interface ComponentClass { - new (props?: Props, context?: any): Component; + new (props?: Props, context?: any): Component; } export type StatelessComponent = (props: Props, context?: any) => JSX.Element; diff --git a/types/express-enforces-ssl/express-enforces-ssl-tests.ts b/types/express-enforces-ssl/express-enforces-ssl-tests.ts new file mode 100644 index 0000000000..50dab42cdf --- /dev/null +++ b/types/express-enforces-ssl/express-enforces-ssl-tests.ts @@ -0,0 +1,6 @@ +import express = require('express'); +import expressEnforcesSsl = require('express-enforces-ssl'); + +let app: express.Express = express(); + +app.use(expressEnforcesSsl()); diff --git a/types/express-enforces-ssl/index.d.ts b/types/express-enforces-ssl/index.d.ts new file mode 100644 index 0000000000..f4c1d424a4 --- /dev/null +++ b/types/express-enforces-ssl/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for express-enforces-ssl 1.1 +// Project: https://github.com/aredo/express-enforces-ssl +// Definitions by: Kevin Stubbs +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Request, Response, NextFunction } from 'express'; + +/** + * Enforces HTTPS connections on any incoming requests. + */ +declare function enforceHTTPS(): (req: Request, res: Response, next: NextFunction) => void; + +export = enforceHTTPS; diff --git a/types/express-enforces-ssl/tsconfig.json b/types/express-enforces-ssl/tsconfig.json new file mode 100644 index 0000000000..2fdb6a3472 --- /dev/null +++ b/types/express-enforces-ssl/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "express-enforces-ssl-tests.ts" + ] +} diff --git a/types/express-enforces-ssl/tslint.json b/types/express-enforces-ssl/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/express-enforces-ssl/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fetch.io/fetch.io-tests.ts b/types/fetch.io/fetch.io-tests.ts index 538da8e74b..67c2612fdc 100644 --- a/types/fetch.io/fetch.io-tests.ts +++ b/types/fetch.io/fetch.io-tests.ts @@ -57,3 +57,8 @@ request .post('') .send({}) .json(); + +request + .post('') + .append('key', 'value') + .append({key: 'value'}); diff --git a/types/fetch.io/index.d.ts b/types/fetch.io/index.d.ts index 8258cbf8da..fabbbc4b52 100644 --- a/types/fetch.io/index.d.ts +++ b/types/fetch.io/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for fetch.io 3.1 +// Type definitions for fetch.io 4.0 // Project: https://github.com/haoxins/fetch.io // Definitions by: newraina // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -95,7 +95,9 @@ export class Request { /** * ppend formData */ - append(key: string, value: string): this; + append(key: string, value: any): this; + + append(object: {[key: string]: any}): this; /** * Get Response directly diff --git a/types/ffmpeg-static/ffmpeg-static-tests.ts b/types/ffmpeg-static/ffmpeg-static-tests.ts new file mode 100644 index 0000000000..319a5e27f8 --- /dev/null +++ b/types/ffmpeg-static/ffmpeg-static-tests.ts @@ -0,0 +1,3 @@ +import * as ffmpegStatic from 'ffmpeg-static'; + +ffmpegStatic.path; diff --git a/types/ffmpeg-static/index.d.ts b/types/ffmpeg-static/index.d.ts new file mode 100644 index 0000000000..dfd9ce0906 --- /dev/null +++ b/types/ffmpeg-static/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for ffmpeg-static 2.0 +// Project: https://github.com/eugeneware/ffmpeg-static#readme +// Definitions by: Steve Tran +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/*~ You can declare properties of the module using const, let, or var */ +/** + * Binary location + */ +export const path: string; diff --git a/types/ffmpeg-static/tsconfig.json b/types/ffmpeg-static/tsconfig.json new file mode 100644 index 0000000000..94c7a336b8 --- /dev/null +++ b/types/ffmpeg-static/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ffmpeg-static-tests.ts" + ] +} diff --git a/types/ffmpeg-static/tslint.json b/types/ffmpeg-static/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ffmpeg-static/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ffprobe-static/ffprobe-static-tests.ts b/types/ffprobe-static/ffprobe-static-tests.ts new file mode 100644 index 0000000000..6565fd2ae1 --- /dev/null +++ b/types/ffprobe-static/ffprobe-static-tests.ts @@ -0,0 +1,3 @@ +import * as ffprobeStatic from 'ffmpeg-static'; + +ffprobeStatic.path; diff --git a/types/ffprobe-static/index.d.ts b/types/ffprobe-static/index.d.ts new file mode 100644 index 0000000000..b337d85e38 --- /dev/null +++ b/types/ffprobe-static/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for ffprobe-static 2.0 +// Project: https://github.com/joshwnj/ffprobe-static +// Definitions by: Steve Tran +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/*~ You can declare properties of the module using const, let, or var */ +/** + * Binary location + */ +export const path: string; diff --git a/types/ffprobe-static/tsconfig.json b/types/ffprobe-static/tsconfig.json new file mode 100644 index 0000000000..726a8e0feb --- /dev/null +++ b/types/ffprobe-static/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ffprobe-static-tests.ts" + ] +} diff --git a/types/ffprobe-static/tslint.json b/types/ffprobe-static/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ffprobe-static/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fixed-data-table/fixed-data-table-tests.tsx b/types/fixed-data-table/fixed-data-table-tests.tsx index 64b622b21f..96c17a4a9a 100644 --- a/types/fixed-data-table/fixed-data-table-tests.tsx +++ b/types/fixed-data-table/fixed-data-table-tests.tsx @@ -2,7 +2,7 @@ import * as React from "react"; import {Table, Cell, Column, CellProps} from "fixed-data-table"; // create your Table -class MyTable1 extends React.Component<{}, {}> { +class MyTable1 extends React.Component { render(): React.ReactElement { return ( { } // create your Columns -class MyTable2 extends React.Component<{}, {}> { +class MyTable2 extends React.Component { render(): React.ReactElement { return (
{ +class MyTextCell extends React.Component { render(): React.ReactElement { const {rowIndex, field, myData} = this.props; @@ -104,7 +104,7 @@ class MyTextCell extends React.Component { } } -class MyLinkCell extends React.Component { +class MyLinkCell extends React.Component { render(): React.ReactElement { const {rowIndex, field, myData} = this.props; const link: string = myData[rowIndex][field]; @@ -168,7 +168,7 @@ class MyTable4 extends React.Component<{}, MyTable4State> { } // Listen for events -class MyTable5 extends React.Component<{}, {}> { +class MyTable5 extends React.Component { render(): React.ReactElement { return (
, Stephen Jelfs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 /// @@ -489,12 +489,12 @@ declare namespace FixedDataTable { columnKey?: string | number; } - export class Table extends React.Component { + export class Table extends React.Component { } - export class Column extends React.Component { + export class Column extends React.Component { } - export class ColumnGroup extends React.Component { + export class ColumnGroup extends React.Component { } - export class Cell extends React.Component { + export class Cell extends React.Component { } } diff --git a/types/flux/index.d.ts b/types/flux/index.d.ts index 7380613ce7..096c9516e6 100644 --- a/types/flux/index.d.ts +++ b/types/flux/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Steve Baker // Giedrius Grabauskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import * as Dispatcher from "./lib/Dispatcher"; diff --git a/types/fluxxor/fluxxor-tests.ts b/types/fluxxor/fluxxor-tests.ts index ef6a8c707a..38522b1e1b 100644 --- a/types/fluxxor/fluxxor-tests.ts +++ b/types/fluxxor/fluxxor-tests.ts @@ -1,5 +1,5 @@ -import React = require('react'); -import Fluxxor = require('fluxxor'); +import * as React from 'react'; +import * as Fluxxor from 'fluxxor'; class DispatcherTest { v: Fluxxor.Dispatcher; diff --git a/types/fluxxor/index.d.ts b/types/fluxxor/index.d.ts index c091186aaa..d5389f9cde 100644 --- a/types/fluxxor/index.d.ts +++ b/types/fluxxor/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/BinaryMuse/fluxxor // Definitions by: Yuichi Murata // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 import * as EventEmitter3 from 'eventemitter3'; import * as React from "react"; diff --git a/types/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts b/types/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts index 46e623207a..b17cb07e32 100644 --- a/types/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts +++ b/types/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts @@ -1,47 +1,48 @@ import fs = require('fs-extra-promise-es6'); import stream = require('stream'); -var stats: fs.Stats; -var str: string; -var strArr: string[]; -var bool: boolean; -var num: number; -var src: string; -var dest: string; -var file: string; -var filename: string; -var dir: string; -var path: string; -var data: any; -var object: Object; -var buffer: NodeBuffer; -var modeNum: number; -var modeStr: string; -var encoding: string; -var type: string; -var flags: string; -var srcpath: string; -var dstpath: string; -var oldPath: string; -var newPath: string; -var cache: string; -var offset: number; -var length: number; -var position: number; -var cacheBool: boolean; -var cacheStr: string; -var fd: number; -var len: number; -var uid: number; -var gid: number; -var atime: number; -var mtime: number; -var statsCallback: (err: Error, stats: fs.Stats) => void; -var errorCallback: (err: Error) => void; -var openOpts: fs.OpenOptions; -var watcher: fs.FSWatcher; -var readStreeam: stream.Readable; -var writeStream: stream.Writable; +let stats: fs.Stats; +let str: string; +let strArr: string[]; +let bool: boolean; +let num: number; +let src: string; +let dest: string; +let file: string; +let filename: string; +let dir: string; +let path: string; +let data: any; +let object: any; +let buffer: NodeBuffer; +let modeNum: number; +let modeStr: string; +let encoding: string; +let type: string; +let flags: string; +let srcpath: string; +let dstpath: string; +let oldPath: string; +let newPath: string; +let cache: string; +let offset: number; +let length: number; +let position: number; +let cacheBool: boolean; +let cacheStr: string; +let fd: number; +let len: number; +let uid: number; +let gid: number; +let atime: number; +let mtime: number; +let statsCallback: (err: Error, stats: fs.Stats) => void; +let errorCallback: (err: Error) => void; +let openOpts: fs.OpenOptions; +let watcher: fs.FSWatcher; +let readStreeam: stream.Readable; +let writeStream: stream.Writable; +let isDirectory: boolean; fs.copy(src, dest, errorCallback); fs.copy(src, dest, (src: string) => { @@ -119,13 +120,10 @@ fs.linkSync(srcpath, dstpath); fs.symlink(srcpath, dstpath, type, errorCallback); fs.symlinkSync(srcpath, dstpath, type); fs.readlink(path, (err: Error, linkString: string) => { - }); fs.realpath(path, (err: Error, resolvedPath: string) => { - }); fs.realpath(path, cache, (err: Error, resolvedPath: string) => { - }); str = fs.realpathSync(path, cacheBool); fs.unlink(path, errorCallback); @@ -137,13 +135,11 @@ fs.mkdir(path, modeStr, errorCallback); fs.mkdirSync(path, modeNum); fs.mkdirSync(path, modeStr); fs.readdir(path, (err: Error, files: string[]) => { - }); strArr = fs.readdirSync(path); fs.close(fd, errorCallback); fs.closeSync(fd); fs.open(path, flags, modeStr, (err: Error, fd: number) => { - }); num = fs.openSync(path, flags, modeStr); fs.utimes(path, atime, mtime, errorCallback); @@ -153,24 +149,18 @@ fs.futimesSync(fd, atime, mtime); fs.fsync(fd, errorCallback); fs.fsyncSync(fd); fs.write(fd, buffer, offset, length, position, (err: Error, written: number, buffer: NodeBuffer) => { - }); num = fs.writeSync(fd, buffer, offset, length, position); fs.read(fd, buffer, offset, length, position, (err: Error, bytesRead: number, buffer: NodeBuffer) => { - }); num = fs.readSync(fd, buffer, offset, length, position); fs.readFile(filename, (err: Error, data: NodeBuffer) => { - }); fs.readFile(filename, encoding, (err: Error, data: string) => { - }); fs.readFile(filename, openOpts, (err: Error, data: string) => { - }); fs.readFile(filename, (err: Error, data: NodeBuffer) => { - }); buffer = fs.readFileSync(filename); str = fs.readFileSync(filename, encoding); @@ -203,10 +193,8 @@ fs.watchFile(filename, { }); fs.unwatchFile(filename); watcher = fs.watch(filename, { persistent: bool }, (event: string, filename: string) => { - }); fs.exists(path, (exists: boolean) => { - }); bool = fs.existsSync(path); @@ -222,3 +210,10 @@ writeStream = fs.createWriteStream(path, { flags: str, encoding: str }); + +let isDirectoryCallback = (err: Error, isDirectory: boolean) => { +}; +fs.isDirectory(path, isDirectoryCallback); +fs.isDirectory(path); +isDirectory = fs.isDirectorySync(path); +fs.isDirectoryAsync(path); diff --git a/types/fs-extra-promise-es6/index.d.ts b/types/fs-extra-promise-es6/index.d.ts index 85055636dc..db262c1460 100644 --- a/types/fs-extra-promise-es6/index.d.ts +++ b/types/fs-extra-promise-es6/index.d.ts @@ -1,158 +1,194 @@ -// Type definitions for fs-extra-promise-es6 +// Type definitions for fs-extra-promise-es6 0.1 // Project: https://github.com/vinsonchuong/fs-extra-promise-es6 -// Definitions by: midknight41 , Jason Swearingen , Joshua DeVinney +// Definitions by: midknight41 +// Jason Swearingen +// Joshua DeVinney +// Hiromi Shikata // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Imported from: fs-extra-promise typings (minus Bluebird) -/// - +/// import stream = require("stream"); import fs = require("fs"); -export type Stats = fs.Stats +export type Stats = fs.Stats; export interface FSWatcher { close(): void; } -export declare class ReadStream extends stream.Readable { } -export declare class WriteStream extends stream.Writable { } +export class ReadStream extends stream.Readable { } +export class WriteStream extends stream.Writable { } -//extended methods -export declare function copy(src: string, dest: string, callback?: (err: Error) => void): void; -export declare function copy(src: string, dest: string, filter: (src: string) => boolean, callback?: (err: Error) => void): void; +// extended methods +export function copy(src: string, dest: string, callback?: (err: Error) => void): void; +export function copy(src: string, dest: string, filter: (src: string) => boolean, callback?: (err: Error) => void): void; -export declare function copySync(src: string, dest: string): void; -export declare function copySync(src: string, dest: string, filter: (src: string) => boolean): void; +export function copySync(src: string, dest: string, filter?: (src: string) => boolean): void; -export declare function createFile(file: string, callback?: (err: Error) => void): void; -export declare function createFileSync(file: string): void; +export function createFile(file: string, callback?: (err: Error) => void): void; +export function createFileSync(file: string): void; -export declare function mkdirs(dir: string, callback?: (err: Error) => void): void; -export declare function mkdirp(dir: string, callback?: (err: Error) => void): void; -export declare function mkdirsSync(dir: string): void; -export declare function mkdirpSync(dir: string): void; +export function mkdirs(dir: string, callback?: (err: Error) => void): void; +export function mkdirp(dir: string, callback?: (err: Error) => void): void; +export function mkdirsSync(dir: string): void; +export function mkdirpSync(dir: string): void; -export declare function outputFile(file: string, data: any, callback?: (err: Error) => void): void; -export declare function outputFileSync(file: string, data: any): void; +export function outputFile(file: string, data: any, callback?: (err: Error) => void): void; +export function outputFileSync(file: string, data: any): void; -export declare function outputJson(file: string, data: any, callback?: (err: Error) => void): void; -export declare function outputJSON(file: string, data: any, callback?: (err: Error) => void): void; -export declare function outputJsonSync(file: string, data: any): void; -export declare function outputJSONSync(file: string, data: any): void; +export function outputJson(file: string, data: any, callback?: (err: Error) => void): void; +export function outputJSON(file: string, data: any, callback?: (err: Error) => void): void; +export function outputJsonSync(file: string, data: any): void; +export function outputJSONSync(file: string, data: any): void; -export declare function readJson(file: string, callback?: (err: Error) => void): void; -export declare function readJson(file: string, options?: OpenOptions, callback?: (err: Error) => void): void; -export declare function readJSON(file: string, callback?: (err: Error) => void): void; -export declare function readJSON(file: string, options?: OpenOptions, callback?: (err: Error) => void): void; +export function readJson(file: string, callback?: (err: Error) => void): void; +export function readJson(file: string, options?: OpenOptions, callback?: (err: Error) => void): void; +export function readJSON(file: string, callback?: (err: Error) => void): void; +export function readJSON(file: string, options?: OpenOptions, callback?: (err: Error) => void): void; -export declare function readJsonSync(file: string, options?: OpenOptions): void; -export declare function readJSONSync(file: string, options?: OpenOptions): void; +export function readJsonSync(file: string, options?: OpenOptions): void; +export function readJSONSync(file: string, options?: OpenOptions): void; -export declare function remove(dir: string, callback?: (err: Error) => void): void; -export declare function removeSync(dir: string): void; +export function remove(dir: string, callback?: (err: Error) => void): void; +export function removeSync(dir: string): void; // export function delete(dir: string, callback?: (err: Error) => void): void; // export function deleteSync(dir: string): void; -export declare function writeJson(file: string, object: any, callback?: (err: Error) => void): void; -export declare function writeJson(file: string, object: any, options?: OpenOptions, callback?: (err: Error) => void): void; -export declare function writeJSON(file: string, object: any, callback?: (err: Error) => void): void; -export declare function writeJSON(file: string, object: any, options?: OpenOptions, callback?: (err: Error) => void): void; +export function writeJson(file: string, object: any, callback?: (err: Error) => void): void; +export function writeJson(file: string, object: any, options?: OpenOptions, callback?: (err: Error) => void): void; +export function writeJSON(file: string, object: any, callback?: (err: Error) => void): void; +export function writeJSON(file: string, object: any, options?: OpenOptions, callback?: (err: Error) => void): void; -export declare function writeJsonSync(file: string, object: any, options?: OpenOptions): void; -export declare function writeJSONSync(file: string, object: any, options?: OpenOptions): void; +export function writeJsonSync(file: string, object: any, options?: OpenOptions): void; +export function writeJSONSync(file: string, object: any, options?: OpenOptions): void; -export declare function rename(oldPath: string, newPath: string, callback?: (err: Error) => void): void; -export declare function renameSync(oldPath: string, newPath: string): void; -export declare function truncate(fd: number, len: number, callback?: (err: Error) => void): void; -export declare function truncateSync(fd: number, len: number): void; -export declare function chown(path: string, uid: number, gid: number, callback?: (err: Error) => void): void; -export declare function chownSync(path: string, uid: number, gid: number): void; -export declare function fchown(fd: number, uid: number, gid: number, callback?: (err: Error) => void): void; -export declare function fchownSync(fd: number, uid: number, gid: number): void; -export declare function lchown(path: string, uid: number, gid: number, callback?: (err: Error) => void): void; -export declare function lchownSync(path: string, uid: number, gid: number): void; -export declare function chmod(path: string, mode: number, callback?: (err: Error) => void): void; -export declare function chmod(path: string, mode: string, callback?: (err: Error) => void): void; -export declare function chmodSync(path: string, mode: number): void; -export declare function chmodSync(path: string, mode: string): void; -export declare function fchmod(fd: number, mode: number, callback?: (err: Error) => void): void; -export declare function fchmod(fd: number, mode: string, callback?: (err: Error) => void): void; -export declare function fchmodSync(fd: number, mode: number): void; -export declare function fchmodSync(fd: number, mode: string): void; -export declare function lchmod(path: string, mode: string, callback?: (err: Error) => void): void; -export declare function lchmod(path: string, mode: number, callback?: (err: Error) => void): void; -export declare function lchmodSync(path: string, mode: number): void; -export declare function lchmodSync(path: string, mode: string): void; -export declare function stat(path: string, callback?: (err: Error, stats: Stats) => void): void; -export declare function lstat(path: string, callback?: (err: Error, stats: Stats) => void): void; -export declare function fstat(fd: number, callback?: (err: Error, stats: Stats) => void): void; -export declare function statSync(path: string): Stats; -export declare function lstatSync(path: string): Stats; -export declare function fstatSync(fd: number): Stats; -export declare function link(srcpath: string, dstpath: string, callback?: (err: Error) => void): void; -export declare function linkSync(srcpath: string, dstpath: string): void; -export declare function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err: Error) => void): void; -export declare function symlinkSync(srcpath: string, dstpath: string, type?: string): void; -export declare function readlink(path: string, callback?: (err: Error, linkString: string) => void): void; -export declare function realpath(path: string, callback?: (err: Error, resolvedPath: string) => void): void; -export declare function realpath(path: string, cache: string, callback: (err: Error, resolvedPath: string) => void): void; -export declare function realpathSync(path: string, cache?: boolean): string; -export declare function unlink(path: string, callback?: (err: Error) => void): void; -export declare function unlinkSync(path: string): void; -export declare function rmdir(path: string, callback?: (err: Error) => void): void; -export declare function rmdirSync(path: string): void; -export declare function mkdir(path: string, mode?: number, callback?: (err: Error) => void): void; -export declare function mkdir(path: string, mode?: string, callback?: (err: Error) => void): void; -export declare function mkdirSync(path: string, mode?: number): void; -export declare function mkdirSync(path: string, mode?: string): void; -export declare function readdir(path: string, callback?: (err: Error, files: string[]) => void): void; -export declare function readdirSync(path: string): string[]; -export declare function close(fd: number, callback?: (err: Error) => void): void; -export declare function closeSync(fd: number): void; -export declare function open(path: string, flags: string, mode?: string, callback?: (err: Error, fs: number) => void): void; -export declare function openSync(path: string, flags: string, mode?: string): number; -export declare function utimes(path: string, atime: number, mtime: number, callback?: (err: Error) => void): void; -export declare function utimesSync(path: string, atime: number, mtime: number): void; -export declare function futimes(fd: number, atime: number, mtime: number, callback?: (err: Error) => void): void; -export declare function futimesSync(fd: number, atime: number, mtime: number): void; -export declare function fsync(fd: number, callback?: (err: Error) => void): void; -export declare function fsyncSync(fd: number): void; -export declare function write(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: Error, written: number, buffer: NodeBuffer) => void): void; -export declare function writeSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; -export declare function read(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: Error, bytesRead: number, buffer: NodeBuffer) => void): void; -export declare function readSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; -export declare function readFile(filename: string, encoding: string, callback: (err: Error, data: string) => void): void; -export declare function readFile(filename: string, options: OpenOptions, callback: (err: Error, data: string) => void): void; -export declare function readFile(filename: string, callback: (err: Error, data: NodeBuffer) => void): void; -export declare function readFileSync(filename: string): NodeBuffer; -export declare function readFileSync(filename: string, encoding: string): string; -export declare function readFileSync(filename: string, options: OpenOptions): string; -export declare function writeFile(filename: string, data: any, encoding?: string, callback?: (err: Error) => void): void; -export declare function writeFile(filename: string, data: any, options?: OpenOptions, callback?: (err: Error) => void): void; -export declare function writeFileSync(filename: string, data: any, encoding?: string): void; -export declare function writeFileSync(filename: string, data: any, option?: OpenOptions): void; -export declare function appendFile(filename: string, data: any, encoding?: string, callback?: (err: Error) => void): void; -export declare function appendFile(filename: string, data: any, option?: OpenOptions, callback?: (err: Error) => void): void; -export declare function appendFileSync(filename: string, data: any, encoding?: string): void; -export declare function appendFileSync(filename: string, data: any, option?: OpenOptions): void; -export declare function watchFile(filename: string, listener: { curr: Stats; prev: Stats; }): void; -export declare function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: { curr: Stats; prev: Stats; }): void; -export declare function unwatchFile(filename: string, listener?: Stats): void; -export declare function watch(filename: string, options?: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; -export declare function exists(path: string, callback?: (exists: boolean) => void): void; -export declare function existsSync(path: string): boolean; -export declare function ensureDir(path: string, cb: (err: Error) => void): void; -export declare function ensureDirSync(path: string): void; +export function rename(oldPath: string, newPath: string, callback?: (err: Error) => void): void; +export function renameSync(oldPath: string, newPath: string): void; +export function truncate(fd: number, len: number, callback?: (err: Error) => void): void; +export function truncateSync(fd: number, len: number): void; +export function chown(path: string, uid: number, gid: number, callback?: (err: Error) => void): void; +export function chownSync(path: string, uid: number, gid: number): void; +export function fchown(fd: number, uid: number, gid: number, callback?: (err: Error) => void): void; +export function fchownSync(fd: number, uid: number, gid: number): void; +export function lchown(path: string, uid: number, gid: number, callback?: (err: Error) => void): void; +export function lchownSync(path: string, uid: number, gid: number): void; +export function chmod(path: string, mode: number | string, callback?: (err: Error) => void): void; +export function chmodSync(path: string, mode: number | string): void; +export function fchmod(fd: number, mode: number | string, callback?: (err: Error) => void): void; +export function fchmodSync(fd: number, mode: number | string): void; +export function lchmod(path: string, mode: number | string, callback?: (err: Error) => void): void; +export function lchmodSync(path: string, mode: number | string): void; +export function stat(path: string, callback?: (err: Error, stats: Stats) => void): void; +export function lstat(path: string, callback?: (err: Error, stats: Stats) => void): void; +export function fstat(fd: number, callback?: (err: Error, stats: Stats) => void): void; +export function statSync(path: string): Stats; +export function lstatSync(path: string): Stats; +export function fstatSync(fd: number): Stats; +export function link(srcpath: string, dstpath: string, callback?: (err: Error) => void): void; +export function linkSync(srcpath: string, dstpath: string): void; +export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err: Error) => void): void; +export function symlinkSync(srcpath: string, dstpath: string, type?: string): void; +export function readlink(path: string, callback?: (err: Error, linkString: string) => void): void; +export function realpath(path: string, callback?: (err: Error, resolvedPath: string) => void): void; +export function realpath(path: string, cache: string, callback: (err: Error, resolvedPath: string) => void): void; +export function realpathSync(path: string, cache?: boolean): string; +export function unlink(path: string, callback?: (err: Error) => void): void; +export function unlinkSync(path: string): void; +export function rmdir(path: string, callback?: (err: Error) => void): void; +export function rmdirSync(path: string): void; +export function mkdir(path: string, mode?: number | string, callback?: (err: Error) => void): void; +export function mkdirSync(path: string, mode?: number | string): void; +export function readdir(path: string, callback?: (err: Error, files: string[]) => void): void; +export function readdirSync(path: string): string[]; +export function close(fd: number, callback?: (err: Error) => void): void; +export function closeSync(fd: number): void; +export function open(path: string, flags: string, mode?: string, callback?: (err: Error, fs: number) => void): void; +export function openSync(path: string, flags: string, mode?: string): number; +export function utimes(path: string, atime: number, mtime: number, callback?: (err: Error) => void): void; +export function utimesSync(path: string, atime: number, mtime: number): void; +export function futimes(fd: number, atime: number, mtime: number, callback?: (err: Error) => void): void; +export function futimesSync(fd: number, atime: number, mtime: number): void; +export function fsync(fd: number, callback?: (err: Error) => void): void; +export function fsyncSync(fd: number): void; +export function write(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: Error, written: number, buffer: NodeBuffer) => void): void; +export function writeSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; +export function read(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: Error, bytesRead: number, buffer: NodeBuffer) => void): void; +export function readSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; +/** + * readFile + * @param filename + * @param options + * string: encoding + * OpenOptions: options + * @param callback + */ +export function readFile(filename: string, options: OpenOptions | string, callback: (err: Error, data: string) => void): void; +export function readFile(filename: string, callback: (err: Error, data: NodeBuffer) => void): void; +export function readFileSync(filename: string): NodeBuffer; +/** + * readFileSync + * @param filename + * @param options + * string: encoding + * OpenOptions: options + */ +export function readFileSync(filename: string, options: OpenOptions | string): string; +/** + * writeFile + * @param filename + * @param data + * @param options + * string: encoding + * OpenOptions: options + * @param callback + */ +export function writeFile(filename: string, data: any, options?: OpenOptions | string, callback?: (err: Error) => void): void; +/** + * writeFileSync + * @param filename + * @param data + * @param option + * string: encoding + * OpenOptions: options + */ +export function writeFileSync(filename: string, data: any, option?: OpenOptions | string): void; +/** + * appendFile + * @param filename + * @param data + * @param option: + * string: encoding + * OpenOptions: options + * @param callback + */ +export function appendFile(filename: string, data: any, option?: OpenOptions | string, callback?: (err: Error) => void): void; +/** + * appendFileSync + * @param filename + * @param data + * @param option + * string: encoding + * OpenOptions: options + */ +export function appendFileSync(filename: string, data: any, option?: OpenOptions | string): void; +export function watchFile(filename: string, listener: { curr: Stats; prev: Stats; }): void; +export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: { curr: Stats; prev: Stats; }): void; +export function unwatchFile(filename: string, listener?: Stats): void; +export function watch(filename: string, options?: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; +export function exists(path: string, callback?: (exists: boolean) => void): void; +export function existsSync(path: string): boolean; +export function ensureDir(path: string, cb: (err: Error) => void): void; +export function ensureDirSync(path: string): void; export interface OpenOptions { encoding?: string; flag?: string; } -export declare function createReadStream(path: string | Buffer, options?: { +export function createReadStream(path: string | Buffer, options?: { flags?: string; encoding?: string; fd?: number; @@ -161,81 +197,90 @@ export declare function createReadStream(path: string | Buffer, options?: { start?: number; end?: number; }): ReadStream; -export declare function createWriteStream(path: string | Buffer, options?: { +export function createWriteStream(path: string | Buffer, options?: { flags?: string; encoding?: string; fd?: number; mode?: number; }): WriteStream; +// promisified versions +export function copyAsync(src: string, dest: string, filter?: (src: string) => boolean): Promise; +export function createFileAsync(file: string): Promise; -//promisified versions -export declare function copyAsync(src: string, dest: string): Promise; -export declare function copyAsync(src: string, dest: string, filter: (src: string) => boolean): Promise; +export function mkdirsAsync(dir: string): Promise; +export function mkdirpAsync(dir: string): Promise; -export declare function createFileAsync(file: string): Promise; +export function outputFileAsync(file: string, data: any): Promise; -export declare function mkdirsAsync(dir: string): Promise; -export declare function mkdirpAsync(dir: string): Promise; +export function outputJSONAsync(file: string, data: any): Promise; -export declare function outputFileAsync(file: string, data: any): Promise; +export function readJSONAsync(file: string, options?: OpenOptions): Promise; -export declare function outputJsonAsync(file: string, data: any): Promise; -export declare function outputJSONAsync(file: string, data: any): Promise; - -export declare function readJsonAsync(file: string): Promise; -export declare function readJsonAsync(file: string, options?: OpenOptions): Promise; -export declare function readJSONAsync(file: string): Promise; -export declare function readJSONAsync(file: string, options?: OpenOptions): Promise; - - -export declare function removeAsync(dir: string): Promise; +export function removeAsync(dir: string): Promise; // export function deleteAsync(dir: string):Promise; -export declare function writeJsonAsync(file: string, object: any): Promise; -export declare function writeJsonAsync(file: string, object: any, options?: OpenOptions): Promise; -export declare function writeJSONAsync(file: string, object: any): Promise; -export declare function writeJSONAsync(file: string, object: any, options?: OpenOptions): Promise; +export function writeJsonAsync(file: string, object: any, options?: OpenOptions): Promise; +export function writeJSONAsync(file: string, object: any, options?: OpenOptions): Promise; -export declare function renameAsync(oldPath: string, newPath: string): Promise; -export declare function truncateAsync(fd: number, len: number): Promise; -export declare function chownAsync(path: string, uid: number, gid: number): Promise; -export declare function fchownAsync(fd: number, uid: number, gid: number): Promise; -export declare function lchownAsync(path: string, uid: number, gid: number): Promise; -export declare function chmodAsync(path: string, mode: number): Promise; -export declare function chmodAsync(path: string, mode: string): Promise; -export declare function fchmodAsync(fd: number, mode: number): Promise; -export declare function fchmodAsync(fd: number, mode: string): Promise; -export declare function lchmodAsync(path: string, mode: string): Promise; -export declare function lchmodAsync(path: string, mode: number): Promise; -export declare function statAsync(path: string): Promise; -export declare function lstatAsync(path: string): Promise; -export declare function fstatAsync(fd: number): Promise; -export declare function linkAsync(srcpath: string, dstpath: string): Promise; -export declare function symlinkAsync(srcpath: string, dstpath: string, type?: string): Promise; -export declare function readlinkAsync(path: string): Promise; -export declare function realpathAsync(path: string): Promise; -export declare function realpathAsync(path: string, cache: string): Promise; -export declare function unlinkAsync(path: string): Promise; -export declare function rmdirAsync(path: string): Promise; -export declare function mkdirAsync(path: string, mode?: number): Promise; -export declare function mkdirAsync(path: string, mode?: string): Promise; -export declare function readdirAsync(path: string): Promise; -export declare function closeAsync(fd: number): Promise; -export declare function openAsync(path: string, flags: string, mode?: string): Promise; -export declare function utimesAsync(path: string, atime: number, mtime: number): Promise; -export declare function futimesAsync(fd: number, atime: number, mtime: number): Promise; -export declare function fsyncAsync(fd: number): Promise; -export declare function writeAsync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): Promise<[number, NodeBuffer]>; -export declare function readAsync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): Promise<[number, NodeBuffer]>; -export declare function readFileAsync(filename: string, encoding: string): Promise; -export declare function readFileAsync(filename: string, options: OpenOptions): Promise; -export declare function readFileAsync(filename: string): Promise; -export declare function writeFileAsync(filename: string, data: any, encoding?: string): Promise; -export declare function writeFileAsync(filename: string, data: any, options?: OpenOptions): Promise; -export declare function appendFileAsync(filename: string, data: any, encoding?: string): Promise; -export declare function appendFileAsync(filename: string, data: any, option?: OpenOptions): Promise; +export function renameAsync(oldPath: string, newPath: string): Promise; +export function truncateAsync(fd: number, len: number): Promise; +export function chownAsync(path: string, uid: number, gid: number): Promise; +export function fchownAsync(fd: number, uid: number, gid: number): Promise; +export function lchownAsync(path: string, uid: number, gid: number): Promise; +export function chmodAsync(path: string, mode: number | string): Promise; +export function fchmodAsync(fd: number, mode: number | string): Promise; +export function lchmodAsync(path: string, mode: number | string): Promise; +export function statAsync(path: string): Promise; +export function lstatAsync(path: string): Promise; +export function fstatAsync(fd: number): Promise; +export function linkAsync(srcpath: string, dstpath: string): Promise; +export function symlinkAsync(srcpath: string, dstpath: string, type?: string): Promise; +export function readlinkAsync(path: string): Promise; +export function realpathAsync(path: string, cache?: string): Promise; +export function unlinkAsync(path: string): Promise; +export function rmdirAsync(path: string): Promise; +export function mkdirAsync(path: string, mode?: number | string): Promise; +export function readdirAsync(path: string): Promise; +export function closeAsync(fd: number): Promise; +export function openAsync(path: string, flags: string, mode?: string): Promise; +export function utimesAsync(path: string, atime: number, mtime: number): Promise; +export function futimesAsync(fd: number, atime: number, mtime: number): Promise; +export function fsyncAsync(fd: number): Promise; +export function writeAsync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): Promise<[number, NodeBuffer]>; +export function readAsync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): Promise<[number, NodeBuffer]>; +/** + * readFileAsync + * @param filename + * @param options: + * string: encoding + * OpenOptions: options + */ +export function readFileAsync(filename: string, options: OpenOptions | string): Promise; +export function readFileAsync(filename: string): Promise; +/** + * writeFileAsync + * @param filename + * @param data + * @param options: + * string: encoding + * OpenOptions: options + */ +export function writeFileAsync(filename: string, data: any, options?: OpenOptions | string): Promise; +/** + * appendFileAsync + * @param filename + * @param data + * @param option: + * string: encoding + * OpenOptions: option + */ +export function appendFileAsync(filename: string, data: any, option?: OpenOptions | string): Promise; -export declare function existsAsync(path: string): Promise; -export declare function ensureDirAsync(path: string): Promise; +export function existsAsync(path: string): Promise; +export function ensureDirAsync(path: string): Promise; + +export function isDirectory(path: string, callback?: (err: Error, isDirectory: boolean) => void): void; +export function isDirectorySync(path: string): boolean; +export function isDirectoryAsync(path: string): Promise; diff --git a/types/fs-extra-promise-es6/tslint.json b/types/fs-extra-promise-es6/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/fs-extra-promise-es6/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/fs-extra-promise/fs-extra-promise-tests.ts b/types/fs-extra-promise/fs-extra-promise-tests.ts index ef8de43ad3..9f5a8b32bf 100644 --- a/types/fs-extra-promise/fs-extra-promise-tests.ts +++ b/types/fs-extra-promise/fs-extra-promise-tests.ts @@ -1,48 +1,49 @@ import fs = require('fs-extra-promise'); import stream = require('stream'); -var stats: fs.Stats; -var str: string; -var strArr: string[]; -var bool: boolean; -var num: number; -var src: string; -var dest: string; -var file: string; -var filename: string; -var dir: string; -var path: string; -var data: any; -var object: Object; -var buf: Buffer; -var buffer: NodeBuffer; -var modeNum: number; -var modeStr: string; -var encoding: string; -var type: string; -var flags: string; -var srcpath: string; -var dstpath: string; -var oldPath: string; -var newPath: string; -var cache: { [path: string]: string; }; -var offset: number; -var length: number; -var position: number; -var fd: number; -var len: number; -var uid: number; -var gid: number; -var atime: number; -var mtime: number; -var watchListener: (curr: fs.Stats, prev: fs.Stats) => void; -var statsCallback: (err: Error, stats: fs.Stats) => void; -var errorCallback: (err: Error) => void; -var openOpts: fs.ReadOptions; -var writeOpts: fs.WriteOptions; -var watcher: fs.FSWatcher; -var readStream: stream.Readable; -var writeStream: stream.Writable; +let stats: fs.Stats; +let str: string; +let strArr: string[]; +let bool: boolean; +let num: number; +let src: string; +let dest: string; +let file: string; +let filename: string; +let dir: string; +let path: string; +let data: any; +let object: object; +let buf: Buffer; +let buffer: NodeBuffer; +let modeNum: number; +let modeStr: string; +let encoding: string; +let type: string; +let flags: string; +let srcpath: string; +let dstpath: string; +let oldPath: string; +let newPath: string; +let cache: { [path: string]: string; }; +let offset: number; +let length: number; +let position: number; +let fd: number; +let len: number; +let uid: number; +let gid: number; +let atime: number; +let mtime: number; +let watchListener: (curr: fs.Stats, prev: fs.Stats) => void; +let statsCallback: (err: Error, stats: fs.Stats) => void; +let errorCallback: (err: Error) => void; +let openOpts: fs.ReadOptions; +let writeOpts: fs.WriteOptions; +let watcher: fs.FSWatcher; +let readStream: stream.Readable; +let writeStream: stream.Writable; +let isDirectory: boolean; fs.copy(src, dest, errorCallback); fs.copy(src, dest, (src: string) => { @@ -122,13 +123,10 @@ fs.linkSync(srcpath, dstpath); fs.symlink(srcpath, dstpath, type, errorCallback); fs.symlinkSync(srcpath, dstpath, type); fs.readlink(path, (err: Error, linkString: string) => { - }); fs.realpath(path, (err: Error, resolvedPath: string) => { - }); fs.realpath(path, cache, (err: Error, resolvedPath: string) => { - }); str = fs.realpathSync(path, cache); fs.unlink(path, errorCallback); @@ -140,13 +138,11 @@ fs.mkdir(path, modeStr, errorCallback); fs.mkdirSync(path, modeNum); fs.mkdirSync(path, modeStr); fs.readdir(path, (err: Error, files: string[]) => { - }); strArr = fs.readdirSync(path); fs.close(fd, errorCallback); fs.closeSync(fd); fs.open(path, flags, modeNum, (err: Error, fd: number) => { - }); num = fs.openSync(path, flags, modeNum); fs.utimes(path, atime, mtime, errorCallback); @@ -156,24 +152,18 @@ fs.futimesSync(fd, atime, mtime); fs.fsync(fd, errorCallback); fs.fsyncSync(fd); fs.write(fd, buffer, offset, length, position, (err: Error, written: number, buffer: NodeBuffer) => { - }); num = fs.writeSync(fd, buffer, offset, length, position); fs.read(fd, buffer, offset, length, position, (err: Error, bytesRead: number, buffer: NodeBuffer) => { - }); num = fs.readSync(fd, buffer, offset, length, position); fs.readFile(filename, (err: Error, data: NodeBuffer) => { - }); fs.readFile(filename, encoding, (err: Error, data: string) => { - }); fs.readFile(filename, openOpts, (err: NodeJS.ErrnoException, data: Buffer) => { - }); fs.readFile(filename, (err: Error, data: NodeBuffer) => { - }); buffer = fs.readFileSync(filename); str = fs.readFileSync(filename, encoding); @@ -200,10 +190,8 @@ fs.watchFile(filename, { }, watchListener); fs.unwatchFile(filename); watcher = fs.watch(filename, { persistent: bool }, (event: string, filename: string) => { - }); fs.exists(path, (exists: boolean) => { - }); bool = fs.existsSync(path); @@ -219,3 +207,10 @@ writeStream = fs.createWriteStream(path, { flags: str, encoding: str }); + +let isDirectoryCallback = (err: Error, isDirectory: boolean) => { +}; +fs.isDirectory(path, isDirectoryCallback); +fs.isDirectory(path); +isDirectory = fs.isDirectorySync(path); +fs.isDirectoryAsync(path); diff --git a/types/fs-extra-promise/index.d.ts b/types/fs-extra-promise/index.d.ts index b4c9a648ac..9d174f791f 100644 --- a/types/fs-extra-promise/index.d.ts +++ b/types/fs-extra-promise/index.d.ts @@ -1,12 +1,10 @@ // Type definitions for fs-extra-promise 1.0 // Project: https://github.com/overlookmotel/fs-extra-promise -// Definitions by: midknight41 , Jason Swearingen +// Definitions by: midknight41 , Jason Swearingen , Hiromi Shikata // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 /// -/// -/// import * as stream from 'stream'; import { Stats } from 'fs'; @@ -20,73 +18,94 @@ export interface MkdirOptions { mode?: number; } -//promisified versions -export declare function copyAsync(src: string, dest: string): Promise; -export declare function copyAsync(src: string, dest: string, filter: CopyFilter): Promise; -export declare function copyAsync(src: string, dest: string, options: CopyOptions): Promise; +// promisified versions +/** + * copyAsync + * @param src + * @param dest + * @param options + * CopyFilter: filter + * CopyOptions: options + */ +export function copyAsync(src: string, dest: string, options?: CopyFilter | CopyOptions): Promise; -export declare function createFileAsync(file: string): Promise; +export function createFileAsync(file: string): Promise; -export declare function mkdirsAsync(dir: string, options?: MkdirOptions): Promise; -export declare function mkdirpAsync(dir: string, options?: MkdirOptions): Promise; +export function mkdirsAsync(dir: string, options?: MkdirOptions): Promise; +export function mkdirpAsync(dir: string, options?: MkdirOptions): Promise; -export declare function moveAsync(src: string, dest: string, options?: MoveOptions): Promise; +export function moveAsync(src: string, dest: string, options?: MoveOptions): Promise; -export declare function outputFileAsync(file: string, data: any): Promise; +export function outputFileAsync(file: string, data: any): Promise; -export declare function outputJsonAsync(file: string, data: any): Promise; -export declare function outputJSONAsync(file: string, data: any): Promise; +export function outputJsonAsync(file: string, data: any): Promise; +export function outputJSONAsync(file: string, data: any): Promise; -export declare function readJsonAsync(file: string): Promise; -export declare function readJsonAsync(file: string, options?: ReadOptions): Promise; -export declare function readJSONAsync(file: string): Promise; -export declare function readJSONAsync(file: string, options?: ReadOptions): Promise; +export function readJsonAsync(file: string, options?: ReadOptions): Promise; +export function readJSONAsync(file: string, options?: ReadOptions): Promise; -export declare function removeAsync(dir: string): Promise; +export function removeAsync(dir: string): Promise; -export declare function writeJsonAsync(file: string, object: any): Promise; -export declare function writeJsonAsync(file: string, object: any, options?: WriteOptions): Promise; -export declare function writeJSONAsync(file: string, object: any): Promise; -export declare function writeJSONAsync(file: string, object: any, options?: WriteOptions): Promise; +export function writeJsonAsync(file: string, object: any, options?: WriteOptions): Promise; +export function writeJSONAsync(file: string, object: any, options?: WriteOptions): Promise; -export declare function renameAsync(oldPath: string, newPath: string): Promise; -export declare function truncateAsync(fd: number, len: number): Promise; -export declare function chownAsync(path: string, uid: number, gid: number): Promise; -export declare function fchownAsync(fd: number, uid: number, gid: number): Promise; -export declare function lchownAsync(path: string, uid: number, gid: number): Promise; -export declare function chmodAsync(path: string, mode: number): Promise; -export declare function chmodAsync(path: string, mode: string): Promise; -export declare function fchmodAsync(fd: number, mode: number): Promise; -export declare function fchmodAsync(fd: number, mode: string): Promise; -export declare function lchmodAsync(path: string, mode: string): Promise; -export declare function lchmodAsync(path: string, mode: number): Promise; -export declare function statAsync(path: string): Promise; -export declare function lstatAsync(path: string): Promise; -export declare function fstatAsync(fd: number): Promise; -export declare function linkAsync(srcpath: string, dstpath: string): Promise; -export declare function symlinkAsync(srcpath: string, dstpath: string, type?: string): Promise; -export declare function readlinkAsync(path: string): Promise; -export declare function realpathAsync(path: string): Promise; -export declare function realpathAsync(path: string, cache: { [path: string]: string }): Promise; -export declare function unlinkAsync(path: string): Promise; -export declare function rmdirAsync(path: string): Promise; -export declare function mkdirAsync(path: string, mode?: number): Promise; -export declare function mkdirAsync(path: string, mode?: string): Promise; -export declare function readdirAsync(path: string): Promise; -export declare function closeAsync(fd: number): Promise; -export declare function openAsync(path: string, flags: string, mode?: string): Promise; -export declare function utimesAsync(path: string, atime: number, mtime: number): Promise; -export declare function futimesAsync(fd: number, atime: number, mtime: number): Promise; -export declare function fsyncAsync(fd: number): Promise; -export declare function writeAsync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): Promise<[number, NodeBuffer]>; -export declare function readAsync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): Promise<[number, NodeBuffer]>; -export declare function readFileAsync(filename: string, encoding: string): Promise; -export declare function readFileAsync(filename: string, options: ReadOptions): Promise; -export declare function readFileAsync(filename: string): Promise; -export declare function writeFileAsync(filename: string, data: any, encoding?: string): Promise; -export declare function writeFileAsync(filename: string, data: any, options?: WriteOptions): Promise; -export declare function appendFileAsync(filename: string, data: any, encoding?: string): Promise; -export declare function appendFileAsync(filename: string, data: any, option?: WriteOptions): Promise; +export function renameAsync(oldPath: string, newPath: string): Promise; +export function truncateAsync(fd: number, len: number): Promise; +export function chownAsync(path: string, uid: number, gid: number): Promise; +export function fchownAsync(fd: number, uid: number, gid: number): Promise; +export function lchownAsync(path: string, uid: number, gid: number): Promise; +export function chmodAsync(path: string, mode: number | string): Promise; +export function fchmodAsync(fd: number, mode: number | string): Promise; +export function lchmodAsync(path: string, mode: number | string): Promise; +export function statAsync(path: string): Promise; +export function lstatAsync(path: string): Promise; +export function fstatAsync(fd: number): Promise; +export function linkAsync(srcpath: string, dstpath: string): Promise; +export function symlinkAsync(srcpath: string, dstpath: string, type?: string): Promise; +export function readlinkAsync(path: string): Promise; +export function realpathAsync(path: string, cache?: { [path: string]: string }): Promise; +export function unlinkAsync(path: string): Promise; +export function rmdirAsync(path: string): Promise; +export function mkdirAsync(path: string, mode?: number | string): Promise; +export function readdirAsync(path: string): Promise; +export function closeAsync(fd: number): Promise; +export function openAsync(path: string, flags: string, mode?: string): Promise; +export function utimesAsync(path: string, atime: number, mtime: number): Promise; +export function futimesAsync(fd: number, atime: number, mtime: number): Promise; +export function fsyncAsync(fd: number): Promise; +export function writeAsync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): Promise<[number, NodeBuffer]>; +export function readAsync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): Promise<[number, NodeBuffer]>; +/** + * readFileAsync + * @param filename + * @param options: + * string: encoding + * ReadOptions: options + */ +export function readFileAsync(filename: string, options: string | ReadOptions): Promise; +export function readFileAsync(filename: string): Promise; +/** + * writeFileAsync + * @param filename + * @param data + * @param options: + * string: encoding + * WriteOptions: options + */ +export function writeFileAsync(filename: string, data: any, options?: string | WriteOptions): Promise; +/** + * appendFileAsync + * @param filename + * @param data + * @param options: + * string: encoding + * WriteOptions: options + */ +export function appendFileAsync(filename: string, data: any, option?: string | WriteOptions): Promise; -export declare function existsAsync(path: string): Promise; -export declare function ensureDirAsync(path: string): Promise; +export function existsAsync(path: string): Promise; +export function ensureDirAsync(path: string): Promise; + +export function isDirectory(path: string, callback?: (err: Error, isDirectory: boolean) => void): void; +export function isDirectorySync(path: string): boolean; +export function isDirectoryAsync(path: string): Promise; diff --git a/types/fs-extra-promise/tslint.json b/types/fs-extra-promise/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/fs-extra-promise/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/geokdbush/geokdbush-tests.ts b/types/geokdbush/geokdbush-tests.ts new file mode 100644 index 0000000000..f2fa9d54c3 --- /dev/null +++ b/types/geokdbush/geokdbush-tests.ts @@ -0,0 +1,10 @@ +import * as kdbush from 'kdbush'; +import * as geokdbush from 'geokdbush'; + +const points = [ + {lon: 0, lat: 0}, + {lon: 20, lat: 10}, + {lon: -10, lat: 30}, +]; +const index = kdbush(points, p => p.lon, p => p.lat); +const nearest = geokdbush.around(index, -119.7051, 34.4363, 1000); diff --git a/types/geokdbush/index.d.ts b/types/geokdbush/index.d.ts new file mode 100644 index 0000000000..4ece8ff98d --- /dev/null +++ b/types/geokdbush/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for geokdbush 1.1 +// Project: https://github.com/mourner/geokdbush +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import {KDBush} from 'kdbush'; + +export function around( + index: KDBush, + longitude: number, + latitude: number, + maxResults?: number, + maxDistance?: number, + filterFn?: any): T[]; + +export function distance( + longitude1: number, + latitude1: number, + longitude2: number, + latitude2: number): number; diff --git a/types/geokdbush/tsconfig.json b/types/geokdbush/tsconfig.json new file mode 100644 index 0000000000..9f00c027da --- /dev/null +++ b/types/geokdbush/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "geokdbush-tests.ts" + ] +} diff --git a/types/geokdbush/tslint.json b/types/geokdbush/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/geokdbush/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/google-map-react/index.d.ts b/types/google-map-react/index.d.ts index 080dbe5762..c1898a9e3f 100644 --- a/types/google-map-react/index.d.ts +++ b/types/google-map-react/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/istarkov/google-map-react // Definitions by: Honza Brecka // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 import * as React from 'react'; @@ -102,7 +102,7 @@ export interface Props { yesIWantToUseGoogleMapApiInternals?: boolean; } -export default class GoogleMapReact extends React.Component {} +export default class GoogleMapReact extends React.Component {} export interface ChildComponentProps extends Coords { $hover?: boolean; diff --git a/types/graphql/type/schema.d.ts b/types/graphql/type/schema.d.ts index 0f02cd78af..01bd3b1ca5 100644 --- a/types/graphql/type/schema.d.ts +++ b/types/graphql/type/schema.d.ts @@ -49,8 +49,8 @@ export class GraphQLSchema { constructor(config: GraphQLSchemaConfig) getQueryType(): GraphQLObjectType; - getMutationType(): GraphQLObjectType; - getSubscriptionType(): GraphQLObjectType; + getMutationType(): GraphQLObjectType|null|undefined; + getSubscriptionType(): GraphQLObjectType|null|undefined; getTypeMap(): { [typeName: string]: GraphQLNamedType }; getType(name: string): GraphQLType; getPossibleTypes(abstractType: GraphQLAbstractType): Array; diff --git a/types/griddle-react/index.d.ts b/types/griddle-react/index.d.ts index e8f817b5a1..ea40fb2130 100644 --- a/types/griddle-react/index.d.ts +++ b/types/griddle-react/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/griddlegriddle/griddle // Definitions by: David Hara // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 /* The MIT License (MIT) @@ -162,7 +162,7 @@ export interface GriddleProps { onRowClick?(): void; } -declare class Griddle extends React.Component, any> { +declare class Griddle extends React.Component> { } export default Griddle; diff --git a/types/griddle-react/test/CustomColumnComponent.tsx b/types/griddle-react/test/CustomColumnComponent.tsx index fff018dcfb..6e81453e95 100644 --- a/types/griddle-react/test/CustomColumnComponent.tsx +++ b/types/griddle-react/test/CustomColumnComponent.tsx @@ -12,7 +12,7 @@ interface MyCustomResult { test: string; } -class LinkComponent extends React.Component, any> { +class LinkComponent extends React.Component> { render() { const url = "speakers/" + this.props.rowData.test + "/" + this.props.data; return {this.props.data}; @@ -50,7 +50,7 @@ const rowMetaData = { } }; -class CustomColumnComponentGrid extends React.Component { +class CustomColumnComponentGrid extends React.Component { render() { type TypedGriddle = new () => Griddle; const TypedGriddle = Griddle as TypedGriddle; diff --git a/types/griddle-react/test/CustomFilterComponent.tsx b/types/griddle-react/test/CustomFilterComponent.tsx index 3de40132f1..b045281868 100644 --- a/types/griddle-react/test/CustomFilterComponent.tsx +++ b/types/griddle-react/test/CustomFilterComponent.tsx @@ -22,7 +22,7 @@ const CustomFilterFunction = (items: ResultType[], query: string): ResultType[] }); }; -class CustomFilterComponent extends React.Component { +class CustomFilterComponent extends React.Component { query: string = ''; searchChange(event: React.FormEvent) { @@ -73,7 +73,7 @@ const someData: ResultType[] = [ } ]; -class CustomFilterComponentGrid extends React.Component { +class CustomFilterComponentGrid extends React.Component { render() { type TypedGriddle = new () => Griddle; const TypedGriddle = Griddle as TypedGriddle; diff --git a/types/griddle-react/test/CustomHeaderComponent.tsx b/types/griddle-react/test/CustomHeaderComponent.tsx index af9d1d6ea3..c5256956fc 100644 --- a/types/griddle-react/test/CustomHeaderComponent.tsx +++ b/types/griddle-react/test/CustomHeaderComponent.tsx @@ -11,7 +11,7 @@ interface MoreCustomHeaderComponentProps extends CustomHeaderComponentProps { color: string; } -class HeaderComponent extends React.Component { +class HeaderComponent extends React.Component { textOnClick(e: React.FormEvent) { e.stopPropagation(); } @@ -80,7 +80,7 @@ const columnMeta: Array> = [ } ]; -class CustomHeaderComponentGrid extends React.Component { +class CustomHeaderComponentGrid extends React.Component { render() { type TypedGriddle = new () => Griddle; const TypedGriddle = Griddle as TypedGriddle; diff --git a/types/griddle-react/test/index.tsx b/types/griddle-react/test/index.tsx index 3e0b1c76ff..4c977c0f97 100644 --- a/types/griddle-react/test/index.tsx +++ b/types/griddle-react/test/index.tsx @@ -16,7 +16,7 @@ interface MyCustomResult { test: string; } -class LinkComponent extends React.Component, any> { +class LinkComponent extends React.Component> { render() { const url = "speakers/" + this.props.rowData.test + "/" + this.props.data; return {this.props.data}; diff --git a/types/gulp-istanbul/gulp-istanbul-tests.ts b/types/gulp-istanbul/gulp-istanbul-tests.ts index a57932419d..af15f5df54 100644 --- a/types/gulp-istanbul/gulp-istanbul-tests.ts +++ b/types/gulp-istanbul/gulp-istanbul-tests.ts @@ -5,7 +5,7 @@ function testFramework(): NodeJS.ReadWriteStream { return null; } -gulp.task('test', function (cb: Function) { +gulp.task('test', function (cb: () => void) { gulp.src(['lib/**/*.js', 'main.js']) .pipe(istanbul()) // Covering files .pipe(gulp.dest('test-tmp/')) @@ -17,7 +17,7 @@ gulp.task('test', function (cb: Function) { }); }); -gulp.task('test', function (cb: Function) { +gulp.task('test', function (cb: () => void) { gulp.src(['lib/**/*.js', 'main.js']) .pipe(istanbul({includeUntested: true})) // Covering files .pipe(istanbul.hookRequire()) @@ -29,7 +29,7 @@ gulp.task('test', function (cb: Function) { }); }); -gulp.task('test', function (cb: Function) { +gulp.task('test', function (cb: () => void) { gulp.src(['lib/**/*.js', 'main.js']) .pipe(istanbul({includeUntested: true})) // Covering files .pipe(istanbul.hookRequire()) diff --git a/types/gulp-sourcemaps/gulp-sourcemaps-tests.ts b/types/gulp-sourcemaps/gulp-sourcemaps-tests.ts index 9ea2849f1e..f41612c4a5 100644 --- a/types/gulp-sourcemaps/gulp-sourcemaps-tests.ts +++ b/types/gulp-sourcemaps/gulp-sourcemaps-tests.ts @@ -94,4 +94,26 @@ gulp.task('javascript', function() { } })) .pipe(gulp.dest('public/scripts')); +}); + +gulp.task('javascript', function() { + var stream = gulp.src('src/**/*.js') + .pipe(sourcemaps.init()) + .pipe(plugin1()) + .pipe(plugin2()) + .pipe(sourcemaps.write('../maps', { + clone: true + })) + .pipe(gulp.dest('public/scripts')); +}); + +gulp.task('javascript', function() { + var stream = gulp.src('src/**/*.js') + .pipe(sourcemaps.init()) + .pipe(plugin1()) + .pipe(plugin2()) + .pipe(sourcemaps.write('../maps', { + clone: { contents: false } + })) + .pipe(gulp.dest('public/scripts')); }); \ No newline at end of file diff --git a/types/gulp-sourcemaps/index.d.ts b/types/gulp-sourcemaps/index.d.ts index 107c6560c1..8a038af6ec 100644 --- a/types/gulp-sourcemaps/index.d.ts +++ b/types/gulp-sourcemaps/index.d.ts @@ -15,11 +15,17 @@ interface WriteMapper { (file: string): string; } +interface CloneOptions { + contents?: boolean; + deep?: boolean; +} + interface WriteOptions { addComment?: boolean; includeContent?: boolean; sourceRoot?: string | WriteMapper; sourceMappingURLPrefix?: string | WriteMapper; + clone?: boolean | CloneOptions; } export declare function init(opts?: InitOptions): NodeJS.ReadWriteStream; diff --git a/types/gulp-watch/gulp-watch-tests.ts b/types/gulp-watch/gulp-watch-tests.ts index 56a676bc65..de531257a5 100644 --- a/types/gulp-watch/gulp-watch-tests.ts +++ b/types/gulp-watch/gulp-watch-tests.ts @@ -7,7 +7,7 @@ gulp.task('stream', () => .pipe(gulp.dest('build')) ); -gulp.task('callback', (cb: Function) => +gulp.task('callback', (cb: () => void) => watch('css/**/*.css', () => gulp.src('css/**/*.css') .pipe(watch('css/**/*.css')) @@ -25,3 +25,15 @@ gulp.task('build', () => { gulp.src(files, { base: '..' }) .pipe(watch(files, { base: '..' })); }); + +gulp.task('build', () => { + var files = [ + 'app/**/*.ts', + 'lib/**/*.ts', + 'components/**/*.ts', + ]; + + gulp.src(files, { cwd: '..' }) + .pipe(watch(files, { base: '..' })); +}); + diff --git a/types/gulp-watch/index.d.ts b/types/gulp-watch/index.d.ts index de56633491..f9855f09a6 100644 --- a/types/gulp-watch/index.d.ts +++ b/types/gulp-watch/index.d.ts @@ -5,8 +5,9 @@ /// +import {SrcOptions} from "vinyl-fs"; -interface IOptions { +interface IOptions extends SrcOptions { ignoreInitial?: boolean; events?: Array; base?: string; diff --git a/types/halogen/index.d.ts b/types/halogen/index.d.ts index 35337e7e9f..216281972e 100644 --- a/types/halogen/index.d.ts +++ b/types/halogen/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/yuanyan/halogen // Definitions by: Vincent Rouffiat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 import * as react from "react"; @@ -34,50 +34,50 @@ export interface RadiusLoaderProps extends MarginLoaderProps { /** * React components */ -export type PulseLoader = react.Component, {}>; +export type PulseLoader = react.Component>; export const PulseLoader: react.ComponentClass>; -export type RotateLoader = react.Component, {}>; +export type RotateLoader = react.Component>; export const RotateLoader: react.ComponentClass>; -export type BeatLoader = react.Component, {}>; +export type BeatLoader = react.Component>; export const BeatLoader: react.ComponentClass>; -export type RiseLoader = react.Component, {}>; +export type RiseLoader = react.Component>; export const RiseLoader: react.ComponentClass>; -export type SyncLoader = react.Component, {}>; +export type SyncLoader = react.Component>; export const SyncLoader: react.ComponentClass>; -export type GridLoader = react.Component, {}>; +export type GridLoader = react.Component>; export const GridLoader: react.ComponentClass>; -export type ClipLoader = react.Component; +export type ClipLoader = react.Component; export const ClipLoader: react.ComponentClass; -export type SquareLoader = react.Component; +export type SquareLoader = react.Component; export const SquareLoader: react.ComponentClass; -export type DotLoader = react.Component; +export type DotLoader = react.Component; export const DotLoader: react.ComponentClass; -export type PacmanLoader = react.Component, {}>; +export type PacmanLoader = react.Component>; export const PacmanLoader: react.ComponentClass>; -export type MoonLoader = react.Component; +export type MoonLoader = react.Component; export const MoonLoader: react.ComponentClass; -export type RingLoader = react.Component; +export type RingLoader = react.Component; export const RingLoader: react.ComponentClass; -export type BounceLoader = react.Component; +export type BounceLoader = react.Component; export const BounceLoader: react.ComponentClass; -export type SkewLoader = react.Component; +export type SkewLoader = react.Component; export const SkewLoader: react.ComponentClass; -export type FadeLoader = react.Component; +export type FadeLoader = react.Component; export const FadeLoader: react.ComponentClass; -export type ScaleLoader = react.Component; +export type ScaleLoader = react.Component; export const ScaleLoader: react.ComponentClass; diff --git a/types/halogen/test/clip-loader.tsx b/types/halogen/test/clip-loader.tsx index 02f0dd232c..af3a72762f 100644 --- a/types/halogen/test/clip-loader.tsx +++ b/types/halogen/test/clip-loader.tsx @@ -1,7 +1,7 @@ import * as React from "react"; import * as Halogen from "halogen"; -class HalogenTests_ClipLoader_withNoProps extends React.Component, {}> { +class HalogenTests_ClipLoader_withNoProps extends React.Component> { render() { return ( @@ -9,7 +9,7 @@ class HalogenTests_ClipLoader_withNoProps extends React.Component, {}> { +class HalogenTests_ClipLoader_withAllProps extends React.Component> { render() { return ( diff --git a/types/halogen/test/fade-loader.tsx b/types/halogen/test/fade-loader.tsx index deeae1ce95..23fb8fa3ca 100644 --- a/types/halogen/test/fade-loader.tsx +++ b/types/halogen/test/fade-loader.tsx @@ -1,7 +1,7 @@ import * as React from "react"; import * as Halogen from "halogen"; -class HalogenTests_FadeLoader_withNoProps extends React.Component, {}> { +class HalogenTests_FadeLoader_withNoProps extends React.Component> { render() { return ( @@ -9,7 +9,7 @@ class HalogenTests_FadeLoader_withNoProps extends React.Component, {}> { +class HalogenTests_FadeLoader_withAllProps extends React.Component> { render() { return ( , {}> { +class HalogenTests_PacmanLoader_withNoProps extends React.Component> { render() { return ( @@ -9,7 +9,7 @@ class HalogenTests_PacmanLoader_withNoProps extends React.Component, {}> { +class HalogenTests_PacmanLoader_withAllProps extends React.Component> { render() { return ( diff --git a/types/halogen/test/rotate-loader.tsx b/types/halogen/test/rotate-loader.tsx index a5325a4962..38274aefea 100644 --- a/types/halogen/test/rotate-loader.tsx +++ b/types/halogen/test/rotate-loader.tsx @@ -1,7 +1,7 @@ import * as React from "react"; import * as Halogen from "halogen"; -class HalogenTests_RotateLoader_withNoProps extends React.Component, {}> { +class HalogenTests_RotateLoader_withNoProps extends React.Component> { render() { return ( @@ -9,7 +9,7 @@ class HalogenTests_RotateLoader_withNoProps extends React.Component, {}> { +class HalogenTests_RotateLoader_withAllProps extends React.Component> { render() { return ( diff --git a/types/hapi/v8/hapi-tests.ts b/types/hapi/v8/hapi-tests.ts index 585e58e100..ee8af0d335 100644 --- a/types/hapi/v8/hapi-tests.ts +++ b/types/hapi/v8/hapi-tests.ts @@ -124,15 +124,5 @@ server.route([{ } }]); -// Implict handler -server.route({ - method: 'GET', - path: '/hello6', - handler: function (request, reply) { - request.log('info', { route: '/hello' }, Date.now()); - reply('hello world'); - } -}); - // Start the server server.start(); diff --git a/types/heredatalens/heredatalens-tests.ts b/types/heredatalens/heredatalens-tests.ts index 37f20f2f84..40e68902c5 100644 --- a/types/heredatalens/heredatalens-tests.ts +++ b/types/heredatalens/heredatalens-tests.ts @@ -121,3 +121,41 @@ let spatialLayerOptions: H.datalens.SpatialLayer.Options = { }; let spatialLayer = new H.datalens.SpatialLayer(provider, spatialProvider, spatialLayerOptions); + +let layer = new H.datalens.ObjectLayer( + provider, + { + rowToMapObject: (cluster) => { + return new H.map.Marker(cluster.getPosition()); + }, + clustering: { + rowToDataPoint: (row) => { + return new H.clustering.DataPoint(row.lat, row.lng, 1); + }, + options: () => { + return { + eps: 25 * devicePixelRatio, // px + minWeight: 20 + }; + } + }, + rowToStyle: (cluster) => { + const size = 32; + + let icon = H.datalens.ObjectLayer.createIcon([ + 'svg', + { + viewBox: [-size, -size, 2 * size, 2 * size] + }, + ['circle', { + cx: 0, + cy: 0, + r: size, + fill: cluster.isCluster() ? 'orange' : 'transparent' + }] + ], { size, crossOrigin: false }); + + return { icon }; + } + } +); diff --git a/types/heredatalens/index.d.ts b/types/heredatalens/index.d.ts index 0c68c88a45..b01014ba1e 100644 --- a/types/heredatalens/index.d.ts +++ b/types/heredatalens/index.d.ts @@ -618,7 +618,7 @@ declare namespace H { /** * A factory method for data-driven icons. The method allows you to build an icon from SVG markup or JsonML object. Provides caching of icons with the same markup. * @param svg {string | Array} - SVG presented as markup or JsonML Array - * @param options {H.map.Icon.Options} - Icon options (eg size and anchor). Note that the default anchor is in the middle. + * @param options {H.map.Icon.Options=} - Icon options (eg size and anchor). Note that the default anchor is in the middle. * @param options.size {H.math.ISize | number} - When the icon is a square, you can define the size as a number in pixels * @returns {H.map.Icon} - Icon which can be used for marker or cluster */ @@ -684,6 +684,7 @@ declare namespace H { */ interface Row { getPosition(): H.geo.Point; + isCluster(): boolean; lat: number; lng: number; } @@ -704,9 +705,9 @@ declare namespace H { */ interface ObjectStyleOptions { icon: H.map.Icon; - style: H.map.SpatialStyle.Options; - arrows: H.map.ArrowStyle.Options; - zIndex: number; + style?: H.map.SpatialStyle.Options; + arrows?: H.map.ArrowStyle.Options; + zIndex?: number; } /** diff --git a/types/history/PathUtils.d.ts b/types/history/PathUtils.d.ts index 4cc947fcf3..80e5c2db54 100644 --- a/types/history/PathUtils.d.ts +++ b/types/history/PathUtils.d.ts @@ -2,6 +2,8 @@ import { Path, Location, LocationDescriptorObject } from './index'; export function addLeadingSlash(path: Path): Path; export function stripLeadingSlash(path: Path): Path; -export function stripPrefix(path: Path, prefix: string): Path; +export function hasBasename(path: Path): boolean; +export function stripBasename(path: Path, prefix: string): Path; +export function stripTrailingSlash(path: Path): Path; export function parsePath(path: Path): Location; export function createPath(location: LocationDescriptorObject): Path; diff --git a/types/history/history-tests.ts b/types/history/history-tests.ts index a316bf03d3..0a63059b12 100644 --- a/types/history/history-tests.ts +++ b/types/history/history-tests.ts @@ -109,7 +109,7 @@ let input = { value: "" }; { let path = PathUtils.createPath({ pathname: '/a/path', hash: '#hash' }); - let strippedPath = PathUtils.stripPrefix(path, '/a/'); + let strippedPath = PathUtils.stripBasename(path, '/a/'); let location = PathUtils.parsePath(strippedPath); } diff --git a/types/history/index.d.ts b/types/history/index.d.ts index eda8c1bb10..a7f93bba86 100644 --- a/types/history/index.d.ts +++ b/types/history/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for history 4.5 +// Type definitions for history 4.6.2 // Project: https://github.com/mjackson/history // Definitions by: Sergey Buturlakin , Nathan Brown , Young Rok Kim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/hls.js/hls.js-tests.ts b/types/hls.js/hls.js-tests.ts index e6d4a995f5..a8f7291044 100644 --- a/types/hls.js/hls.js-tests.ts +++ b/types/hls.js/hls.js-tests.ts @@ -3,6 +3,7 @@ import * as Hls from 'hls.js'; if (Hls.isSupported()) { const video = document.getElementById('video'); const hls = new Hls(); + const version: string = Hls.version; hls.loadSource('http://www.streambox.fr/playlists/test_001/stream.m3u8'); hls.attachMedia(video); hls.on(Hls.Events.MANIFEST_PARSED, () => { diff --git a/types/hls.js/index.d.ts b/types/hls.js/index.d.ts index 622fadd890..1911413c4f 100644 --- a/types/hls.js/index.d.ts +++ b/types/hls.js/index.d.ts @@ -382,7 +382,7 @@ declare namespace Hls { /** * returns hls.js dist version number */ - const version: number; + const version: string; interface Config { /** diff --git a/types/inline-css/index.d.ts b/types/inline-css/index.d.ts index a6db3ef67b..6d43b7975d 100644 --- a/types/inline-css/index.d.ts +++ b/types/inline-css/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/jonkemp/inline-css // Definitions by: Philip Spain // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/jake/index.d.ts b/types/jake/index.d.ts index cb23f992f0..98fc72d148 100644 --- a/types/jake/index.d.ts +++ b/types/jake/index.d.ts @@ -38,7 +38,7 @@ declare function fail(...err:any[]): void; * @param action The action to perform for this task * @param opts Perform this task asynchronously. If you flag a task with this option, you must call the global `complete` method inside the task's action, for execution to proceed to the next task. */ -declare function file(name:string, prereqs?:string[], action?:()=>void, opts?:jake.FileTaskOptions): jake.FileTask; +declare function file(name:string, prereqs?:string[], action?:(this: jake.FileTask)=>void, opts?:jake.FileTaskOptions): jake.FileTask; /** * Creates Jake FileTask from regex patterns @@ -63,9 +63,9 @@ declare function namespace(name:string, scope:()=>void): void; * @param action The action to perform for this task * @param opts */ -declare function task(name:string, prereqs?:string[], action?:(...params:any[])=>any, opts?:jake.TaskOptions): jake.Task; -declare function task(name:string, action?:(...params:any[])=>any, opts?:jake.TaskOptions): jake.Task; -declare function task(name:string, opts?:jake.TaskOptions, action?:(...params:any[])=>any): jake.Task; +declare function task(name:string, prereqs?:string[], action?:(this: jake.Task, ...params:any[])=>any, opts?:jake.TaskOptions): jake.Task; +declare function task(name:string, action?:(this: jake.Task, ...params:any[])=>any, opts?:jake.TaskOptions): jake.Task; +declare function task(name:string, opts?:jake.TaskOptions, action?:(this: jake.Task, ...params:any[])=>any): jake.Task; /** * @param name The name of the NpmPublishTask @@ -214,7 +214,7 @@ declare namespace jake{ * @param action The action to perform for this task * @param opts Perform this task asynchronously. If you flag a task with this option, you must call the global `complete` method inside the task's action, for execution to proceed to the next task. */ - constructor(name:string, prereqs?:string[], action?:()=>void, opts?:TaskOptions); + constructor(name:string, prereqs?:string[], action?:(this: Task)=>void, opts?:TaskOptions); /** * Runs prerequisites, then this task. If the task has already been run, will not run the task again. @@ -236,10 +236,19 @@ declare namespace jake{ listeners(event: string): Function[]; emit(event: string, ...args: any[]): boolean; listenerCount(type: string): number; + complete(value?: any): void; value: any; + + name?: string; + prereqs?: string[]; + action?: (...params: any[]) => any; + taskStatus?: string; + async?: boolean; + description?: string; + fullName: string; } - export class DirectoryTask{ + export class DirectoryTask extends FileTask { /** * @param name The name of the directory to create. */ @@ -254,14 +263,14 @@ declare namespace jake{ async?: boolean; } - export class FileTask{ + export class FileTask extends Task{ /** * @param name The name of the Task * @param prereqs Prerequisites to be run before this task * @param action The action to perform to create this file * @param opts Perform this task asynchronously. If you flag a task with this option, you must call the global `complete` method inside the task's action, for execution to proceed to the next task. */ - constructor(name:string, prereqs?:string[], action?:()=>void, opts?:FileTaskOptions); + constructor(name:string, prereqs?:string[], action?:(this: FileTask)=>void, opts?:FileTaskOptions); } interface FileFilter{ diff --git a/types/jasmine-ajax/index.d.ts b/types/jasmine-ajax/index.d.ts index dcc6720f04..0d1d92751d 100644 --- a/types/jasmine-ajax/index.d.ts +++ b/types/jasmine-ajax/index.d.ts @@ -24,6 +24,8 @@ interface JasmineAjaxRequest extends XMLHttpRequest { data(): string; respondWith(response: JasmineAjaxResponse): void; + responseTimeout(): void; + responseError(): void; } interface JasmineAjaxRequestTracker { diff --git a/types/jasmine/index.d.ts b/types/jasmine/index.d.ts index 4ebc04eada..f1af5ef514 100644 --- a/types/jasmine/index.d.ts +++ b/types/jasmine/index.d.ts @@ -209,7 +209,7 @@ declare namespace jasmine { withMock(func: () => void): void; } - type CustomEqualityTester = (first: any, second: any) => boolean; + type CustomEqualityTester = (first: any, second: any) => boolean | void; interface CustomMatcher { compare(actual: T, expected: T): CustomMatcherResult; @@ -730,4 +730,4 @@ declare module "jasmine" { helperFiles: string[]; } export = jasmine; -} \ No newline at end of file +} diff --git a/types/jasmine/jasmine-tests.ts b/types/jasmine/jasmine-tests.ts index aaf02a170e..017896ebf5 100644 --- a/types/jasmine/jasmine-tests.ts +++ b/types/jasmine/jasmine-tests.ts @@ -872,7 +872,7 @@ describe("Fail", () => { // test based on http://jasmine.github.io/2.2/custom_equality.html describe("custom equality", () => { - var myCustomEquality: jasmine.CustomEqualityTester = function (first: any, second: any): boolean { + var myCustomEquality: jasmine.CustomEqualityTester = function (first: any, second: any): boolean | void { if (typeof first === "string" && typeof second === "string") { return first[0] === second[1]; } diff --git a/types/java/index.d.ts b/types/java/index.d.ts index 46dc577e35..cf770a8807 100644 --- a/types/java/index.d.ts +++ b/types/java/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/joeferner/node-java // Definitions by: Jim Lloyd , Kentaro Teramoto // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/java/java-tests.ts b/types/java/java-tests.ts index 6d464b36e1..4c79640733 100644 --- a/types/java/java-tests.ts +++ b/types/java/java-tests.ts @@ -1,5 +1,3 @@ -/// - import java = require('java'); import BluePromise = require('bluebird'); @@ -9,7 +7,7 @@ java.asyncOptions = { promiseSuffix: 'P', promisify: BluePromise.promisify }; -// todo: figure out why promise doesn't work here +// todo: figure out why promise doesn't work here /* java.registerClientP((): Promise => { return BluePromise.resolve(); }); */ diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index ac23de158b..b886bdeaac 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Jest 20.0.5 // Project: http://facebook.github.io/jest/ -// Definitions by: Asana , Ivo Stratev , jwbay , Alexey Svetliakov , Alex Jover Morales +// Definitions by: Asana , Ivo Stratev , jwbay , Alexey Svetliakov , Alex Jover Morales , Allan Lukwago // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -114,8 +114,9 @@ declare namespace jest { * * @param {string} name The name of your test * @param {fn?} ProvidesCallback The function for your test + * @param {timeout?} timeout The timeout for an async function test */ - (name: string, fn?: ProvidesCallback): void; + (name: string, fn?: ProvidesCallback, timeout?: number): void; /** Only runs this test in the current file. */ only: It; skip: It; diff --git a/types/jquery.notify/index.d.ts b/types/jquery.notify/index.d.ts new file mode 100644 index 0000000000..9dcf3e5d49 --- /dev/null +++ b/types/jquery.notify/index.d.ts @@ -0,0 +1,32 @@ +// Type definitions for jquery.notify 1.5 +// Project: https://github.com/ehynds/jquery-notify (jQuery Notify UI Widget by Eric Hynds) +// Definitions by: Sergei Dorogin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +interface JQueryNotifyOptions { + close?: () => void; + open?: () => void; + custom?: boolean; + disabled?: boolean; + expires?: number; + queue?: boolean; + speed?: number; + stack?: "below" | "above"; +} +interface JQuery { + notify(options?: JQueryNotifyOptions): JQueryNotifyWidget; + notify(method: string, template: number, params?: object, opts?: JQueryNotifyOptions): JQueryNotifyInstance; + notify(method: string, params?: object, opts?: JQueryNotifyOptions): JQueryNotifyInstance; +} +interface JQueryNotifyInstance { + element: JQuery; + isOpen: boolean; + options: JQueryNotifyOptions; + close(): void; + open(): void; +} +interface JQueryNotifyWidget extends JQuery { +} diff --git a/types/jquery.notify/jquery.notify-tests.ts b/types/jquery.notify/jquery.notify-tests.ts new file mode 100644 index 0000000000..1af31996a1 --- /dev/null +++ b/types/jquery.notify/jquery.notify-tests.ts @@ -0,0 +1,21 @@ +let $container: JQueryNotifyWidget = $("").appendTo(document.body).notify(); + +let notification: JQueryNotifyInstance = $container.notify( + "create", + {}, // empty parameters + { + close: () => { + console.log("closed"); + }, + open: () => { + console.log("opened"); + }, + expires: 1000, + speed: 100 + } +); +notification.element.html("text"); + +notification.element.click(() => { + notification.close(); +}); diff --git a/types/jquery.notify/tsconfig.json b/types/jquery.notify/tsconfig.json new file mode 100644 index 0000000000..0fbfcb5134 --- /dev/null +++ b/types/jquery.notify/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jquery.notify-tests.ts" + ] +} \ No newline at end of file diff --git a/types/jquery.notify/tslint.json b/types/jquery.notify/tslint.json new file mode 100644 index 0000000000..e6098321a2 --- /dev/null +++ b/types/jquery.notify/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-empty-interface": false, + "prefer-method-signature": false + } +} diff --git a/types/jquery/README.md b/types/jquery/README.md new file mode 100644 index 0000000000..8fab451ce0 --- /dev/null +++ b/types/jquery/README.md @@ -0,0 +1,68 @@ +### Usage + +#### Global + +When jQuery is globally available, you can use `jQuery` and `$` directly. + +#### Importing (with a global DOM available) + +When you want to import jQuery as a module and have a global DOM available (e.g. browser and browser-like environments): + +```typescript +import jQuery = require('jquery'); +``` + +#### Importing (without a global DOM available) + +When you want to import jQuery as a module and do not have a global DOM available (e.g. Node.js environment): + +```typescript +import jQueryFactory = require('jquery'); +const jQuery = jQueryFactory(window, true); +``` + +Note that while the factory function ignores the second parameter, it is required to get correct type declarations. + +### Project structure + +- [jquery-tests.ts](jquery-tests.ts) + - Tests that exercise TypeScript-specific usage and cases not covered by other test files. +- [test/example-tests.ts](test/example-tests.ts) + - Tests generated from examples in jQuery documentation. +- [test/longdesc-tests.ts](test/longdesc-tests.ts) + - Tests generated from non-example snippets in jQuery documentation. +- [test/jquery-window-module-tests.ts](test/jquery-window-module-tests.ts)
+ [test/jquery-slim-window-module-tests.ts](test/jquery-slim-window-module-tests.ts) + - Tests importing jQuery with a DOM available +- [test/jquery-no-window-module-tests.ts](test/jquery-no-window-module-tests.ts)
+ [test/jquery-slim-no-window-module-tests.ts](test/jquery-slim-no-window-module-tests.ts) + - Tests importing jQuery without a DOM available + +### Authoring type definitions for jQuery plugins + +`$.fn` is represented by `JQuery`. + +`$` is represented by `JQueryStatic`. + +Declare an interface that has the plugin's overloads as call signatures and static members as properties. + +```typescript +interface MyPlugin { + settings: MyPluginSettings; + + (behavior: 'enable'): JQuery; + (settings?: MyPluginSettings): JQuery; +} + +interface MyPluginSettings { + title?: string; +} +``` + +Then declare a property on `JQuery` with your plugin's type. + +```typescript +interface JQuery { + myPlugin: MyPlugin; +} +``` diff --git a/types/jquery/index.d.ts b/types/jquery/index.d.ts index 598d71bc60..ce32477d98 100644 --- a/types/jquery/index.d.ts +++ b/types/jquery/index.d.ts @@ -25,17 +25,11 @@ // TypeScript Version: 2.3 declare module 'jquery' { - function factory(window: Window): JQueryStatic; - - const factoryOrJQuery: typeof factory & JQueryStatic; - export = factoryOrJQuery; + export = jQuery; } declare module 'jquery/dist/jquery.slim' { - function factory(window: Window): JQueryStatic; - - const factoryOrJQuery: typeof factory & JQueryStatic; - export = factoryOrJQuery; + export = jQuery; } declare const jQuery: JQueryStatic; @@ -68,7 +62,7 @@ interface JQuery { * @see {@link https://api.jquery.com/add/} * @since 1.4 */ - add(selector: JQuery.Selector, context: Element): JQuery; + add(selector: JQuery.Selector, context: Element): this; /** * Create a new jQuery object with elements added to the set of matched elements. * @@ -80,7 +74,7 @@ interface JQuery { * @since 1.0 * @since 1.3.2 */ - add(selector: JQuery.Selector | JQuery.TypeOrArray | JQuery.htmlString | JQuery): JQuery; + add(selector: JQuery.Selector | JQuery.TypeOrArray | JQuery.htmlString | JQuery): this; /** * Add the previous set of elements on the stack to the current set, optionally filtered by a selector. * @@ -109,7 +103,7 @@ interface JQuery { * @see {@link https://api.jquery.com/after/} * @since 1.0 */ - after(...contents: Array | JQuery>): this; + after(...contents: Array | JQuery>): this; /** * Insert content, specified by the parameter, after each element in the set of matched elements. * @@ -121,7 +115,7 @@ interface JQuery { * @since 1.4 * @since 1.10 */ - after(fn: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; + after(fn: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; /** * Register a handler to be called when Ajax requests complete. This is an AjaxEvent. * @@ -129,7 +123,7 @@ interface JQuery { * @see {@link https://api.jquery.com/ajaxComplete/} * @since 1.0 */ - ajaxComplete(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxOptions: JQuery.AjaxSettings) => void | false): this; + ajaxComplete(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxOptions: JQuery.AjaxSettings) => void | false): this; /** * Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event. * @@ -137,7 +131,7 @@ interface JQuery { * @see {@link https://api.jquery.com/ajaxError/} * @since 1.0 */ - ajaxError(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxSettings: JQuery.AjaxSettings, thrownError: string) => void | false): this; + ajaxError(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxSettings: JQuery.AjaxSettings, thrownError: string) => void | false): this; /** * Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. * @@ -145,7 +139,7 @@ interface JQuery { * @see {@link https://api.jquery.com/ajaxSend/} * @since 1.0 */ - ajaxSend(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxOptions: JQuery.AjaxSettings) => void | false): this; + ajaxSend(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxOptions: JQuery.AjaxSettings) => void | false): this; /** * Register a handler to be called when the first Ajax request begins. This is an Ajax Event. * @@ -169,7 +163,7 @@ interface JQuery { * @see {@link https://api.jquery.com/ajaxSuccess/} * @since 1.0 */ - ajaxSuccess(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxOptions: JQuery.AjaxSettings, data: JQuery.PlainObject) => void | false): this; + ajaxSuccess(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxOptions: JQuery.AjaxSettings, data: JQuery.PlainObject) => void | false): this; /** * Perform a custom animation of a set of CSS properties. * @@ -201,15 +195,22 @@ interface JQuery { * Perform a custom animation of a set of CSS properties. * * @param properties An object of CSS properties and values that the animation will move toward. - * @param duration_easing_complete_options A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. - * A map of additional options to pass to the method. + * @param options A map of additional options to pass to the method. * @see {@link https://api.jquery.com/animate/} * @since 1.0 */ animate(properties: JQuery.PlainObject, - duration_easing_complete_options?: JQuery.Duration | string | ((this: TElement) => void) | JQuery.EffectsOptions): this; + options: JQuery.EffectsOptions): this; + /** + * Perform a custom animation of a set of CSS properties. + * + * @param properties An object of CSS properties and values that the animation will move toward. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see {@link https://api.jquery.com/animate/} + * @since 1.0 + */ + animate(properties: JQuery.PlainObject, + complete?: (this: TElement) => void): this; /** * Insert content, specified by the parameter, to the end of each element in the set of matched elements. * @@ -218,7 +219,7 @@ interface JQuery { * @see {@link https://api.jquery.com/append/} * @since 1.0 */ - append(...contents: Array | JQuery>): this; + append(...contents: Array | JQuery>): this; /** * Insert content, specified by the parameter, to the end of each element in the set of matched elements. * @@ -229,7 +230,7 @@ interface JQuery { * @see {@link https://api.jquery.com/append/} * @since 1.4 */ - append(fn: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; + append(fn: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; /** * Insert every element in the set of matched elements to the end of the target. * @@ -276,7 +277,7 @@ interface JQuery { * @see {@link https://api.jquery.com/before/} * @since 1.0 */ - before(...contents: Array | JQuery>): this; + before(...contents: Array | JQuery>): this; /** * Insert content, specified by the parameter, before each element in the set of matched elements. * @@ -288,7 +289,8 @@ interface JQuery { * @since 1.4 * @since 1.10 */ - before(fn: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; + before(fn: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; + // [bind() overloads] https://github.com/jquery/api.jquery.com/issues/1048 /** * Attach a handler to an event for the elements. * @@ -297,43 +299,23 @@ interface JQuery { * @param handler A function to execute each time the event is triggered. * @see {@link https://api.jquery.com/bind/} * @since 1.0 - * @deprecated 3.0 - */ - bind(eventType: string, eventData: TData, handler: JQuery.EventHandler | false): this; - /** - * Attach a handler to an event for the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param eventData An object containing data that will be passed to the event handler. - * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from - * occurring and stops the event from bubbling. The default is true. - * @see {@link https://api.jquery.com/bind/} * @since 1.4.3 * @deprecated 3.0 */ - bind(eventType: string, eventData: any, preventBubble: boolean): this; + bind(eventType: string, eventData: TData, handler: JQuery.EventHandler): this; /** * Attach a handler to an event for the elements. * * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param handler A function to execute each time the event is triggered. + * Setting the second argument to false will attach a function that prevents the default action from + * occurring and stops the event from bubbling. * @see {@link https://api.jquery.com/bind/} * @since 1.0 + * @since 1.4.3 * @deprecated 3.0 */ - bind(eventType: string, handler: JQuery.EventHandler | false): this; - /** - * Attach a handler to an event for the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param preventBubble_eventData Setting the third argument to false will attach a function that prevents the default action from - * occurring and stops the event from bubbling. The default is true. - * An object containing data that will be passed to the event handler. - * @see {@link https://api.jquery.com/bind/} - * @since 1.0 - * @deprecated 3.0 - */ - bind(eventType: string, preventBubble_eventData?: boolean | any): this; + bind(eventType: string, handler: JQuery.EventHandler | false | null | undefined): this; /** * Attach a handler to an event for the elements. * @@ -351,7 +333,7 @@ interface JQuery { * @see {@link https://api.jquery.com/blur/} * @since 1.4.3 */ - blur(eventData: TData, handler: JQuery.EventHandler | false): this; + blur(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to the "blur" JavaScript event, or trigger that event on an element. * @@ -368,7 +350,7 @@ interface JQuery { * @see {@link https://api.jquery.com/change/} * @since 1.4.3 */ - change(eventData: TData, handler: JQuery.EventHandler | false): this; + change(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to the "change" JavaScript event, or trigger that event on an element. * @@ -401,7 +383,7 @@ interface JQuery { * @see {@link https://api.jquery.com/click/} * @since 1.4.3 */ - click(eventData: TData, handler: JQuery.EventHandler | false): this; + click(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to the "click" JavaScript event, or trigger that event on an element. * @@ -444,14 +426,14 @@ interface JQuery { * @since 1.3 * @since 1.6 */ - closest(selector: JQuery.Selector | JQuery | Element): this; + closest(selector: JQuery.Selector | Element | JQuery): this; /** * Get the children of each element in the set of matched elements, including text and comment nodes. * * @see {@link https://api.jquery.com/contents/} * @since 1.2 */ - contents(): this; + contents(): JQuery; /** * Bind an event handler to the "contextmenu" JavaScript event, or trigger that event on an element. * @@ -460,7 +442,7 @@ interface JQuery { * @see {@link https://api.jquery.com/contextmenu/} * @since 1.4.3 */ - contextmenu(eventData: TData, handler: JQuery.EventHandler | false): this; + contextmenu(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to the "contextmenu" JavaScript event, or trigger that event on an element. * @@ -516,8 +498,7 @@ interface JQuery { * @see {@link https://api.jquery.com/data/} * @since 1.2.3 */ - // tslint:disable-next-line:unified-signatures - data(key: string, undefined: undefined): any; + data(key: string, undefined: undefined): any; // tslint:disable-line:unified-signatures /** * Store arbitrary data associated with the matched elements. * @@ -560,7 +541,7 @@ interface JQuery { * @see {@link https://api.jquery.com/dblclick/} * @since 1.4.3 */ - dblclick(eventData: TData, handler: JQuery.EventHandler | false): this; + dblclick(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element. * @@ -591,7 +572,7 @@ interface JQuery { * @since 1.4.2 * @deprecated 3.0 */ - delegate(selector: string, eventType: string, eventData: TData, handler: JQuery.EventHandler | false): this; + delegate(selector: JQuery.Selector, eventType: string, eventData: TData, handler: JQuery.EventHandler): this; /** * Attach a handler to one or more events for all elements that match the selector, now or in the * future, based on a specific set of root elements. @@ -604,7 +585,7 @@ interface JQuery { * @since 1.4.2 * @deprecated 3.0 */ - delegate(selector: string, eventType: string, handler: JQuery.EventHandler | false): this; + delegate(selector: JQuery.Selector, eventType: string, handler: JQuery.EventHandler | false): this; /** * Attach a handler to one or more events for all elements that match the selector, now or in the * future, based on a specific set of root elements. @@ -615,7 +596,7 @@ interface JQuery { * @since 1.4.3 * @deprecated 3.0 */ - delegate(selector: string, events: JQuery.PlainObject | false>): this; + delegate(selector: JQuery.Selector, events: JQuery.PlainObject | false>): this; /** * Execute the next function on the queue for the matched elements. * @@ -639,7 +620,7 @@ interface JQuery { * @see {@link https://api.jquery.com/each/} * @since 1.0 */ - each(fn: (this: TElement, index: number, element: Element) => void | false): this; + each(fn: (this: TElement, index: number, element: TElement) => void | false): this; /** * Remove all child nodes of the set of matched elements from the DOM. * @@ -672,7 +653,7 @@ interface JQuery { * @see {@link https://api.jquery.com/jQuery.fn.extend/} * @since 1.0 */ - extend(obj: object): JQuery; + extend(obj: object): this; /** * Display the matched elements by fading them to opaque. * @@ -693,7 +674,7 @@ interface JQuery { * @since 1.0 * @since 1.4.3 */ - fadeIn(duration_easing: JQuery.Duration | string, complete?: (this: TElement) => void): this; + fadeIn(duration_easing: JQuery.Duration | string, complete: (this: TElement) => void): this; /** * Display the matched elements by fading them to opaque. * @@ -726,7 +707,7 @@ interface JQuery { * @since 1.0 * @since 1.4.3 */ - fadeOut(duration_easing: JQuery.Duration | string, complete?: (this: TElement) => void): this; + fadeOut(duration_easing: JQuery.Duration | string, complete: (this: TElement) => void): this; /** * Hide the matched elements by fading them to transparent. * @@ -780,7 +761,7 @@ interface JQuery { * @since 1.0 * @since 1.4.3 */ - fadeToggle(duration_easing: JQuery.Duration | string, complete?: (this: TElement) => void): this; + fadeToggle(duration_easing: JQuery.Duration | string, complete: (this: TElement) => void): this; /** * Display or hide the matched elements by animating their opacity. * @@ -815,7 +796,7 @@ interface JQuery { * @since 1.0 * @since 1.6 */ - find(selector: JQuery.Selector | Element | JQuery): JQuery; + find(selector: JQuery.Selector | Element | JQuery): this; /** * Stop the currently-running animation, remove all queued animations, and complete all animations for * the matched elements. @@ -840,7 +821,7 @@ interface JQuery { * @see {@link https://api.jquery.com/focus/} * @since 1.4.3 */ - focus(eventData: TData, handler: JQuery.EventHandler | false): this; + focus(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to the "focus" JavaScript event, or trigger that event on an element. * @@ -857,7 +838,7 @@ interface JQuery { * @see {@link https://api.jquery.com/focusin/} * @since 1.4.3 */ - focusin(eventData: TData, handler: JQuery.EventHandler | false): this; + focusin(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to the "focusin" event. * @@ -874,7 +855,7 @@ interface JQuery { * @see {@link https://api.jquery.com/focusout/} * @since 1.4.3 */ - focusout(eventData: TData, handler: JQuery.EventHandler | false): this; + focusout(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to the "focusout" JavaScript event. * @@ -933,7 +914,7 @@ interface JQuery { * @see {@link https://api.jquery.com/height/} * @since 1.0 */ - height(): number; + height(): number | undefined; /** * Hide the matched elements. * @@ -975,8 +956,7 @@ interface JQuery { * @since 1.0 * @since 1.4 */ - hover(handlerInOut: (this: TElement, eventObject: JQuery.Event) => void | false, - handlerOut?: (this: TElement, eventObject: JQuery.Event) => void | false): this; + hover(handlerInOut: JQuery.EventHandler | false, handlerOut?: JQuery.EventHandler | false): this; /** * Set the HTML contents of each element in the set of matched elements. * @@ -1005,7 +985,7 @@ interface JQuery { * @since 1.0 * @since 1.4 */ - index(element?: Element | JQuery | JQuery.Selector): number; + index(element?: JQuery.Selector | Element | JQuery): number; /** * Set the CSS inner height of each element in the set of matched elements. * @@ -1025,7 +1005,7 @@ interface JQuery { * @see {@link https://api.jquery.com/innerHeight/} * @since 1.2.6 */ - innerHeight(): number; + innerHeight(): number | undefined; /** * Set the CSS inner width of each element in the set of matched elements. * @@ -1045,7 +1025,7 @@ interface JQuery { * @see {@link https://api.jquery.com/innerWidth/} * @since 1.2.6 */ - innerWidth(): number; + innerWidth(): number | undefined; /** * Insert every element in the set of matched elements after the target. * @@ -1078,7 +1058,7 @@ interface JQuery { * @since 1.0 * @since 1.6 */ - is(selector: JQuery.Selector | ((this: TElement, index: number, element: TElement) => boolean) | JQuery | Element | Element[]): boolean; + is(selector: JQuery.Selector | JQuery.TypeOrArray | JQuery | ((this: TElement, index: number, element: TElement) => boolean)): boolean; /** * Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element. * @@ -1087,7 +1067,7 @@ interface JQuery { * @see {@link https://api.jquery.com/keydown/} * @since 1.4.3 */ - keydown(eventData: TData, handler: JQuery.EventHandler | false): this; + keydown(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element. * @@ -1104,7 +1084,7 @@ interface JQuery { * @see {@link https://api.jquery.com/keypress/} * @since 1.4.3 */ - keypress(eventData: TData, handler: JQuery.EventHandler | false): this; + keypress(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element. * @@ -1121,7 +1101,7 @@ interface JQuery { * @see {@link https://api.jquery.com/keyup/} * @since 1.4.3 */ - keyup(eventData: TData, handler: JQuery.EventHandler | false): this; + keyup(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element. * @@ -1148,7 +1128,7 @@ interface JQuery { */ load(url: string, data: string | JQuery.PlainObject, - complete: (this: TElement, responseText: string, textStatus: string, jqXHR: JQuery.jqXHR) => void): this; + complete: (this: TElement, responseText: string, textStatus: JQuery.Ajax.TextStatus, jqXHR: JQuery.jqXHR) => void): this; /** * Load data from the server and place the returned HTML into the matched element. * @@ -1159,7 +1139,7 @@ interface JQuery { * @since 1.0 */ load(url: string, - complete_data?: ((this: TElement, responseText: string, textStatus: string, jqXHR: JQuery.jqXHR) => void) | string | JQuery.PlainObject): this; + complete_data?: ((this: TElement, responseText: string, textStatus: JQuery.Ajax.TextStatus, jqXHR: JQuery.jqXHR) => void) | string | JQuery.PlainObject): this; /** * Pass each element in the current matched set through a function, producing a new jQuery object * containing the return values. @@ -1168,7 +1148,7 @@ interface JQuery { * @see {@link https://api.jquery.com/map/} * @since 1.2 */ - map(callback: (this: TElement, index: number, domElement: TElement) => any | any[] | null | undefined): JQuery; + map(callback: (this: TElement, index: number, domElement: TElement) => any | any[] | null | undefined): this; /** * Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element. * @@ -1177,7 +1157,7 @@ interface JQuery { * @see {@link https://api.jquery.com/mousedown/} * @since 1.4.3 */ - mousedown(eventData: TData, handler: JQuery.EventHandler | false): this; + mousedown(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element. * @@ -1194,7 +1174,7 @@ interface JQuery { * @see {@link https://api.jquery.com/mouseenter/} * @since 1.4.3 */ - mouseenter(eventData: TData, handler: JQuery.EventHandler | false): this; + mouseenter(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element. * @@ -1211,7 +1191,7 @@ interface JQuery { * @see {@link https://api.jquery.com/mouseleave/} * @since 1.4.3 */ - mouseleave(eventData: TData, handler: JQuery.EventHandler | false): this; + mouseleave(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element. * @@ -1228,7 +1208,7 @@ interface JQuery { * @see {@link https://api.jquery.com/mousemove/} * @since 1.4.3 */ - mousemove(eventData: TData, handler: JQuery.EventHandler | false): this; + mousemove(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element. * @@ -1245,7 +1225,7 @@ interface JQuery { * @see {@link https://api.jquery.com/mouseout/} * @since 1.4.3 */ - mouseout(eventData: TData, handler: JQuery.EventHandler | false): this; + mouseout(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element. * @@ -1262,7 +1242,7 @@ interface JQuery { * @see {@link https://api.jquery.com/mouseover/} * @since 1.4.3 */ - mouseover(eventData: TData, handler: JQuery.EventHandler | false): this; + mouseover(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element. * @@ -1279,7 +1259,7 @@ interface JQuery { * @see {@link https://api.jquery.com/mouseup/} * @since 1.4.3 */ - mouseup(eventData: TData, handler: JQuery.EventHandler | false): this; + mouseup(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element. * @@ -1329,7 +1309,7 @@ interface JQuery { * @since 1.0 * @since 1.4 */ - not(selector: JQuery.Selector | JQuery.TypeOrArray | ((this: TElement, index: number, element: TElement) => boolean) | JQuery): this; + not(selector: JQuery.Selector | JQuery.TypeOrArray | JQuery | ((this: TElement, index: number, element: TElement) => boolean)): this; /** * Remove an event handler. * @@ -1340,17 +1320,7 @@ interface JQuery { * @see {@link https://api.jquery.com/off/} * @since 1.7 */ - off(events: string, selector: string, handler: JQuery.EventHandler | false): this; - /** - * Remove an event handler. - * - * @param events An object where the string keys represent one or more space-separated event types and optional - * namespaces, and the values represent handler functions previously attached for the event(s). - * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. - * @see {@link https://api.jquery.com/off/} - * @since 1.7 - */ - off(events: JQuery.PlainObject | false>, selector: string): this; + off(events: string, selector: JQuery.Selector, handler: JQuery.EventHandler | false): this; /** * Remove an event handler. * @@ -1361,17 +1331,25 @@ interface JQuery { * @see {@link https://api.jquery.com/off/} * @since 1.7 */ - off(events: string, selector_handler?: string | JQuery.EventHandler | false): this; + off(events: string, selector_handler?: JQuery.Selector | JQuery.EventHandler | false): this; /** * Remove an event handler. * - * @param events A jQuery.Event object. - * An object where the string keys represent one or more space-separated event types and optional + * @param events An object where the string keys represent one or more space-separated event types and optional * namespaces, and the values represent handler functions previously attached for the event(s). + * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. * @see {@link https://api.jquery.com/off/} * @since 1.7 */ - off(events?: JQuery.Event | JQuery.PlainObject | false>): this; + off(events: JQuery.PlainObject | false>, selector?: JQuery.Selector): this; + /** + * Remove an event handler. + * + * @param event A jQuery.Event object. + * @see {@link https://api.jquery.com/off/} + * @since 1.7 + */ + off(event?: JQuery.Event): this; /** * Set the current coordinates of every element in the set of matched elements, relative to the document. * @@ -1405,37 +1383,33 @@ interface JQuery { * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the * selector is null or omitted, the event is always triggered when it reaches the selected element. * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand - * for a function that simply does return false. + * @param handler A function to execute when the event is triggered. * @see {@link https://api.jquery.com/on/} * @since 1.7 */ - on(events: string, selector: string | null, data: TData, handler: JQuery.EventHandler | false): this; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events An object in which the string keys represent one or more space-separated event types and optional - * namespaces, and the values represent a handler function to be called for the event(s). - * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If - * the selector is null or omitted, the handler is always called when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event occurs. - * @see {@link https://api.jquery.com/on/} - * @since 1.7 - */ - on(events: JQuery.PlainObject | false>, selector: string | null, data: TData): this; + on(events: string, selector: JQuery.Selector | null, data: TData, handler: JQuery.EventHandler): this; /** * Attach an event handler function for one or more events to the selected elements. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector_data A selector string to filter the descendants of the selected elements that trigger the event. If the - * selector is null or omitted, the event is always triggered when it reaches the selected element. - * Data to be passed to the handler in event.data when an event is triggered. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the + * selector is null or omitted, the event is always triggered when it reaches the selected element. * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand * for a function that simply does return false. * @see {@link https://api.jquery.com/on/} * @since 1.7 */ - on(events: string, selector_data: string | null | TData, handler: JQuery.EventHandler | false): this; + on(events: string, selector: JQuery.Selector | null, handler: JQuery.EventHandler | false): this; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. + * @see {@link https://api.jquery.com/on/} + * @since 1.7 + */ + on(events: string, data: TData, handler: JQuery.EventHandler): this; /** * Attach an event handler function for one or more events to the selected elements. * @@ -1451,13 +1425,43 @@ interface JQuery { * * @param events An object in which the string keys represent one or more space-separated event types and optional * namespaces, and the values represent a handler function to be called for the event(s). - * @param selector_data A selector string to filter the descendants of the selected elements that will call the handler. If - * the selector is null or omitted, the handler is always called when it reaches the selected element. - * Data to be passed to the handler in event.data when an event occurs. + * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If + * the selector is null or omitted, the handler is always called when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event occurs. * @see {@link https://api.jquery.com/on/} * @since 1.7 */ - on(events: JQuery.PlainObject | false>, selector_data?: string | null | TData): this; + on(events: JQuery.PlainObject | false>, selector: JQuery.Selector | null, data: TData): this; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional + * namespaces, and the values represent a handler function to be called for the event(s). + * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If + * the selector is null or omitted, the handler is always called when it reaches the selected element. + * @see {@link https://api.jquery.com/on/} + * @since 1.7 + */ + on(events: JQuery.PlainObject | false>, selector: JQuery.Selector): this; // tslint:disable-line:unified-signatures + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional + * namespaces, and the values represent a handler function to be called for the event(s). + * @param data Data to be passed to the handler in event.data when an event occurs. + * @see {@link https://api.jquery.com/on/} + * @since 1.7 + */ + on(events: JQuery.PlainObject | false>, data: TData): this; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional + * namespaces, and the values represent a handler function to be called for the event(s). + * @see {@link https://api.jquery.com/on/} + * @since 1.7 + */ + on(events: JQuery.PlainObject | false>): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @@ -1465,37 +1469,33 @@ interface JQuery { * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the * selector is null or omitted, the event is always triggered when it reaches the selected element. * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand - * for a function that simply does return false. + * @param handler A function to execute when the event is triggered. * @see {@link https://api.jquery.com/one/} * @since 1.7 */ - one(events: string, selector: string | null, data: TData, handler: JQuery.EventHandler | false): this; + one(events: string, selector: JQuery.Selector | null, data: TData, handler: JQuery.EventHandler): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector_data A selector string to filter the descendants of the selected elements that trigger the event. If the - * selector is null or omitted, the event is always triggered when it reaches the selected element. - * Data to be passed to the handler in event.data when an event is triggered. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the + * selector is null or omitted, the event is always triggered when it reaches the selected element. * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand * for a function that simply does return false. * @see {@link https://api.jquery.com/one/} * @since 1.7 */ - one(events: string, selector_data: string | null | TData, handler: JQuery.EventHandler | false): this; + one(events: string, selector: JQuery.Selector | null, handler: JQuery.EventHandler | false): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * - * @param events An object in which the string keys represent one or more space-separated event types and optional - * namespaces, and the values represent a handler function to be called for the event(s). - * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If - * the selector is null or omitted, the handler is always called when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event occurs. + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. * @see {@link https://api.jquery.com/one/} * @since 1.7 */ - one(events: JQuery.PlainObject | false>, selector: string | null, data: TData): this; + one(events: string, data: TData, handler: JQuery.EventHandler): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @@ -1511,13 +1511,43 @@ interface JQuery { * * @param events An object in which the string keys represent one or more space-separated event types and optional * namespaces, and the values represent a handler function to be called for the event(s). - * @param selector_data A selector string to filter the descendants of the selected elements that will call the handler. If - * the selector is null or omitted, the handler is always called when it reaches the selected element. - * Data to be passed to the handler in event.data when an event occurs. + * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If + * the selector is null or omitted, the handler is always called when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event occurs. * @see {@link https://api.jquery.com/one/} * @since 1.7 */ - one(events: JQuery.PlainObject | false>, selector_data?: string | null | TData): this; + one(events: JQuery.PlainObject | false>, selector: JQuery.Selector | null, data: TData): this; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional + * namespaces, and the values represent a handler function to be called for the event(s). + * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If + * the selector is null or omitted, the handler is always called when it reaches the selected element. + * @see {@link https://api.jquery.com/one/} + * @since 1.7 + */ + one(events: JQuery.PlainObject | false>, selector: JQuery.Selector): this; // tslint:disable-line:unified-signatures + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional + * namespaces, and the values represent a handler function to be called for the event(s). + * @param data Data to be passed to the handler in event.data when an event occurs. + * @see {@link https://api.jquery.com/one/} + * @since 1.7 + */ + one(events: JQuery.PlainObject | false>, data: TData): this; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional + * namespaces, and the values represent a handler function to be called for the event(s). + * @see {@link https://api.jquery.com/one/} + * @since 1.7 + */ + one(events: JQuery.PlainObject | false>): this; /** * Set the CSS outer height of each element in the set of matched elements. * @@ -1535,7 +1565,7 @@ interface JQuery { * @see {@link https://api.jquery.com/outerHeight/} * @since 1.2.6 */ - outerHeight(includeMargin?: boolean): number; + outerHeight(includeMargin?: boolean): number | undefined; /** * Set the CSS outer width of each element in the set of matched elements. * @@ -1555,7 +1585,7 @@ interface JQuery { * @see {@link https://api.jquery.com/outerWidth/} * @since 1.2.6 */ - outerWidth(includeMargin?: boolean): number; + outerWidth(includeMargin?: boolean): number | undefined; /** * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. * @@ -1599,7 +1629,7 @@ interface JQuery { * @see {@link https://api.jquery.com/prepend/} * @since 1.0 */ - prepend(...contents: Array | JQuery>): this; + prepend(...contents: Array | JQuery>): this; /** * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. * @@ -1610,7 +1640,7 @@ interface JQuery { * @see {@link https://api.jquery.com/prepend/} * @since 1.4 */ - prepend(fn: (this: TElement, elementOfArray: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; + prepend(fn: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; /** * Insert every element in the set of matched elements to the beginning of the target. * @@ -1619,7 +1649,7 @@ interface JQuery { * @see {@link https://api.jquery.com/prependTo/} * @since 1.0 */ - prependTo(target: JQuery.Selector | JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; + prependTo(target: JQuery.Selector | JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; /** * Get the immediately preceding sibling of each element in the set of matched elements. If a selector * is provided, it retrieves the previous sibling only if it matches that selector. @@ -1658,7 +1688,7 @@ interface JQuery { * @see {@link https://api.jquery.com/promise/} * @since 1.6 */ - promise(type: string, target: T): T & JQuery.Promise; + promise(type: string, target: T): T & JQuery.Promise; /** * Return a Promise object to observe when all actions of a certain type bound to the collection, * queued or not, have finished. @@ -1667,7 +1697,7 @@ interface JQuery { * @see {@link https://api.jquery.com/promise/} * @since 1.6 */ - promise(target: T): T & JQuery.Promise; + promise(target: T): T & JQuery.Promise; /** * Return a Promise object to observe when all actions of a certain type bound to the collection, * queued or not, have finished. @@ -1695,8 +1725,7 @@ interface JQuery { * @see {@link https://api.jquery.com/prop/} * @since 1.6 */ - // tslint:disable-next-line:unified-signatures - prop(propertyName: string, value: any): this; + prop(propertyName: string, value: any): this; // tslint:disable-line:unified-signatures /** * Set one or more properties for the set of matched elements. * @@ -1722,7 +1751,7 @@ interface JQuery { * @see {@link https://api.jquery.com/pushStack/} * @since 1.3 */ - pushStack(elements: ArrayLike, name: string, args: any[]): JQuery; + pushStack(elements: ArrayLike, name: string, args: any[]): this; /** * Add a collection of DOM elements onto the jQuery stack. * @@ -1730,7 +1759,7 @@ interface JQuery { * @see {@link https://api.jquery.com/pushStack/} * @since 1.0 */ - pushStack(elements: ArrayLike): JQuery; + pushStack(elements: ArrayLike): this; /** * Manipulate the queue of functions to be executed, once for each matched element. * @@ -1765,7 +1794,7 @@ interface JQuery { * @see {@link https://api.jquery.com/ready/} * @since 1.0 */ - ready(handler: ($: JQueryStatic) => void): this; + ready(handler: ($: JQueryStatic) => void): this; /** * Remove the set of matched elements from the DOM. * @@ -1829,7 +1858,7 @@ interface JQuery { * @since 1.2 * @since 1.4 */ - replaceWith(newContent: JQuery.htmlString | JQuery.TypeOrArray | JQuery | ((this: TElement) => any)): JQuery; + replaceWith(newContent: JQuery.htmlString | JQuery | JQuery.TypeOrArray | ((this: TElement) => any)): this; /** * Bind an event handler to the "resize" JavaScript event, or trigger that event on an element. * @@ -1838,7 +1867,7 @@ interface JQuery { * @see {@link https://api.jquery.com/resize/} * @since 1.4.3 */ - resize(eventData: TData, handler: JQuery.EventHandler | false): this; + resize(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to the "resize" JavaScript event, or trigger that event on an element. * @@ -1855,7 +1884,7 @@ interface JQuery { * @see {@link https://api.jquery.com/scroll/} * @since 1.4.3 */ - scroll(eventData: TData, handler: JQuery.EventHandler | false): this; + scroll(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element. * @@ -1903,7 +1932,7 @@ interface JQuery { * @see {@link https://api.jquery.com/select/} * @since 1.4.3 */ - select(eventData: TData, handler: JQuery.EventHandler | false): this; + select(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to the "select" JavaScript event, or trigger that event on an element. * @@ -1996,7 +2025,7 @@ interface JQuery { * @since 1.0 * @since 1.4.3 */ - slideDown(duration_easing: JQuery.Duration | string, complete?: (this: TElement) => void): this; + slideDown(duration_easing: JQuery.Duration | string, complete: (this: TElement) => void): this; /** * Display the matched elements with a sliding motion. * @@ -2029,7 +2058,7 @@ interface JQuery { * @since 1.0 * @since 1.4.3 */ - slideToggle(duration_easing: JQuery.Duration | string, complete?: (this: TElement) => void): this; + slideToggle(duration_easing: JQuery.Duration | string, complete: (this: TElement) => void): this; /** * Display or hide the matched elements with a sliding motion. * @@ -2062,7 +2091,7 @@ interface JQuery { * @since 1.0 * @since 1.4.3 */ - slideUp(duration_easing: JQuery.Duration | string, complete?: (this: TElement) => void): this; + slideUp(duration_easing: JQuery.Duration | string, complete: (this: TElement) => void): this; /** * Hide the matched elements with a sliding motion. * @@ -2102,7 +2131,7 @@ interface JQuery { * @see {@link https://api.jquery.com/submit/} * @since 1.4.3 */ - submit(eventData: TData, handler: JQuery.EventHandler | false): this; + submit(eventData: TData, handler: JQuery.EventHandler): this; /** * Bind an event handler to the "submit" JavaScript event, or trigger that event on an element. * @@ -2155,17 +2184,19 @@ interface JQuery { * @see {@link https://api.jquery.com/toggle/} * @since 1.0 */ - toggle(duration: JQuery.Duration, complete?: (this: TElement) => void): this; + toggle(duration: JQuery.Duration, complete: (this: TElement) => void): this; /** * Display or hide the matched elements. * - * @param options A map of additional options to pass to the method. - * Use true to show the element or false to hide it. + * @param duration_complete_options_display A string or number determining how long the animation will run. + * A function to call once the animation is complete, called once per matched element. + * A map of additional options to pass to the method. + * Use true to show the element or false to hide it. * @see {@link https://api.jquery.com/toggle/} * @since 1.0 * @since 1.3 */ - toggle(options?: JQuery.EffectsOptions | boolean): this; + toggle(duration_complete_options_display?: JQuery.Duration | ((this: TElement) => void) | JQuery.EffectsOptions | boolean): this; /** * Add or remove one or more classes from each element in the set of matched elements, depending on * either the class's presence or the value of the state argument. @@ -2179,10 +2210,11 @@ interface JQuery { * @since 1.3 * @since 1.4 */ - toggleClass(className: string | ((this: TElement, index: number, className: string, state: boolean) => string), - state?: boolean): this; + toggleClass(className: string | ((this: TElement, index: number, className: string, state: TState) => string), + state?: TState): this; /** - * + * Add or remove one or more classes from each element in the set of matched elements, depending on + * either the class's presence or the value of the state argument. * * @param state A boolean value to determine whether the class should be added or removed. * @see {@link https://api.jquery.com/toggleClass/} @@ -2200,7 +2232,7 @@ interface JQuery { * @since 1.0 * @since 1.3 */ - trigger(eventType: string | JQuery.Event, extraParameters?: any[] | JQuery.PlainObject): this; + trigger(eventType: string | JQuery.Event, extraParameters?: any[] | JQuery.PlainObject | string | number): this; /** * Execute all handlers attached to an element for an event. * @@ -2211,7 +2243,7 @@ interface JQuery { * @since 1.2 * @since 1.3 */ - triggerHandler(eventType: string | JQuery.Event, extraParameters?: any[] | JQuery.PlainObject): undefined | any; + triggerHandler(eventType: string | JQuery.Event, extraParameters?: any[] | JQuery.PlainObject | string | number): undefined | any; /** * Remove a previously-attached event handler from the elements. * @@ -2316,7 +2348,7 @@ interface JQuery { * @see {@link https://api.jquery.com/width/} * @since 1.0 */ - width(): number; + width(): number | undefined; /** * Wrap an HTML structure around each element in the set of matched elements. * @@ -2356,7 +2388,7 @@ interface JQuery { * @since 1.2 * @since 1.4 */ - wrapInner(wrappingElement: JQuery.htmlString | JQuery.Selector | JQuery | Element | ((this: TElement, index: number) => string)): this; + wrapInner(wrappingElement: JQuery.Selector | JQuery.htmlString | Element | JQuery | ((this: TElement, index: number) => string | JQuery | Element)): this; } interface JQuery extends ArrayLike, Iterable { } @@ -2379,7 +2411,7 @@ interface JQueryStatic { * @since 1.4.3 */ cssNumber: JQuery.PlainObject; - readonly fn: JQuery; + readonly fn: JQuery; fx: { /** * The rate (in milliseconds) at which animations fire. @@ -2404,7 +2436,7 @@ interface JQueryStatic { * @see {@link https://api.jquery.com/jQuery.ready/} * @since 1.8 */ - ready: JQuery.Thenable; + ready: JQuery.Thenable>; /** * A collection of properties that represent the presence of different browser features or bugs. * Intended for jQuery's internal use; specific properties may be removed when they are no longer @@ -2438,7 +2470,10 @@ interface JQueryStatic { * @see {@link https://api.jquery.com/jQuery/} * @since 1.0 */ - (selector: JQuery.Selector, context: Element | Document | JQuery): JQuery; + (selector: JQuery.Selector, context: Element | Document | JQuery | undefined): JQuery; + // HACK: This is the factory function returned when importing jQuery without a DOM. Declaring it separately breaks using the type parameter on JQueryStatic. + // HACK: The discriminator parameter handles the edge case of passing a Window object to JQueryStatic. It doesn't actually exist on the factory function. + (window: Window, discriminator: boolean): JQueryStatic; /** * Creates DOM elements on the fly from the provided string of raw HTML. * @@ -2454,7 +2489,9 @@ interface JQueryStatic { * @since 1.0 * @since 1.4 */ - (selector_object_callback?: JQuery.Selector | JQuery.TypeOrArray | JQuery.PlainObject | JQuery | (($: JQueryStatic) => void)): JQuery; + (selector_object_callback?: JQuery.Selector | JQuery.htmlString | JQuery.TypeOrArray | JQuery | + JQuery.PlainObject | + ((this: Document, $: JQueryStatic) => void)): JQuery; /** * A multi-purpose callbacks list object that provides a powerful way to manage callback lists. * @@ -2553,8 +2590,7 @@ interface JQueryStatic { * @see {@link https://api.jquery.com/jQuery.data/} * @since 1.2.3 */ - // tslint:disable-next-line:unified-signatures - data(element: Element, key: string, undefined: undefined): any; + data(element: Element, key: string, undefined: undefined): any; // tslint:disable-line:unified-signatures /** * Store arbitrary data associated with the specified element. Returns the value that was set. * @@ -2595,7 +2631,7 @@ interface JQueryStatic { * @see {@link https://api.jquery.com/jQuery.each/} * @since 1.0 */ - each(array: ArrayLike, callback: (indexInArray: number, value: T) => false | any): ArrayLike; + each(array: ArrayLike, callback: (this: T, indexInArray: number, value: T) => false | any): ArrayLike; /** * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. * Arrays and array-like objects with a length property (such as a function's arguments object) are @@ -2606,7 +2642,7 @@ interface JQueryStatic { * @see {@link https://api.jquery.com/jQuery.each/} * @since 1.0 */ - each(obj: T, callback: (propertyName: K, valueOfProperty: T[K]) => false | any): T; + each(obj: T, callback: (this: T[K], propertyName: K, valueOfProperty: T[K]) => false | any): T; /** * Takes a string and throws an exception containing it. * @@ -2614,7 +2650,7 @@ interface JQueryStatic { * @see {@link https://api.jquery.com/jQuery.error/} * @since 1.4.1 */ - error(message: string): never; + error(message: string): any; /** * Escapes any character that has a special meaning in a CSS selector. * @@ -2685,7 +2721,7 @@ interface JQueryStatic { * @see {@link https://api.jquery.com/jQuery.extend/} * @since 1.1.4 */ - extend(deep: true, target: T, ...objects: U[]): T & U; + extend(deep: true, target: any, object1: any, ...objects: any[]): any; /** * Merge the contents of two or more objects together into the first object. * @@ -2748,7 +2784,7 @@ interface JQueryStatic { * @see {@link https://api.jquery.com/jQuery.extend/} * @since 1.0 */ - extend(target: T, ...objects: U[]): T & U; + extend(target: any, object1: any, ...objects: any[]): any; /** * Load data from the server using a HTTP GET request. * @@ -2801,7 +2837,7 @@ interface JQueryStatic { * @since 1.12 * @since 2.2 */ - get(url_settings?: string | JQuery.AjaxSettings): JQuery.jqXHR; + get(url_settings?: string | JQuery.UrlAjaxSettings): JQuery.jqXHR; /** * Load JSON-encoded data from the server using a GET HTTP request. * @@ -2834,7 +2870,7 @@ interface JQueryStatic { * @since 1.0 */ getScript(url: string, - success?: JQuery.jqXHR.DoneCallback): JQuery.jqXHR; + success?: JQuery.jqXHR.DoneCallback): JQuery.jqXHR; /** * Execute some JavaScript code globally. * @@ -2881,7 +2917,7 @@ interface JQueryStatic { * @see {@link https://api.jquery.com/jQuery.htmlPrefilter/} * @since 1.12/2.2 */ - htmlPrefilter(html: string): string; + htmlPrefilter(html: JQuery.htmlString): JQuery.htmlString; /** * Search for a specified value within an array and return its index (or -1 if not found). * @@ -2995,7 +3031,7 @@ interface JQueryStatic { * @see {@link https://api.jquery.com/jQuery.noConflict/} * @since 1.0 */ - noConflict(removeAll?: boolean): JQueryStatic; + noConflict(removeAll?: boolean): this; /** * An empty function. * @@ -3031,7 +3067,7 @@ interface JQueryStatic { * @see {@link https://api.jquery.com/jQuery.parseHTML/} * @since 1.8 */ - parseHTML(data: string, context: Document | null | undefined, keepScripts: boolean): Node[]; + parseHTML(data: string, context: Document | null | undefined, keepScripts: boolean): JQuery.Node[]; /** * Parses a string into an array of DOM nodes. * @@ -3041,7 +3077,7 @@ interface JQueryStatic { * @see {@link https://api.jquery.com/jQuery.parseHTML/} * @since 1.8 */ - parseHTML(data: string, context_keepScripts?: Document | null | undefined | boolean): Node[]; + parseHTML(data: string, context_keepScripts?: Document | null | undefined | boolean): JQuery.Node[]; /** * Takes a well-formed JSON string and returns the resulting JavaScript value. * @@ -3111,7 +3147,7 @@ interface JQueryStatic { * @since 1.12 * @since 2.2 */ - post(url_settings?: string | JQuery.AjaxSettings): JQuery.jqXHR; + post(url_settings?: string | JQuery.UrlAjaxSettings): JQuery.jqXHR; /** * Takes a function and returns a new one that will always have a particular context. * @@ -3144,16 +3180,7 @@ interface JQueryStatic { * @see {@link https://api.jquery.com/jQuery.queue/} * @since 1.3 */ - queue(element: Element, queueName: string, newQueue: JQuery.TypeOrArray>): JQuery; - /** - * Show the queue of functions to be executed on the matched element. - * - * @param element A DOM element to inspect for an attached queue. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @see {@link https://api.jquery.com/jQuery.queue/} - * @since 1.3 - */ - queue(element: Element, queueName?: string): JQuery.Queue; + queue(element: T, queueName?: string, newQueue?: JQuery.TypeOrArray>): JQuery.Queue; /** * Handles errors thrown synchronously in functions wrapped in jQuery(). * @@ -3170,7 +3197,7 @@ interface JQueryStatic { * @see {@link https://api.jquery.com/jQuery.removeData/} * @since 1.2.3 */ - removeData(element: Element, name?: string): JQuery; + removeData(element: Element, name?: string): void; /** * Creates an object containing a set of properties ready to be used in the definition of custom animations. * @@ -3181,38 +3208,28 @@ interface JQueryStatic { * @since 1.1 */ speed(duration: JQuery.Duration, easing: string, complete: (this: TElement) => void): JQuery.EffectsOptions; - /** - * Creates an object containing a set of properties ready to be used in the definition of custom animations. - * - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/jQuery.speed/} - * @since 1.1 - */ - speed(easing: string, complete: (this: TElement) => void): JQuery.EffectsOptions; /** * Creates an object containing a set of properties ready to be used in the definition of custom animations. * * @param duration A string or number determining how long the animation will run. - * @param easing_complete_settings A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. + * @param easing_complete A string indicating which easing function to use for the transition. + * A function to call once the animation is complete, called once per matched element. * @see {@link https://api.jquery.com/jQuery.speed/} * @since 1.0 * @since 1.1 */ speed(duration: JQuery.Duration, - easing_complete_settings: string | ((this: TElement) => void) | JQuery.SpeedSettings): JQuery.EffectsOptions; + easing_complete: string | ((this: TElement) => void)): JQuery.EffectsOptions; /** * Creates an object containing a set of properties ready to be used in the definition of custom animations. * - * @param duration_easing_complete_settings A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. + * @param duration_complete_settings A string or number determining how long the animation will run. + * A function to call once the animation is complete, called once per matched element. * @see {@link https://api.jquery.com/jQuery.speed/} * @since 1.0 * @since 1.1 */ - speed(duration_easing_complete_settings?: JQuery.Duration | string | ((this: TElement) => void) | JQuery.SpeedSettings): JQuery.EffectsOptions; + speed(duration_complete_settings?: JQuery.Duration | ((this: TElement) => void) | JQuery.SpeedSettings): JQuery.EffectsOptions; /** * Remove the whitespace from the beginning and end of a string. * @@ -3264,6 +3281,7 @@ interface JQueryStatic { declare namespace JQuery { type TypeOrArray = T | T[]; + type Node = Element | Text | Comment; /** * A string is designated htmlString in jQuery documentation when it is used to represent one or more @@ -3291,262 +3309,18 @@ declare namespace JQuery { // region Ajax - /** - * @see {@link http://api.jquery.com/jquery.ajax/#jQuery-ajax-settings} - */ - interface AjaxSettings { - /** - * A set of key/value pairs that map a given dataType to its MIME type, which gets sent in the Accept - * request header. This header tells the server what kind of response it will accept in return. - */ - accepts?: PlainObject; - /** - * By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need - * synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests - * do not support synchronous operation. Note that synchronous requests may temporarily lock the - * browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: - * false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback - * options instead of the corresponding methods of the jqXHR object such as jqXHR.done(). - */ - async?: boolean; - /** - * A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, - * XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and - * settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend - * function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless - * of the type of request. - */ - beforeSend?(this: TContext, jqXHR: jqXHR, settings: AjaxSettings): false | void; - /** - * If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache - * to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" - * to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a - * POST is made to a URL that has already been requested by a GET. - */ - cache?: boolean; - /** - * A function to be called when the request finishes (after success and error callbacks are executed). - * The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a - * string categorizing the status of the request ("success", "notmodified", "nocontent", "error", - * "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of - * functions. Each function will be called in turn. This is an Ajax Event. - */ - complete?: TypeOrArray>; - /** - * An object of string/regular-expression pairs that determine how jQuery will parse the response, - * given its content type. - */ - contents?: PlainObject; - /** - * When sending data to the server, use this content type. Default is - * "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly - * pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). - * As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. Note: The W3C - * XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset - * will not force the browser to change the encoding. Note: For cross-domain requests, setting the - * content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or - * text/plain will trigger the browser to send a preflight OPTIONS request to the server. - */ - contentType?: string | false; - /** - * This object will be the context of all Ajax-related callbacks. By default, the context is an object - * that represents the Ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). - */ - context?: TContext; - /** - * An object containing dataType-to-dataType converters. Each converter's value is a function that - * returns the transformed value of the response. - */ - converters?: PlainObject<((value: any) => any) | true>; - /** - * If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of - * crossDomain to true. This allows, for example, server-side redirection to another domain. - */ - crossDomain?: boolean; - /** - * Data to be sent to the server. It is converted to a query string, if not already a string. It's - * appended to the url for GET-requests. See processData option to prevent this automatic processing. - * Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same - * key based on the value of the traditional setting (described below). - */ - data?: PlainObject | string | any[]; - /** - * A function to be used to handle the raw response data of XMLHttpRequest. This is a pre-filtering - * function to sanitize the response. You should return the sanitized data. The function accepts two - * arguments: The raw data returned from the server and the 'dataType' parameter. - */ - dataFilter?(data: string, type: string): any; - /** - * The type of data that you're expecting back from the server. If none is specified, jQuery will try - * to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON - * will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be - * returned as a string). The available types (and the result passed as the first argument to your - * success callback) are: - * - * "xml": Returns a XML document that can be processed via jQuery. - * - * "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM. - * - * "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by - * appending a query string parameter, _=[TIMESTAMP], to the URL unless the cache option is set to - * true. Note: This will turn POSTs into GETs for remote-domain requests. - * - * "json": Evaluates the response as JSON and returns a JavaScript object. Cross-domain "json" requests - * are converted to "jsonp" unless the request includes jsonp: false in its request options. The JSON - * data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of - * jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} - * instead. (See json.org for more information on proper JSON formatting.) - * - * "jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to - * specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to - * the URL unless the cache option is set to true. - * - * "text": A plain text string. - * - * multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it - * received in the Content-Type header to what you require. For example, if you want a text response to - * be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it - * received as text, and interpreted by jQuery as XML: "jsonp text xml". Similarly, a shorthand string - * such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from - * jsonp to text, and then from text to xml. - */ - dataType?: 'xml' | 'html' | 'script' | 'json' | 'jsonp' | 'text' | string; - /** - * A function to be called if the request fails. The function receives three arguments: The jqXHR (in - * jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an - * optional exception object, if one occurred. Possible values for the second argument (besides null) - * are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives - * the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery - * 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: - * This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event. - */ - error?: TypeOrArray>; - /** - * Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to - * prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to - * control various Ajax Events. - */ - global?: boolean; - /** - * An object of additional header key/value pairs to send along with requests using the XMLHttpRequest - * transport. The header X-Requested-With: XMLHttpRequest is always added, but its default - * XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from - * within the beforeSend function. - */ - headers?: PlainObject; - /** - * Allow the request to be successful only if the response has changed since the last request. This is - * done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery - * 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data. - */ - ifModified?: boolean; - /** - * Allow the current environment to be recognized as "local," (e.g. the filesystem), even if jQuery - * does not recognize it as such by default. The following protocols are currently recognized as local: - * file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so - * once in the $.ajaxSetup() method. - */ - isLocal?: boolean; - /** - * Override the callback function name in a JSONP request. This value will be used instead of - * 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would - * result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false - * prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for - * transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, - * { jsonp: false, jsonpCallback: "callbackName" }. If you don't trust the target of your Ajax - * requests, consider setting the jsonp property to false for security reasons. - */ - jsonp?: string | boolean; - /** - * Specify the callback function name for a JSONP request. This value will be used instead of the - * random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name - * as it'll make it easier to manage the requests and provide callbacks and error handling. You may - * want to specify the callback when you want to enable better browser caching of GET requests. As of - * jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback - * is set to the return value of that function. - */ - jsonpCallback?: string | ((this: TContext) => string); - /** - * The HTTP method to use for the request (e.g. "POST", "GET", "PUT"). - */ - method?: string; - /** - * A mime type to override the XHR mime type. - */ - mimeType?: string; - /** - * A password to be used with XMLHttpRequest in response to an HTTP access authentication request. - */ - password?: string; - /** - * By default, data passed in to the data option as an object (technically, anything other than a - * string) will be processed and transformed into a query string, fitting to the default content-type - * "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, - * set this option to false. - */ - processData?: boolean; - /** - * Only applies when the "script" transport is used (e.g., cross-domain requests with "jsonp" or - * "script" dataType and "GET" type). Sets the charset attribute on the script tag used in the request. - * Used when the character set on the local page is not the same as the one on the remote script. - */ - scriptCharset?: string; - /** - * An object of numeric HTTP codes and functions to be called when the response has the corresponding - * code. - * - * If the request is successful, the status code functions take the same parameters as the success - * callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback. - */ - statusCode?: PlainObject | Ajax.ErrorCallback>; - /** - * A function to be called if the request succeeds. The function gets passed three arguments: The data - * returned from the server, formatted according to the dataType parameter or the dataFilter callback - * function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, - * XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each - * function will be called in turn. This is an Ajax Event. - */ - success?: TypeOrArray>; - /** - * Set a timeout (in milliseconds) for the request. A value of 0 means there will be no timeout. This - * will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the - * $.ajax call is made; if several other requests are in progress and the browser has no connections - * available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and - * below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any - * object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be - * cancelled by a timeout; the script will run even if it arrives after the timeout period. - */ - timeout?: number; - /** - * Set this to true if you wish to use the traditional style of param serialization. - */ - traditional?: boolean; - /** - * An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0. - */ - type?: string; + interface AjaxSettings extends Ajax.AjaxSettingsBase { /** * A string containing the URL to which the request is sent. */ url?: string; + } + + interface UrlAjaxSettings extends Ajax.AjaxSettingsBase { /** - * A username to be used with XMLHttpRequest in response to an HTTP access authentication request. + * A string containing the URL to which the request is sent. */ - username?: string; - /** - * Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), - * the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or - * enhancements to the factory. - */ - xhr?(): XMLHttpRequest; - /** - * An object of fieldName-fieldValue pairs to set on the native XHR object. - * - * In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS - * requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ - * should you require the use of it. - */ - xhrFields?: PlainObject; + url: string; } namespace Ajax { @@ -3559,12 +3333,421 @@ declare namespace JQuery { } interface ErrorCallback { - (this: TContext, jqXHR: jqXHR, textStatus: ErrorTextStatus | null, errorThrown: string): void; + (this: TContext, jqXHR: jqXHR, textStatus: ErrorTextStatus, errorThrown: string): void; } interface CompleteCallback { (this: TContext, jqXHR: jqXHR, textStatus: TextStatus): void; } + + /** + * @see {@link http://api.jquery.com/jquery.ajax/#jQuery-ajax-settings} + */ + interface AjaxSettingsBase { + /** + * A set of key/value pairs that map a given dataType to its MIME type, which gets sent in the Accept + * request header. This header tells the server what kind of response it will accept in return. + */ + accepts?: PlainObject; + /** + * By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need + * synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests + * do not support synchronous operation. Note that synchronous requests may temporarily lock the + * browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: + * false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback + * options instead of the corresponding methods of the jqXHR object such as jqXHR.done(). + */ + async?: boolean; + /** + * A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, + * XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and + * settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend + * function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless + * of the type of request. + */ + beforeSend?(this: TContext, jqXHR: jqXHR, settings: AjaxSettingsBase): false | void; + /** + * If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache + * to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" + * to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a + * POST is made to a URL that has already been requested by a GET. + */ + cache?: boolean; + /** + * A function to be called when the request finishes (after success and error callbacks are executed). + * The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a + * string categorizing the status of the request ("success", "notmodified", "nocontent", "error", + * "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of + * functions. Each function will be called in turn. This is an Ajax Event. + */ + complete?: TypeOrArray>; + /** + * An object of string/regular-expression pairs that determine how jQuery will parse the response, + * given its content type. + */ + contents?: PlainObject; + /** + * When sending data to the server, use this content type. Default is + * "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly + * pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). + * As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. Note: The W3C + * XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset + * will not force the browser to change the encoding. Note: For cross-domain requests, setting the + * content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or + * text/plain will trigger the browser to send a preflight OPTIONS request to the server. + */ + contentType?: string | false; + /** + * This object will be the context of all Ajax-related callbacks. By default, the context is an object + * that represents the Ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). + */ + context?: TContext; + /** + * An object containing dataType-to-dataType converters. Each converter's value is a function that + * returns the transformed value of the response. + */ + converters?: PlainObject<((value: any) => any) | true>; + /** + * If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of + * crossDomain to true. This allows, for example, server-side redirection to another domain. + */ + crossDomain?: boolean; + /** + * Data to be sent to the server. It is converted to a query string, if not already a string. It's + * appended to the url for GET-requests. See processData option to prevent this automatic processing. + * Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same + * key based on the value of the traditional setting (described below). + */ + data?: PlainObject | string; + /** + * A function to be used to handle the raw response data of XMLHttpRequest. This is a pre-filtering + * function to sanitize the response. You should return the sanitized data. The function accepts two + * arguments: The raw data returned from the server and the 'dataType' parameter. + */ + dataFilter?(data: string, type: string): any; + /** + * The type of data that you're expecting back from the server. If none is specified, jQuery will try + * to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON + * will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be + * returned as a string). The available types (and the result passed as the first argument to your + * success callback) are: + * + * "xml": Returns a XML document that can be processed via jQuery. + * + * "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM. + * + * "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by + * appending a query string parameter, _=[TIMESTAMP], to the URL unless the cache option is set to + * true. Note: This will turn POSTs into GETs for remote-domain requests. + * + * "json": Evaluates the response as JSON and returns a JavaScript object. Cross-domain "json" requests + * are converted to "jsonp" unless the request includes jsonp: false in its request options. The JSON + * data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of + * jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} + * instead. (See json.org for more information on proper JSON formatting.) + * + * "jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to + * specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to + * the URL unless the cache option is set to true. + * + * "text": A plain text string. + * + * multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it + * received in the Content-Type header to what you require. For example, if you want a text response to + * be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it + * received as text, and interpreted by jQuery as XML: "jsonp text xml". Similarly, a shorthand string + * such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from + * jsonp to text, and then from text to xml. + */ + dataType?: 'xml' | 'html' | 'script' | 'json' | 'jsonp' | 'text' | string; + /** + * A function to be called if the request fails. The function receives three arguments: The jqXHR (in + * jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an + * optional exception object, if one occurred. Possible values for the second argument (besides null) + * are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives + * the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery + * 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: + * This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event. + */ + error?: TypeOrArray>; + /** + * Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to + * prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to + * control various Ajax Events. + */ + global?: boolean; + /** + * An object of additional header key/value pairs to send along with requests using the XMLHttpRequest + * transport. The header X-Requested-With: XMLHttpRequest is always added, but its default + * XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from + * within the beforeSend function. + */ + headers?: PlainObject; + /** + * Allow the request to be successful only if the response has changed since the last request. This is + * done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery + * 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data. + */ + ifModified?: boolean; + /** + * Allow the current environment to be recognized as "local," (e.g. the filesystem), even if jQuery + * does not recognize it as such by default. The following protocols are currently recognized as local: + * file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so + * once in the $.ajaxSetup() method. + */ + isLocal?: boolean; + /** + * Override the callback function name in a JSONP request. This value will be used instead of + * 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would + * result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false + * prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for + * transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, + * { jsonp: false, jsonpCallback: "callbackName" }. If you don't trust the target of your Ajax + * requests, consider setting the jsonp property to false for security reasons. + */ + jsonp?: string | false; + /** + * Specify the callback function name for a JSONP request. This value will be used instead of the + * random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name + * as it'll make it easier to manage the requests and provide callbacks and error handling. You may + * want to specify the callback when you want to enable better browser caching of GET requests. As of + * jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback + * is set to the return value of that function. + */ + jsonpCallback?: string | ((this: TContext) => string); + /** + * The HTTP method to use for the request (e.g. "POST", "GET", "PUT"). + */ + method?: string; + /** + * A mime type to override the XHR mime type. + */ + mimeType?: string; + /** + * A password to be used with XMLHttpRequest in response to an HTTP access authentication request. + */ + password?: string; + /** + * By default, data passed in to the data option as an object (technically, anything other than a + * string) will be processed and transformed into a query string, fitting to the default content-type + * "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, + * set this option to false. + */ + processData?: boolean; + /** + * Only applies when the "script" transport is used (e.g., cross-domain requests with "jsonp" or + * "script" dataType and "GET" type). Sets the charset attribute on the script tag used in the request. + * Used when the character set on the local page is not the same as the one on the remote script. + */ + scriptCharset?: string; + /** + * An object of numeric HTTP codes and functions to be called when the response has the corresponding + * code. + * + * If the request is successful, the status code functions take the same parameters as the success + * callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback. + */ + statusCode?: StatusCodeCallbacks; + /** + * A function to be called if the request succeeds. The function gets passed three arguments: The data + * returned from the server, formatted according to the dataType parameter or the dataFilter callback + * function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, + * XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each + * function will be called in turn. This is an Ajax Event. + */ + success?: TypeOrArray>; + /** + * Set a timeout (in milliseconds) for the request. A value of 0 means there will be no timeout. This + * will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the + * $.ajax call is made; if several other requests are in progress and the browser has no connections + * available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and + * below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any + * object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be + * cancelled by a timeout; the script will run even if it arrives after the timeout period. + */ + timeout?: number; + /** + * Set this to true if you wish to use the traditional style of param serialization. + */ + traditional?: boolean; + /** + * An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0. + */ + type?: string; + /** + * A username to be used with XMLHttpRequest in response to an HTTP access authentication request. + */ + username?: string; + /** + * Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), + * the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or + * enhancements to the factory. + */ + xhr?(): XMLHttpRequest; + /** + * An object of fieldName-fieldValue pairs to set on the native XHR object. + * + * In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS + * requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ + * should you require the use of it. + */ + xhrFields?: PlainObject; + } + + // Status codes not listed require type annotations when defining the callback + type StatusCodeCallbacks = { + // jQuery treats 2xx and 304 status codes as a success + 200?: SuccessCallback; + 201?: SuccessCallback; + 202?: SuccessCallback; + 203?: SuccessCallback; + 204?: SuccessCallback; + 205?: SuccessCallback; + 206?: SuccessCallback; + 207?: SuccessCallback; + 208?: SuccessCallback; + 209?: SuccessCallback; + 210?: SuccessCallback; + 211?: SuccessCallback; + 212?: SuccessCallback; + 213?: SuccessCallback; + 214?: SuccessCallback; + 215?: SuccessCallback; + 216?: SuccessCallback; + 217?: SuccessCallback; + 218?: SuccessCallback; + 219?: SuccessCallback; + 220?: SuccessCallback; + 221?: SuccessCallback; + 222?: SuccessCallback; + 223?: SuccessCallback; + 224?: SuccessCallback; + 225?: SuccessCallback; + 226?: SuccessCallback; + 227?: SuccessCallback; + 228?: SuccessCallback; + 229?: SuccessCallback; + 230?: SuccessCallback; + 231?: SuccessCallback; + 232?: SuccessCallback; + 233?: SuccessCallback; + 234?: SuccessCallback; + 235?: SuccessCallback; + 236?: SuccessCallback; + 237?: SuccessCallback; + 238?: SuccessCallback; + 239?: SuccessCallback; + 240?: SuccessCallback; + 241?: SuccessCallback; + 242?: SuccessCallback; + 243?: SuccessCallback; + 244?: SuccessCallback; + 245?: SuccessCallback; + 246?: SuccessCallback; + 247?: SuccessCallback; + 248?: SuccessCallback; + 249?: SuccessCallback; + 250?: SuccessCallback; + 251?: SuccessCallback; + 252?: SuccessCallback; + 253?: SuccessCallback; + 254?: SuccessCallback; + 255?: SuccessCallback; + 256?: SuccessCallback; + 257?: SuccessCallback; + 258?: SuccessCallback; + 259?: SuccessCallback; + 260?: SuccessCallback; + 261?: SuccessCallback; + 262?: SuccessCallback; + 263?: SuccessCallback; + 264?: SuccessCallback; + 265?: SuccessCallback; + 266?: SuccessCallback; + 267?: SuccessCallback; + 268?: SuccessCallback; + 269?: SuccessCallback; + 270?: SuccessCallback; + 271?: SuccessCallback; + 272?: SuccessCallback; + 273?: SuccessCallback; + 274?: SuccessCallback; + 275?: SuccessCallback; + 276?: SuccessCallback; + 277?: SuccessCallback; + 278?: SuccessCallback; + 279?: SuccessCallback; + 280?: SuccessCallback; + 281?: SuccessCallback; + 282?: SuccessCallback; + 283?: SuccessCallback; + 284?: SuccessCallback; + 285?: SuccessCallback; + 286?: SuccessCallback; + 287?: SuccessCallback; + 288?: SuccessCallback; + 289?: SuccessCallback; + 290?: SuccessCallback; + 291?: SuccessCallback; + 292?: SuccessCallback; + 293?: SuccessCallback; + 294?: SuccessCallback; + 295?: SuccessCallback; + 296?: SuccessCallback; + 297?: SuccessCallback; + 298?: SuccessCallback; + 299?: SuccessCallback; + 304?: SuccessCallback; + + // Standard 3xx, 4xx, and 5xx status codes that are considered an error + 300?: ErrorCallback; + 301?: ErrorCallback; + 302?: ErrorCallback; + 303?: ErrorCallback; + 305?: ErrorCallback; + 306?: ErrorCallback; + 307?: ErrorCallback; + 308?: ErrorCallback; + 400?: ErrorCallback; + 401?: ErrorCallback; + 402?: ErrorCallback; + 403?: ErrorCallback; + 404?: ErrorCallback; + 405?: ErrorCallback; + 406?: ErrorCallback; + 407?: ErrorCallback; + 408?: ErrorCallback; + 409?: ErrorCallback; + 410?: ErrorCallback; + 411?: ErrorCallback; + 412?: ErrorCallback; + 413?: ErrorCallback; + 414?: ErrorCallback; + 415?: ErrorCallback; + 416?: ErrorCallback; + 417?: ErrorCallback; + 418?: ErrorCallback; + 421?: ErrorCallback; + 422?: ErrorCallback; + 423?: ErrorCallback; + 424?: ErrorCallback; + 426?: ErrorCallback; + 428?: ErrorCallback; + 429?: ErrorCallback; + 431?: ErrorCallback; + 451?: ErrorCallback; + 500?: ErrorCallback; + 501?: ErrorCallback; + 502?: ErrorCallback; + 503?: ErrorCallback; + 504?: ErrorCallback; + 505?: ErrorCallback; + 506?: ErrorCallback; + 507?: ErrorCallback; + 508?: ErrorCallback; + 510?: ErrorCallback; + 511?: ErrorCallback; + } & { [index: number]: SuccessCallback | ErrorCallback; }; } interface Transport { @@ -3584,7 +3767,7 @@ declare namespace JQuery { interface jqXHR extends Pick { responseJSON: any; - statusCode(map: PlainObject | Ajax.ErrorCallback>): void; + statusCode(map: Ajax.StatusCodeCallbacks): void; /** * Add handlers to be called when the Deferred object is either resolved or rejected. @@ -3696,7 +3879,7 @@ declare namespace JQuery { } interface FailCallback { - (jqXHR: TResolve, textStatus: Ajax.ErrorTextStatus | null, errorThrown: string): void; + (jqXHR: TResolve, textStatus: Ajax.ErrorTextStatus, errorThrown: string): void; } interface AlwaysCallback { @@ -4043,6 +4226,7 @@ declare namespace JQuery { // region Effects type Duration = number | 'fast' | 'slow'; + // TODO: Is the first element always a string or is that specific to the 'fx' queue? type Queue = { 0: string; } & Array>; interface QueueFunction { @@ -4094,7 +4278,7 @@ declare namespace JQuery { * An object containing one or more of the CSS properties defined by the properties argument and their * corresponding easing functions. */ - specialEasing?: PlainObject; + specialEasing?: PlainObject; /** * A function to call when the animation on an element begins. */ @@ -4144,7 +4328,8 @@ declare namespace JQuery { // region Events - class Event { + // This should be a class but doesn't work correctly under the JQuery namespace. Event should be an inner class of jQuery. + interface Event { /** * The current DOM element within the event bubbling phase. * diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index 09468a1c55..7a05a5630a 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -1,4 +1,9 @@ function JQuery() { + function type_assertion() { + const $el = $(document.createElement('canvas')); + const $canvas = $el as JQuery; + } + function iterable() { for (const a of $('div')) { a.textContent = 'myDiv'; @@ -9,36 +14,3529 @@ function JQuery() { $('div')[0] === new HTMLElement(); } - function on() { - function false_handler_shorthand() { - $().on('events', false); + function ajax() { + function ajaxComplete() { + // $ExpectType JQuery + $(document).ajaxComplete(function(event, jqXHR, ajaxOptions) { + // $ExpectType Document + this; + // $ExpectType Event + event; + // $ExpectType jqXHR + jqXHR; + // $ExpectType AjaxSettings + ajaxOptions; + + return false; + }); } - function typed_event_data() { - $('#myElement').on('custom', 45, (event, data) => { - event.data === 23; + function ajaxError() { + // $ExpectType JQuery + $(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) { + // $ExpectType Document + this; + // $ExpectType Event + event; + // $ExpectType jqXHR + jqXHR; + // $ExpectType AjaxSettings + ajaxSettings; + // $ExpectType string + thrownError; + + return false; }); } + + function ajaxSend() { + // $ExpectType JQuery + $(document).ajaxSend(function(event, jqXHR, ajaxOptions) { + // $ExpectType Document + this; + // $ExpectType Event + event; + // $ExpectType jqXHR + jqXHR; + // $ExpectType AjaxSettings + ajaxOptions; + + return false; + }); + } + + function ajaxStart() { + // $ExpectType JQuery + $(document).ajaxStart(function() { + // $ExpectType Document + this; + + return false; + }); + } + + function ajaxStop() { + // $ExpectType JQuery + $(document).ajaxStop(function() { + // $ExpectType Document + this; + + return false; + }); + } + + function ajaxSuccess() { + // $ExpectType JQuery + $(document).ajaxSuccess(function(event, jqXHR, ajaxOptions, data) { + // $ExpectType Document + this; + // $ExpectType Event + event; + // $ExpectType jqXHR + jqXHR; + // $ExpectType AjaxSettings + ajaxOptions; + // $ExpectType PlainObject + data; + + return false; + }); + } + + function load() { + // $ExpectType JQuery + $('#result').load('/echo/html/', 'data', function(responseText, textStatus, jqXHR) { + // $ExpectType HTMLElement + this; + // $ExpectType string + responseText; + // $ExpectType TextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }); + + // $ExpectType JQuery + $('#result').load('/echo/html/', { data: 'data' }, function(responseText, textStatus, jqXHR) { + // $ExpectType HTMLElement + this; + // $ExpectType string + responseText; + // $ExpectType TextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }); + + // $ExpectType JQuery + $('#result').load('/echo/html/', function(responseText, textStatus, jqXHR) { + // $ExpectType HTMLElement + this; + // $ExpectType string + responseText; + // $ExpectType TextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }); + + // $ExpectType JQuery + $('#result').load('/echo/html/', 'data'); + + // $ExpectType JQuery + $('#result').load('/echo/html/', { data: 'data' }); + } + } + + function attributes() { + function attr() { + // $ExpectType JQuery + $('#greatphoto').attr('alt', 'Beijing Brush Seller'); + + // $ExpectType JQuery + $('#greatphoto').attr('width', 200); + + // $ExpectType JQuery + $('#greatphoto').attr('title', null); + + // $ExpectType JQuery + $('#greatphoto').attr('alt', function(index, attr) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + attr; + + return 'Beijing Brush Seller'; + }); + + // $ExpectType JQuery + $('#greatphoto').attr('width', function(index, attr) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + attr; + + return 200; + }); + + // $ExpectType JQuery + $('#greatphoto').attr('title', function(index, attr) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + attr; + }); + + // $ExpectType JQuery + $('#greatphoto').attr('title', function(index, attr) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + attr; + + return undefined; + }); + + // $ExpectType JQuery + $('img').attr({ + src: '/resources/hat.gif', + title: 'jQuery', + alt: 'jQuery Logo' + }); + + // $ExpectType string | undefined + $('img').attr('src'); + } + + function removeAttr() { + // $ExpectType JQuery + $('#greatphoto').removeAttr('alt'); + } + } + + function properties() { + function prop() { + // $ExpectType JQuery + $('p').prop('myProp', function(index, oldPropertyValue) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType any + oldPropertyValue; + + return {}; + }); + + // $ExpectType JQuery + $('p').prop('myProp', {}); + + // $ExpectType JQuery + $('input[type=\'checkbox\']').prop({ + myProp: true + }); + + // $ExpectType any + $('input[type=\'checkbox\']').prop('myProp'); + } + + function removeProp() { + // $ExpectType JQuery + $('p').removeProp('luggageCode'); + } + } + + function css() { + // TODO: .css() getters can return 'undefined' for properties that don't exist. Consider changing the return types to reflect this after adding specialized signatures. + function css() { + // $ExpectType JQuery + $('p').css('cssProp', 'value'); + + // $ExpectType JQuery + $('p').css('cssProp', 20); + + // $ExpectType JQuery + $('p').css('cssProp', function(index, value) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + value; + + return 'value'; + }); + + // $ExpectType JQuery + $('p').css('cssProp', function(index, value) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + value; + + return 20; + }); + + // $ExpectType JQuery + $('p').css('cssProp', function(index, value) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + value; + }); + + // $ExpectType JQuery + $('p').css('cssProp', function(index, value) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + value; + + return undefined; + }); + + // $ExpectType JQuery + $('p').css({ + myProp1: 'value', + myProp2: 20, + myProp3(index, value) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + value; + + return 'value'; + }, + myProp4(index, value) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + value; + + return 20; + }, + myProp5(index, value) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + value; + }, + myProp6(index, value) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + value; + + return undefined; + } + }); + + // $ExpectType string + $('p').css('myProp'); + + // $ExpectType PlainObject + $('p').css([ + 'myProp1', + 'myProp2' + ]); + } + + function height() { + // $ExpectType JQuery + $('p').height('200px'); + + // $ExpectType JQuery + $('p').height(400); + + // $ExpectType JQuery + $('p').height(function(index, height) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType number + height; + + return '200px'; + }); + + // $ExpectType JQuery + $('p').height(function(index, height) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType number + height; + + return 400; + }); + + // $ExpectType number | undefined + $('p').height(); + } + + function innerHeight() { + // $ExpectType JQuery + $('p').innerHeight('200px'); + + // $ExpectType JQuery + $('p').innerHeight(400); + + // $ExpectType JQuery + $('p').innerHeight(function(index, height) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType number + height; + + return '200px'; + }); + + // $ExpectType JQuery + $('p').innerHeight(function(index, height) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType number + height; + + return 400; + }); + + // $ExpectType number | undefined + $('p').innerHeight(); + } + + function outerHeight() { + // $ExpectType JQuery + $('p').outerHeight('200px'); + + // $ExpectType JQuery + $('p').outerHeight(400); + + // $ExpectType JQuery + $('p').outerHeight(function(index, height) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType number + height; + + return '200px'; + }); + + // $ExpectType JQuery + $('p').outerHeight(function(index, height) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType number + height; + + return 400; + }); + + // $ExpectType number | undefined + $('p').outerHeight(); + + // $ExpectType number | undefined + $('p').outerHeight(true); + } + + function width() { + // $ExpectType JQuery + $('p').width('200px'); + + // $ExpectType JQuery + $('p').width(400); + + // $ExpectType JQuery + $('p').width(function(index, width) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType number + width; + + return '200px'; + }); + + // $ExpectType JQuery + $('p').width(function(index, width) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType number + width; + + return 400; + }); + + // $ExpectType number | undefined + $('p').width(); + } + + function innerWidth() { + // $ExpectType JQuery + $('p').innerWidth('200px'); + + // $ExpectType JQuery + $('p').innerWidth(400); + + // $ExpectType JQuery + $('p').innerWidth(function(index, width) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType number + width; + + return '200px'; + }); + + // $ExpectType JQuery + $('p').innerWidth(function(index, width) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType number + width; + + return 400; + }); + + // $ExpectType number | undefined + $('p').innerWidth(); + } + + function outerWidth() { + // $ExpectType JQuery + $('p').outerWidth('200px'); + + // $ExpectType JQuery + $('p').outerWidth(400); + + // $ExpectType JQuery + $('p').outerWidth(function(index, width) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType number + width; + + return '200px'; + }); + + // $ExpectType JQuery + $('p').outerWidth(function(index, width) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType number + width; + + return 400; + }); + + // $ExpectType number | undefined + $('p').outerWidth(); + + // $ExpectType number | undefined + $('p').outerWidth(true); + } + + function offset() { + // $ExpectType JQuery + $('p').offset({ + left: 20, + top: 50 + }); + + // $ExpectType JQuery + $('p').offset(function(index, coords) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType Coordinates + coords; + + return { + left: 20, + top: 50 + }; + }); + + // $ExpectType Coordinates + $('p').offset(); + } + + function position() { + // $ExpectType Coordinates + $('p').position(); + } + + function scrollLeft() { + // $ExpectType JQuery + $('p').scrollLeft(200); + + // $ExpectType number + $('p').scrollLeft(); + } + + function scrollTop() { + // $ExpectType JQuery + $('p').scrollTop(200); + + // $ExpectType number + $('p').scrollTop(); + } + + function addClass() { + // $ExpectType JQuery + $('p').addClass('className'); + + // $ExpectType JQuery + $('p').addClass(function(index, currentClassName) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + currentClassName; + + return 'className'; + }); + } + + function hasClass() { + // $ExpectType boolean + $('p').hasClass('className'); + } + + function removeClass() { + // $ExpectType JQuery + $('p').removeClass('className'); + + // $ExpectType JQuery + $('p').removeClass(function(index, currentClassName) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + currentClassName; + + return 'className'; + }); + + // $ExpectType JQuery + $('p').removeClass(); + } + + function toggleClass() { + // $ExpectType JQuery + $('p').toggleClass('className', true); + + // $ExpectType JQuery + $('p').toggleClass(function(index, className, state) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + className; + // $ExpectType true + state; + + return 'className'; + }, true); + + // $ExpectType JQuery + $('p').toggleClass('className'); + + // $ExpectType JQuery + $('p').toggleClass(function(index, className, state) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + className; + // $ExpectType boolean + state; + + return 'className'; + }); + + // $ExpectType JQuery + $('p').toggleClass(false); + + // $ExpectType JQuery + $('p').toggleClass(); + } + } + + function data() { + function data() { + // $ExpectType any + $('p').data('myData', undefined); + + // $ExpectType JQuery + $('p').data('myData', {}); + + // $ExpectType JQuery + $('p').data({ + myData1: {}, + myData2: false + }); + + // $ExpectType any + $('p').data('myData'); + + // $ExpectType PlainObject + $('p').data(); + } + + function removeData() { + // $ExpectType JQuery + $('p').removeData('myData'); + + // $ExpectType JQuery + $('p').removeData([ + 'myData1', + 'myData2' + ]); + + // $ExpectType JQuery + $('p').removeData(); + } + } + + function effects() { + function animate() { + // $ExpectType JQuery + $('#book').animate({ + width: ['toggle', 'swing'], + height: 200, + opacity: 'toggle' + }, 5000, 'linear', function() { + // $ExpectType HTMLElement + this; + + $(this).after('
Animation complete.
'); + }); + + // $ExpectType JQuery + $('#book').animate({ + width: ['toggle', 'swing'], + height: 200, + opacity: 'toggle' + }, 5000, 'linear'); + + // $ExpectType JQuery + $('#book').animate({ + width: ['toggle', 'swing'], + height: 200, + opacity: 'toggle' + }, 5000, function() { + // $ExpectType HTMLElement + this; + + $(this).after('
Animation complete.
'); + }); + + // $ExpectType JQuery + $('#book').animate({ + width: ['toggle', 'swing'], + height: 200, + opacity: 'toggle' + }, 'linear', function() { + // $ExpectType HTMLElement + this; + + $(this).after('
Animation complete.
'); + }); + + // $ExpectType JQuery + $('#book').animate({ + width: ['toggle', 'swing'], + height: 200, + opacity: 'toggle' + }, 5000); + + // $ExpectType JQuery + $('#book').animate({ + width: ['toggle', 'swing'], + height: 200, + opacity: 'toggle' + }, 'linear'); + + // $ExpectType JQuery + $('#book').animate({ + width: ['toggle', 'swing'], + height: 200, + opacity: 'toggle' + }, function() { + // $ExpectType HTMLElement + this; + + $(this).after('
Animation complete.
'); + }); + + // $ExpectType JQuery + $('#book').animate({ + width: 'toggle', + height: 'toggle' + }, { + duration: 5000, + specialEasing: { + width: 'linear', + height: 'easeOutBounce' + }, + complete() { + $(this).after('
Animation complete.
'); + } + }); + + // $ExpectType JQuery + $('#book').animate({ + width: ['toggle', 'swing'], + height: 200, + opacity: 'toggle' + }); + } + + function fadeIn() { + // $ExpectType JQuery + $('p').fadeIn(5000, 'linear', function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').fadeIn(5000, 'linear'); + + // $ExpectType JQuery + $('p').fadeIn(5000, function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').fadeIn('linear', function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').fadeIn(5000); + + // $ExpectType JQuery + $('p').fadeIn('linear'); + + // $ExpectType JQuery + $('p').fadeIn(function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').fadeIn({ + duration: 5000, + specialEasing: { + width: 'linear', + height: 'easeOutBounce' + }, + complete() { + $(this).after('
Animation complete.
'); + } + }); + + // $ExpectType JQuery + $('p').fadeIn(); + } + + function fadeOut() { + // $ExpectType JQuery + $('p').fadeOut(5000, 'linear', function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').fadeOut(5000, 'linear'); + + // $ExpectType JQuery + $('p').fadeOut(5000, function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').fadeOut('linear', function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').fadeOut(5000); + + // $ExpectType JQuery + $('p').fadeOut('linear'); + + // $ExpectType JQuery + $('p').fadeOut(function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').fadeOut({ + duration: 5000, + specialEasing: { + width: 'linear', + height: 'easeOutBounce' + }, + complete() { + $(this).after('
Animation complete.
'); + } + }); + + // $ExpectType JQuery + $('p').fadeOut(); + } + + function fadeToggle() { + // $ExpectType JQuery + $('p').fadeToggle(5000, 'linear', function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').fadeToggle(5000, 'linear'); + + // $ExpectType JQuery + $('p').fadeToggle(5000, function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').fadeToggle('linear', function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').fadeToggle(5000); + + // $ExpectType JQuery + $('p').fadeToggle('linear'); + + // $ExpectType JQuery + $('p').fadeToggle(function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').fadeToggle({ + duration: 5000, + specialEasing: { + width: 'linear', + height: 'easeOutBounce' + }, + complete() { + $(this).after('
Animation complete.
'); + } + }); + + // $ExpectType JQuery + $('p').fadeToggle(); + } + + function slideDown() { + // $ExpectType JQuery + $('p').slideDown(5000, 'linear', function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').slideDown(5000, 'linear'); + + // $ExpectType JQuery + $('p').slideDown(5000, function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').slideDown('linear', function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').slideDown(5000); + + // $ExpectType JQuery + $('p').slideDown('linear'); + + // $ExpectType JQuery + $('p').slideDown(function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').slideDown({ + duration: 5000, + specialEasing: { + width: 'linear', + height: 'easeOutBounce' + }, + complete() { + $(this).after('
Animation complete.
'); + } + }); + + // $ExpectType JQuery + $('p').slideDown(); + } + + function slideToggle() { + // $ExpectType JQuery + $('p').slideToggle(5000, 'linear', function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').slideToggle(5000, 'linear'); + + // $ExpectType JQuery + $('p').slideToggle(5000, function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').slideToggle('linear', function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').slideToggle(5000); + + // $ExpectType JQuery + $('p').slideToggle('linear'); + + // $ExpectType JQuery + $('p').slideToggle(function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').slideToggle({ + duration: 5000, + specialEasing: { + width: 'linear', + height: 'easeOutBounce' + }, + complete() { + $(this).after('
Animation complete.
'); + } + }); + + // $ExpectType JQuery + $('p').slideToggle(); + } + + function slideUp() { + // $ExpectType JQuery + $('p').slideUp(5000, 'linear', function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').slideUp(5000, 'linear'); + + // $ExpectType JQuery + $('p').slideUp(5000, function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').slideUp('linear', function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').slideUp(5000); + + // $ExpectType JQuery + $('p').slideUp('linear'); + + // $ExpectType JQuery + $('p').slideUp(function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').slideUp({ + duration: 5000, + specialEasing: { + width: 'linear', + height: 'easeOutBounce' + }, + complete() { + $(this).after('
Animation complete.
'); + } + }); + + // $ExpectType JQuery + $('p').slideUp(); + } + + function fadeTo() { + // $ExpectType JQuery + $('p').fadeTo(5000, 0.9, 'linear', function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').fadeTo(5000, 0.9, 'linear'); + + // $ExpectType JQuery + $('p').fadeTo(5000, 0.9, function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').fadeTo(5000, 0.9); + } + + function toggle() { + // $ExpectType JQuery + $('p').toggle(5000, 'linear', function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').toggle(5000, 'linear'); + + // $ExpectType JQuery + $('p').toggle(5000, function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').toggle(5000); + + // $ExpectType JQuery + $('p').toggle(function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').toggle('linear'); + + // $ExpectType JQuery + $('p').toggle(true); + + // $ExpectType JQuery + $('p').toggle(); + } + + function hide() { + // $ExpectType JQuery + $('p').hide(5000, 'linear', function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').hide(5000, 'linear'); + + // $ExpectType JQuery + $('p').hide(5000, function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').hide(5000); + + // $ExpectType JQuery + $('p').hide(function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').hide({ + duration: 5000, + specialEasing: { + width: 'linear', + height: 'easeOutBounce' + }, + complete() { + $(this).after('
Animation complete.
'); + } + }); + + // $ExpectType JQuery + $('p').hide(); + } + + function show() { + // $ExpectType JQuery + $('p').show(5000, 'linear', function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').show(5000, 'linear'); + + // $ExpectType JQuery + $('p').show(5000, function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').show(5000); + + // $ExpectType JQuery + $('p').show(function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType JQuery + $('p').show({ + duration: 5000, + specialEasing: { + width: 'linear', + height: 'easeOutBounce' + }, + complete() { + $(this).after('
Animation complete.
'); + } + }); + + // $ExpectType JQuery + $('p').show(); + } + } + + function queue() { + function clearQueue() { + // $ExpectType JQuery + $('p').clearQueue('myQueue'); + + // $ExpectType JQuery + $('p').clearQueue(); + } + + function delay() { + // $ExpectType JQuery + $('p').delay('fast', 'myQueue'); + + // $ExpectType JQuery + $('p').delay('slow'); + } + + function dequeue() { + // $ExpectType JQuery + $('p').dequeue('myQueue'); + + // $ExpectType JQuery + $('p').dequeue(); + } + + function finish() { + // $ExpectType JQuery + $('p').finish('myQueue'); + + // $ExpectType JQuery + $('p').finish(); + } + + function queue() { + // $ExpectType JQuery + $('p').queue('myQueue', function(next) { + // $ExpectType HTMLElement + this; + // $ExpectType () => void + next; + }); + + // $ExpectType JQuery + $('p').queue('myQueue', [ + function(next) { + // $ExpectType HTMLElement + this; + // $ExpectType () => void + next; + }, + function(next) { + // $ExpectType HTMLElement + this; + // $ExpectType () => void + next; + } + ]); + + // $ExpectType JQuery + $('p').queue(function(next) { + // $ExpectType HTMLElement + this; + // $ExpectType () => void + next; + }); + + // $ExpectType JQuery + $('p').queue([ + function(next) { + // $ExpectType HTMLElement + this; + // $ExpectType () => void + next; + }, + function(next) { + // $ExpectType HTMLElement + this; + // $ExpectType () => void + next; + } + ]); + + // $ExpectType Queue + $('p').queue('myQueue'); + + // $ExpectType Queue + $('p').queue(); + } + + function stop() { + // $ExpectType JQuery + $('p').stop('myQueue', true, false); + + // $ExpectType JQuery + $('p').stop('myQueue', true); + + // $ExpectType JQuery + $('p').stop(true, false); + + // $ExpectType JQuery + $('p').stop(true); + } + + function promise() { + // $ExpectType { description: string; } & Promise, any, any> + $('p').promise('myQueue', { description: 'desc' }); + + // $ExpectType { description: string; } & Promise, any, any> + $('p').promise({ description: 'desc' }); + + // $ExpectType Promise, any, any> + $('p').promise(); + } + } + + function events() { + // [bind() overloads] https://github.com/jquery/api.jquery.com/issues/1048 + function bind() { + // $ExpectType JQuery + $('p').bind('myEvent', 'myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').bind('myEvent', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').bind('myEvent', false); + + // $ExpectType JQuery + $('p').bind({ + myEvent1(event) { + // $ExpectType HTMLElement + this; + }, + myEvent2: false + }); + + // $ExpectType JQuery + $('p').bind('myEvent', null); + + // $ExpectType JQuery + $('p').bind('myEvent', undefined); + } + + function delegate() { + // $ExpectType JQuery + $('table').delegate('td', 'myEvent', 'myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('table').delegate('td', 'myEvent', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('table').delegate('td', 'myEvent', false); + + // $ExpectType JQuery + $('table').delegate('td', { + myEvent1(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }, + myEvent2: false + }); + } + + function off() { + // $ExpectType JQuery + $('table').off('myEvent', 'td', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('table').off('myEvent', 'td', false); + + // $ExpectType JQuery + $('table').off('myEvent', 'td'); + + // $ExpectType JQuery + $('table').off('myEvent', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('table').off('myEvent', false); + + // $ExpectType JQuery + $('table').off('myEvent'); + + // $ExpectType JQuery + $('table').off({ + myEvent1(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }, + myEvent2: false + }, 'td'); + + // $ExpectType JQuery + $('table').off({ + myEvent1(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }, + myEvent2: false + }); + + // $ExpectType JQuery + $('table').off($.Event('myEvent')); + + // $ExpectType JQuery + $('table').off(); + } + + function on() { + // $ExpectType JQuery + $('table').on('myEvent', 'td', 'myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('table').on('myEvent', null, 'myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('table').on('myEvent', 'td', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('table').on('myEvent', 'td', false); + + // $ExpectType JQuery + $('table').on('myEvent', 3, function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('table').on('myEvent', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('table').on('myEvent', false); + + // $ExpectType JQuery + $('table').on({ + myEvent1(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }, + myEvent2: false + }, 'td', 'myData'); + + // $ExpectType JQuery + $('table').on({ + myEvent1(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }, + myEvent2: false + }, null, 'myData'); + + // $ExpectType JQuery + $('table').on({ + myEvent1(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }, + myEvent2: false + }, 'td'); + + // $ExpectType JQuery + $('table').on({ + myEvent1(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }, + myEvent2: false + }, 3); + + // $ExpectType JQuery + $('table').on({ + myEvent1(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }, + myEvent2: false + }); + } + + function one() { + // $ExpectType JQuery + $('table').one('myEvent', 'td', 'myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('table').one('myEvent', null, 'myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('table').one('myEvent', 'td', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('table').one('myEvent', 'td', false); + + // $ExpectType JQuery + $('table').one('myEvent', 3, function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('table').one('myEvent', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('table').one('myEvent', false); + + // $ExpectType JQuery + $('table').one({ + myEvent1(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }, + myEvent2: false + }, 'td', 'myData'); + + // $ExpectType JQuery + $('table').one({ + myEvent1(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }, + myEvent2: false + }, null, 'myData'); + + // $ExpectType JQuery + $('table').one({ + myEvent1(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }, + myEvent2: false + }, 'td'); + + // $ExpectType JQuery + $('table').one({ + myEvent1(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }, + myEvent2: false + }, 3); + + // $ExpectType JQuery + $('table').one({ + myEvent1(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }, + myEvent2: false + }); + } + + function trigger() { + // $ExpectType JQuery + $('p').trigger('myEvent', ['Custom', 'Event']); + + // $ExpectType JQuery + $('p').trigger('myEvent', { myData: 'myData' }); + + // $ExpectType JQuery + $('p').trigger('myEvent', 'Custom'); + + // $ExpectType JQuery + $('p').trigger('myEvent', 3); + + // $ExpectType JQuery + $('p').trigger($.Event('myEvent'), ['Custom', 'Event']); + + // $ExpectType JQuery + $('p').trigger($.Event('myEvent'), { myData: 'myData' }); + + // $ExpectType JQuery + $('p').trigger($.Event('myEvent'), 'Custom'); + + // $ExpectType JQuery + $('p').trigger($.Event('myEvent'), 3); + } + + function triggerHandler() { + // $ExpectType any + $('p').triggerHandler('myEvent', ['Custom', 'Event']); + + // $ExpectType any + $('p').triggerHandler('myEvent', { myData: 'myData' }); + + // $ExpectType any + $('p').triggerHandler('myEvent', 'Custom'); + + // $ExpectType any + $('p').triggerHandler('myEvent', 3); + + // $ExpectType any + $('p').triggerHandler($.Event('myEvent'), ['Custom', 'Event']); + + // $ExpectType any + $('p').triggerHandler($.Event('myEvent'), { myData: 'myData' }); + + // $ExpectType any + $('p').triggerHandler($.Event('myEvent'), 'Custom'); + + // $ExpectType any + $('p').triggerHandler($.Event('myEvent'), 3); + } + + function unbind() { + // $ExpectType JQuery + $('p').unbind('myEvent', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').unbind('myEvent', false); + + // $ExpectType JQuery + $('p').unbind('myEvent'); + + // $ExpectType JQuery + $('p').unbind($.Event('myEvent')); + + // $ExpectType JQuery + $('p').unbind(); + } + + function undelegate() { + // $ExpectType JQuery + $('table').undelegate('td', 'click', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('table').undelegate('td', 'click', false); + + // $ExpectType JQuery + $('table').undelegate('td', 'click'); + + // $ExpectType JQuery + $('table').undelegate('td', { + myEvent1(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }, + myEvent2: false + }); + + // $ExpectType JQuery + $('table').undelegate('.tt'); + + // $ExpectType JQuery + $('table').undelegate(); + } + + function blur() { + // $ExpectType JQuery + $('p').blur('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').blur(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').blur(false); + + // $ExpectType JQuery + $('p').blur(); + } + + function change() { + // $ExpectType JQuery + $('p').change('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').change(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').change(false); + + // $ExpectType JQuery + $('p').change(); + } + + function click() { + // $ExpectType JQuery + $('p').click('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').click(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').click(false); + + // $ExpectType JQuery + $('p').click(); + } + + function contextmenu() { + // $ExpectType JQuery + $('p').contextmenu('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').contextmenu(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').contextmenu(false); + + // $ExpectType JQuery + $('p').contextmenu(); + } + + function dblclick() { + // $ExpectType JQuery + $('p').dblclick('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').dblclick(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').dblclick(false); + + // $ExpectType JQuery + $('p').dblclick(); + } + + function focus() { + // $ExpectType JQuery + $('p').focus('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').focus(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').focus(false); + + // $ExpectType JQuery + $('p').focus(); + } + + function focusin() { + // $ExpectType JQuery + $('p').focusin('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').focusin(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').focusin(false); + + // $ExpectType JQuery + $('p').focusin(); + } + + function focusout() { + // $ExpectType JQuery + $('p').focusout('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').focusout(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').focusout(false); + + // $ExpectType JQuery + $('p').focusout(); + } + + function keydown() { + // $ExpectType JQuery + $('p').keydown('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').keydown(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').keydown(false); + + // $ExpectType JQuery + $('p').keydown(); + } + + function keypress() { + // $ExpectType JQuery + $('p').keypress('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').keypress(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').keypress(false); + + // $ExpectType JQuery + $('p').keypress(); + } + + function keyup() { + // $ExpectType JQuery + $('p').keyup('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').keyup(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').keyup(false); + + // $ExpectType JQuery + $('p').keyup(); + } + + function mousedown() { + // $ExpectType JQuery + $('p').mousedown('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').mousedown(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').mousedown(false); + + // $ExpectType JQuery + $('p').mousedown(); + } + + function mouseenter() { + // $ExpectType JQuery + $('p').mouseenter('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').mouseenter(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').mouseenter(false); + + // $ExpectType JQuery + $('p').mouseenter(); + } + + function mouseleave() { + // $ExpectType JQuery + $('p').mouseleave('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').mouseleave(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').mouseleave(false); + + // $ExpectType JQuery + $('p').mouseleave(); + } + + function mousemove() { + // $ExpectType JQuery + $('p').mousemove('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').mousemove(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').mousemove(false); + + // $ExpectType JQuery + $('p').mousemove(); + } + + function mouseout() { + // $ExpectType JQuery + $('p').mouseout('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').mouseout(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').mouseout(false); + + // $ExpectType JQuery + $('p').mouseout(); + } + + function mouseover() { + // $ExpectType JQuery + $('p').mouseover('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').mouseover(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').mouseover(false); + + // $ExpectType JQuery + $('p').mouseover(); + } + + function mouseup() { + // $ExpectType JQuery + $('p').mouseup('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').mouseup(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').mouseup(false); + + // $ExpectType JQuery + $('p').mouseup(); + } + + function resize() { + // $ExpectType JQuery + $('p').resize('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').resize(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').resize(false); + + // $ExpectType JQuery + $('p').resize(); + } + + function scroll() { + // $ExpectType JQuery + $('p').scroll('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').scroll(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').scroll(false); + + // $ExpectType JQuery + $('p').scroll(); + } + + function select() { + // $ExpectType JQuery + $('p').select('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').select(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').select(false); + + // $ExpectType JQuery + $('p').select(); + } + + function submit() { + // $ExpectType JQuery + $('p').submit('myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').submit(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').submit(false); + + // $ExpectType JQuery + $('p').submit(); + } + + function hover() { + // $ExpectType JQuery + $('p').hover(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }, function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').hover(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }, false); + + // $ExpectType JQuery + $('p').hover(false, function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').hover(false, false); + + // $ExpectType JQuery + $('p').hover(function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType Event + event; + }); + + // $ExpectType JQuery + $('p').hover(false); + } + + function ready() { + // $ExpectType JQuery + $('p').ready(($) => { + // $ExpectType JQueryStatic + $; + }); + } + } + + function manipulation() { + function after() { + // $ExpectType JQuery + $('p').after('

', new Element(), new Text(), $('p'), [new Element(), new Text()]); + + // $ExpectType JQuery + $('p').after(function(index, html) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + html; + + return '

'; + }); + + // $ExpectType JQuery + $('p').after(function(index, html) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + html; + + return new Element(); + }); + + // $ExpectType JQuery + $('p').after(function(index, html) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + html; + + return new Text(); + }); + + // $ExpectType JQuery + $('p').after(function(index, html) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + html; + + return [new Element(), new Text()]; + }); + + // $ExpectType JQuery + $('p').after(function(index, html) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + html; + + return $('p'); + }); + } + + function append() { + // $ExpectType JQuery + $('p').append('

', new Element(), new Text(), $('p'), [new Element(), new Text()]); + + // $ExpectType JQuery + $('p').append(function(index, html) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + html; + + return '

'; + }); + + // $ExpectType JQuery + $('p').append(function(index, html) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + html; + + return new Element(); + }); + + // $ExpectType JQuery + $('p').append(function(index, html) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + html; + + return new Text(); + }); + + // $ExpectType JQuery + $('p').append(function(index, html) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + html; + + return [new Element(), new Text()]; + }); + + // $ExpectType JQuery + $('p').append(function(index, html) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + html; + + return $('p'); + }); + + // $ExpectType JQuery + $('p').append($.parseHTML('myTextNode ')); + } + + function before() { + // $ExpectType JQuery + $('p').before('

', new Element(), new Text(), $('p'), [new Element(), new Text()]); + + // $ExpectType JQuery + $('p').before(function(index, html) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + html; + + return '

'; + }); + + // $ExpectType JQuery + $('p').before(function(index, html) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + html; + + return new Element(); + }); + + // $ExpectType JQuery + $('p').before(function(index, html) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + html; + + return new Text(); + }); + + // $ExpectType JQuery + $('p').before(function(index, html) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + html; + + return [new Element(), new Text()]; + }); + + // $ExpectType JQuery + $('p').before(function(index, html) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + html; + + return $('p'); + }); + } + + function prepend() { + // $ExpectType JQuery + $('p').prepend('

', new Element(), new Text(), $('p'), [new Element(), new Text()]); + + // $ExpectType JQuery + $('p').prepend(function(index, html) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + html; + + return '

'; + }); + + // $ExpectType JQuery + $('p').prepend(function(index, html) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + html; + + return new Element(); + }); + + // $ExpectType JQuery + $('p').prepend(function(index, html) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + html; + + return new Text(); + }); + + // $ExpectType JQuery + $('p').prepend(function(index, html) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + html; + + return [new Element(), new Text()]; + }); + + // $ExpectType JQuery + $('p').prepend(function(index, html) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + html; + + return $('p'); + }); + } + + function appendTo() { + // $ExpectType JQuery + $('span').appendTo('p'); + + // $ExpectType JQuery + $('span').appendTo('

'); + + // $ExpectType JQuery + $('span').appendTo(new HTMLElement()); + + // $ExpectType JQuery + $('span').appendTo([new HTMLElement()]); + + // $ExpectType JQuery + $('span').appendTo($('p')); + } + + function insertAfter() { + // $ExpectType JQuery + $('span').insertAfter('p'); + + // $ExpectType JQuery + $('span').insertAfter('

'); + + // $ExpectType JQuery + $('span').insertAfter(new HTMLElement()); + + // $ExpectType JQuery + $('span').insertAfter([new HTMLElement()]); + + // $ExpectType JQuery + $('span').insertAfter($('p')); + } + + function insertBefore() { + // $ExpectType JQuery + $('span').insertBefore('p'); + + // $ExpectType JQuery + $('span').insertBefore('

'); + + // $ExpectType JQuery + $('span').insertBefore(new HTMLElement()); + + // $ExpectType JQuery + $('span').insertBefore([new HTMLElement()]); + + // $ExpectType JQuery + $('span').insertBefore($('p')); + } + + function prependTo() { + // $ExpectType JQuery + $('span').prependTo('p'); + + // $ExpectType JQuery + $('span').prependTo('

'); + + // $ExpectType JQuery + $('span').prependTo(new HTMLElement()); + + // $ExpectType JQuery + $('span').prependTo([new HTMLElement()]); + + // $ExpectType JQuery + $('span').prependTo($('p')); + } + + function clone() { + // $ExpectType JQuery + $('p').clone(true, true); + + // $ExpectType JQuery + $('p').clone(true); + + // $ExpectType JQuery + $('p').clone(); + } + + function detach() { + // $ExpectType JQuery + $('p').detach('span'); + + // $ExpectType JQuery + $('p').detach(); + } + + function empty() { + // $ExpectType JQuery + $('p').empty(); + } + + function remove() { + // $ExpectType JQuery + $('p').remove('span'); + + // $ExpectType JQuery + $('p').remove(); + } + + function replaceAll() { + // $ExpectType JQuery + $('p').replaceAll('span'); + + // $ExpectType JQuery + $('p').replaceAll($('span')); + + // $ExpectType JQuery + $('p').replaceAll(new HTMLElement()); + + // $ExpectType JQuery + $('p').replaceAll([new HTMLElement()]); + } + + function replaceWith() { + // $ExpectType JQuery + $('p').replaceWith(''); + + // $ExpectType JQuery + $('p').replaceWith($('span')); + + // $ExpectType JQuery + $('p').replaceWith(new HTMLElement()); + + // $ExpectType JQuery + $('p').replaceWith([new HTMLElement()]); + + // $ExpectType JQuery + $('p').replaceWith(function() { + // $ExpectType HTMLElement + this; + + return this; + }); + } + + function unwrap() { + // $ExpectType JQuery + $('p').unwrap('span'); + + // $ExpectType JQuery + $('p').unwrap(); + } + + function wrap() { + // $ExpectType JQuery + $('p').wrap('span'); + + // $ExpectType JQuery + $('p').wrap(''); + + // $ExpectType JQuery + $('p').wrap(new HTMLElement()); + + // $ExpectType JQuery + $('p').wrap($('span')); + + // $ExpectType JQuery + $('p').wrap(function(index) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + + return ''; + }); + + // $ExpectType JQuery + $('p').wrap(function(index) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + + return $('span'); + }); + } + + function wrapAll() { + // $ExpectType JQuery + $('p').wrapAll('span'); + + // $ExpectType JQuery + $('p').wrapAll(''); + + // $ExpectType JQuery + $('p').wrapAll(new HTMLElement()); + + // $ExpectType JQuery + $('p').wrapAll($('span')); + + // $ExpectType JQuery + $('p').wrapAll(function() { + // $ExpectType HTMLElement + this; + + return ''; + }); + + // $ExpectType JQuery + $('p').wrapAll(function() { + // $ExpectType HTMLElement + this; + + return $('span'); + }); + } + + function wrapInner() { + // $ExpectType JQuery + $('p').wrapInner('span'); + + // $ExpectType JQuery + $('p').wrapInner(''); + + // $ExpectType JQuery + $('p').wrapInner(new HTMLElement()); + + // $ExpectType JQuery + $('p').wrapInner($('span')); + + // $ExpectType JQuery + $('p').wrapInner(function(index) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + + return ''; + }); + + // $ExpectType JQuery + $('p').wrapInner(function(index) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + + return $('span'); + }); + + // $ExpectType JQuery + $('p').wrapInner(function(index) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + + return new HTMLElement(); + }); + } + + function html() { + // $ExpectType JQuery + $('p').html(''); + + // $ExpectType JQuery + $('p').html(function(index, oldhtml) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + oldhtml; + + return oldhtml; + }); + + // $ExpectType string + $('p').html(); + } + + function text() { + // $ExpectType JQuery + $('p').text('myText'); + + // $ExpectType JQuery + $('p').text(4); + + // $ExpectType JQuery + $('p').text(true); + + // $ExpectType JQuery + $('p').text(function(index, text) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + text; + + return 'myText'; + }); + + // $ExpectType JQuery + $('p').text(function(index, text) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + text; + + return 3; + }); + + // $ExpectType JQuery + $('p').text(function(index, text) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + text; + + return false; + }); + + // $ExpectType string + $('p').text(); + } + + function val() { + // $ExpectType JQuery + $('p').val('myVal'); + + // $ExpectType JQuery + $('p').val(5); + + // $ExpectType JQuery + $('p').val(['myVal']); + + // $ExpectType JQuery + $('p').val(function(index, value) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType string + value; + + return 'myVal'; + }); + + // $ExpectType string | number | string[] | undefined + $('p').val(); + } + } + + function traversing() { + function add() { + // $ExpectType JQuery + $('p').add('span', new HTMLElement()); + + // $ExpectType JQuery + $('p').add('span'); + + // $ExpectType JQuery + $('p').add(new HTMLElement()); + + // $ExpectType JQuery + $('p').add([new HTMLElement()]); + + // $ExpectType JQuery + $('p').add(''); + + // $ExpectType JQuery + $('p').add($('span')); + } + + function closest() { + // $ExpectType JQuery + $('p').closest('span', new HTMLElement()); + + // $ExpectType JQuery + $('p').closest('span'); + + // $ExpectType JQuery + $('p').closest(new HTMLElement()); + + // $ExpectType JQuery + $('p').closest($('span')); + } + + function find() { + // $ExpectType JQuery + $('p').find('span'); + + // $ExpectType JQuery + $('p').find(new HTMLElement()); + + // $ExpectType JQuery + $('p').find($('span')); + } + + function addBack() { + // $ExpectType JQuery + $('p').addBack('span'); + + // $ExpectType JQuery + $('p').addBack(); + } + + function children() { + // $ExpectType JQuery + $('p').children('span'); + + // $ExpectType JQuery + $('p').children(); + } + + function siblings() { + // $ExpectType JQuery + $('p').siblings('span'); + + // $ExpectType JQuery + $('p').siblings(); + } + + function contents() { + // $ExpectType JQuery + $('p').contents(); + } + + function end() { + // $ExpectType JQuery + $('p').end(); + } + + function first() { + // $ExpectType JQuery + $('p').first(); + } + + function last() { + // $ExpectType JQuery + $('p').last(); + } + + function offsetParent() { + // $ExpectType JQuery + $('p').offsetParent(); + } + + function filter() { + // $ExpectType JQuery + $('p').filter('span'); + + // $ExpectType JQuery + $('p').filter(new HTMLElement()); + + // $ExpectType JQuery + $('p').filter([new HTMLElement()]); + + // $ExpectType JQuery + $('p').filter($('span')); + + // $ExpectType JQuery + $('p').filter(function(index, element) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType HTMLElement + element; + + return false; + }); + } + + function not() { + // $ExpectType JQuery + $('p').not('span'); + + // $ExpectType JQuery + $('p').not(new HTMLElement()); + + // $ExpectType JQuery + $('p').not([new HTMLElement()]); + + // $ExpectType JQuery + $('p').not($('span')); + + // $ExpectType JQuery + $('p').not(function(index, element) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType HTMLElement + element; + + return false; + }); + } + + function is() { + // $ExpectType boolean + $('p').is('span'); + + // $ExpectType boolean + $('p').is(new HTMLElement()); + + // $ExpectType boolean + $('p').is([new HTMLElement()]); + + // $ExpectType boolean + $('p').is($('span')); + + // $ExpectType boolean + $('p').is(function(index, element) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType HTMLElement + element; + + return false; + }); + } + + function next() { + // $ExpectType JQuery + $('p').next('span'); + + // $ExpectType JQuery + $('p').next(); + } + + function nextAll() { + // $ExpectType JQuery + $('p').nextAll('span'); + + // $ExpectType JQuery + $('p').nextAll(); + } + + function nextUntil() { + // $ExpectType JQuery + $('p').nextUntil('span', 'span'); + + // $ExpectType JQuery + $('p').nextUntil(new HTMLElement(), 'span'); + + // $ExpectType JQuery + $('p').nextUntil($('span'), 'span'); + + // $ExpectType JQuery + $('p').nextUntil('span'); + + // $ExpectType JQuery + $('p').nextUntil(new HTMLElement()); + + // $ExpectType JQuery + $('p').nextUntil($('span')); + + // $ExpectType JQuery + $('p').nextUntil(); + } + + function prev() { + // $ExpectType JQuery + $('p').prev('span'); + + // $ExpectType JQuery + $('p').prev(); + } + + function prevAll() { + // $ExpectType JQuery + $('p').prevAll('span'); + + // $ExpectType JQuery + $('p').prevAll(); + } + + function prevUntil() { + // $ExpectType JQuery + $('p').prevUntil('span', 'span'); + + // $ExpectType JQuery + $('p').prevUntil(new HTMLElement(), 'span'); + + // $ExpectType JQuery + $('p').prevUntil($('span'), 'span'); + + // $ExpectType JQuery + $('p').prevUntil('span'); + + // $ExpectType JQuery + $('p').prevUntil(new HTMLElement()); + + // $ExpectType JQuery + $('p').prevUntil($('span')); + + // $ExpectType JQuery + $('p').prevUntil(); + } + + function parent() { + // $ExpectType JQuery + $('p').parent('span'); + + // $ExpectType JQuery + $('p').parent(); + } + + function parents() { + // $ExpectType JQuery + $('p').parents('span'); + + // $ExpectType JQuery + $('p').parents(); + } + + function parentsUntil() { + // $ExpectType JQuery + $('p').parentsUntil('span', 'span'); + + // $ExpectType JQuery + $('p').parentsUntil(new HTMLElement(), 'span'); + + // $ExpectType JQuery + $('p').parentsUntil($('span'), 'span'); + + // $ExpectType JQuery + $('p').parentsUntil('span'); + + // $ExpectType JQuery + $('p').parentsUntil(new HTMLElement()); + + // $ExpectType JQuery + $('p').parentsUntil($('span')); + + // $ExpectType JQuery + $('p').parentsUntil(); + } + + function eq() { + // $ExpectType JQuery + $('p').eq(0); + } + + function has() { + // $ExpectType JQuery + $('p').has('span'); + + // $ExpectType JQuery + $('p').has(new HTMLElement()); + } + + function map() { + // $ExpectType JQuery + $('p').map(function(index, domElement) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType HTMLElement + domElement; + + return 'myVal'; + }); + + // $ExpectType JQuery + $('p').map(function(index, domElement) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType HTMLElement + domElement; + + return ['myVal1', 'myVal2']; + }); + + // $ExpectType JQuery + $('p').map(function(index, domElement) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType HTMLElement + domElement; + + return null; + }); + + // $ExpectType JQuery + $('p').map(function(index, domElement) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType HTMLElement + domElement; + + return undefined; + }); + } + + function slice() { + // $ExpectType JQuery + $('p').slice(0, 10); + + // $ExpectType JQuery + $('p').slice(0); + } + + function pushStack() { + // $ExpectType JQuery + $('p').pushStack([new HTMLElement()], 'name', ['arg']); + + // $ExpectType JQuery + $('p').pushStack([new HTMLElement()]); + } + } + + function misc() { + function serialize() { + // $ExpectType string + $('p').serialize(); + } + + function serializeArray() { + // $ExpectType NameValuePair[] + $('p').serializeArray(); + } + + function each() { + // $ExpectType JQuery + $('p').each(function(index, element) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType HTMLElement + element; + }); + + // $ExpectType JQuery + $('p').each(function(index, element) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType HTMLElement + element; + + return false; + }); + } + + function extend() { + // $ExpectType JQuery + $.fn.extend({ myPlugin: {} }); + } + + function get() { + // $ExpectType HTMLElement + $('p').get(0); + + // $ExpectType HTMLElement[] + $('p').get(); + } + + function index() { + // $ExpectType number + $('p').index('span'); + + // $ExpectType number + $('p').index(new HTMLElement()); + + // $ExpectType number + $('p').index($('span')); + + // $ExpectType number + $('p').index(); + } + + function toArray() { + // $ExpectType HTMLElement[] + $('p').toArray(); + } } } function JQueryStatic() { + function type_assertion() { + const $Canvas = $ as JQueryStatic; + } + function type_annotation() { const jq: JQueryStatic = $; } - function constructor() { - function selector_object_callback() { - const jq = $ as JQueryStatic; - // $ExpectType JQuery - jq('div'); - } + function call_signature() { + // #ExpectType JQuery + $('

', new Document()); + + // #ExpectType JQuery + $('

', { + class: 'my-div', + on: { + touchstart() { + // Do something + } + } + }); + + // #ExpectType JQuery + $('span', new HTMLElement()); + + // #ExpectType JQuery + $('span', new Document()); + + // #ExpectType JQuery + $('span', $('p')); + + // #ExpectType JQuery + $('span'); + + // #ExpectType JQuery + $('

'); + + // #ExpectType JQuery + $(new HTMLElement()); + + // #ExpectType JQuery + $([new HTMLElement()]); + + // #ExpectType JQuery + $({ foo: 'bar', hello: 'world' }); + + // #ExpectType JQuery + $($('p')); + + // #ExpectType JQuery + $(function($) { + // #ExpectType Document + this; + // #ExpectType JQueryStatic + $; + }); + + // #ExpectType JQuery + $(); } function Callbacks() { - const cb = $.Callbacks(); + // #ExpectType Callbacks + $.Callbacks('once'); - cb.add(console.log); + // #ExpectType Callbacks + $.Callbacks(); } function Event() { @@ -48,26 +3546,468 @@ function JQueryStatic() { } } + function ajax() { + // $ExpectType jqXHR + $.ajax('url', { + cache: true + }); + } + + function ajaxPrefilter() { + // $ExpectType void + $.ajaxPrefilter('dataTypes', (options, originalOptions, jqXHR) => { + // $ExpectType AjaxSettings + options; + // $ExpectType AjaxSettings + originalOptions; + // $ExpectType jqXHR + jqXHR; + + return 'filtered'; + }); + + // $ExpectType void + $.ajaxPrefilter('dataTypes', (options, originalOptions, jqXHR) => { + // $ExpectType AjaxSettings + options; + // $ExpectType AjaxSettings + originalOptions; + // $ExpectType jqXHR + jqXHR; + }); + + // $ExpectType void + $.ajaxPrefilter((options, originalOptions, jqXHR) => { + // $ExpectType AjaxSettings + options; + // $ExpectType AjaxSettings + originalOptions; + // $ExpectType jqXHR + jqXHR; + + return 'filtered'; + }); + + // $ExpectType void + $.ajaxPrefilter((options, originalOptions, jqXHR) => { + // $ExpectType AjaxSettings + options; + // $ExpectType AjaxSettings + originalOptions; + // $ExpectType jqXHR + jqXHR; + }); + } + + function ajaxSetup() { + // $ExpectType AjaxSettings + $.ajaxSetup({ + cache: true + }); + } + + function ajaxTransport() { + // $ExpectType void + $.ajaxTransport('dataTypes', (options, originalOptions, jqXHR) => { + // $ExpectType AjaxSettings + options; + // $ExpectType AjaxSettings + originalOptions; + // $ExpectType jqXHR + jqXHR; + + return { + send(headers, completeCallback) { + // $ExpectType PlainObject + headers; + // $ExpectType SuccessCallback + completeCallback; + }, + abort() { } + }; + }); + + // $ExpectType void + $.ajaxTransport('dataTypes', (options, originalOptions, jqXHR) => { + // $ExpectType AjaxSettings + options; + // $ExpectType AjaxSettings + originalOptions; + // $ExpectType jqXHR + jqXHR; + }); + } + + function contains() { + // $ExpectType boolean + $.contains(new HTMLElement(), new HTMLElement()); + } + + function css() { + // $ExpectType any + $.css(new HTMLElement(), {}); + } + + function data() { + // $ExpectType any + $.data(new HTMLElement(), 'myKey', undefined); + + // $ExpectType "myValue" + $.data(new HTMLElement(), 'myKey', 'myValue'); + + // $ExpectType any + $.data(new HTMLElement(), 'myKey'); + + // $ExpectType any + $.data(new HTMLElement()); + } + + function dequeue() { + // $ExpectType void + $.dequeue(new HTMLElement(), 'myQueue'); + + // $ExpectType void + $.dequeue(new HTMLElement()); + } + function each() { - function arrayLike() { - $.each({ length: 3 }, (index, val) => { - index === 3; - }); - } + // $ExpectType ArrayLike + $.each(['myVal1', 'myVal2'], function(index, val) { + // $ExpectType string + this; + // $ExpectType number + index; + // $ExpectType string + val; + + return false; + }); + + // $ExpectType ArrayLike + $.each(['myVal1', 'myVal2'], function(index, val) { + // $ExpectType string + this; + // $ExpectType number + index; + // $ExpectType string + val; + + return 10; + }); + + // $ExpectType ArrayLike + $.each(['myVal1', 'myVal2'], function(index, val) { + // $ExpectType string + this; + // $ExpectType number + index; + // $ExpectType string + val; + }); + + // $ExpectType { myVal1: boolean; myVal2: () => 10; myVal3: string; } + $.each({ + myVal1: false, + myVal2: () => { + return 10; + }, + myVal3: 'myVal3' + }, function(propertyName, valueOfProperty) { + // $ExpectType string | boolean | (() => 10) + this; + // $ExpectType "myVal1" | "myVal2" | "myVal3" + propertyName; + // $ExpectType string | boolean | (() => 10) + valueOfProperty; + + return false; + }); + + // $ExpectType { myVal1: boolean; myVal2: () => 10; myVal3: string; } + $.each({ + myVal1: false, + myVal2: () => { + return 10; + }, + myVal3: 'myVal3' + }, function(propertyName, valueOfProperty) { + // $ExpectType string | boolean | (() => 10) + this; + // $ExpectType "myVal1" | "myVal2" | "myVal3" + propertyName; + // $ExpectType string | boolean | (() => 10) + valueOfProperty; + + return 10; + }); + + // $ExpectType { myVal1: boolean; myVal2: () => 10; myVal3: string; } + $.each({ + myVal1: false, + myVal2: () => { + return 10; + }, + myVal3: 'myVal3' + }, function(propertyName, valueOfProperty) { + // $ExpectType string | boolean | (() => 10) + this; + // $ExpectType "myVal1" | "myVal2" | "myVal3" + propertyName; + // $ExpectType string | boolean | (() => 10) + valueOfProperty; + }); + } + + function error() { + jQuery.error = console.error; + } + + function escapeSelector() { + // $ExpectType string + $.escapeSelector('span'); + } + + function extend() { + const t = { name: 'myObj' }; + const u = new EventTarget(); + const v = new Node(); + const w = new Comment(); + const x = new Text(); + const y = new Element(); + const z = new HTMLElement(); + const a = new SVGElement(); + + // $ExpectType { name: string; } & EventTarget & Node & Comment & Text & Element & HTMLElement + $.extend(true, t, u, v, w, x, y, z); + + // $ExpectType { name: string; } & EventTarget & Node & Comment & Text & Element + $.extend(true, t, u, v, w, x, y); + + // $ExpectType { name: string; } & EventTarget & Node & Comment & Text + $.extend(true, t, u, v, w, x); + + // $ExpectType { name: string; } & EventTarget & Node & Comment + $.extend(true, t, u, v, w); + + // $ExpectType { name: string; } & EventTarget & Node + $.extend(true, t, u, v); + + // $ExpectType { name: string; } & EventTarget + $.extend(true, t, u); + + // $ExpectType any + $.extend(true, t, u, v, w, x, y, z, a); + + // $ExpectType { name: string; } & EventTarget & Node & Comment & Text & Element & HTMLElement + $.extend(t, u, v, w, x, y, z); + + // $ExpectType { name: string; } & EventTarget & Node & Comment & Text & Element + $.extend(t, u, v, w, x, y); + + // $ExpectType { name: string; } & EventTarget & Node & Comment & Text + $.extend(t, u, v, w, x); + + // $ExpectType { name: string; } & EventTarget & Node & Comment + $.extend(t, u, v, w); + + // $ExpectType { name: string; } & EventTarget & Node + $.extend(t, u, v); + + // $ExpectType { name: string; } & EventTarget + $.extend(t, u); + + // $ExpectType any + $.extend(t, u, v, w, x, y, z, a); + } + + function get() { + // $ExpectType jqXHR + $.get('url', { myData: 'myData' }, (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }, 'script'); + + // $ExpectType jqXHR + $.get('url', 'myData', (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }, 'script'); + + // $ExpectType jqXHR + $.get('url', { myData: 'myData' }, null, 'script'); + + // $ExpectType jqXHR + $.get('url', 'myData', null, 'script'); + + // $ExpectType jqXHR + $.get('url', (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }, 'script'); + + // $ExpectType jqXHR + $.get('url', null, 'script'); + + // $ExpectType jqXHR + $.get('url', (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }, 'script'); + + // $ExpectType jqXHR + $.get('url', { myData: 'myData' }); + + // $ExpectType jqXHR + $.get('url', 'myData'); + + // $ExpectType jqXHR + $.get('url'); + + // $ExpectType jqXHR + $.get({ url: 'url' }); + + // $ExpectType jqXHR + $.get(); + } + + function getJSON() { + // $ExpectType jqXHR + $.getJSON('url', { myVal1: 'myVal1' }, (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }); + + // $ExpectType jqXHR + $.getJSON('url', 'myVal1', (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }); + + // $ExpectType jqXHR + $.getJSON('url', (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }); + + // $ExpectType jqXHR + $.getJSON('url', { myVal1: 'myVal1' }); + + // $ExpectType jqXHR + $.getJSON('url', 'myVal1'); + + // $ExpectType jqXHR + $.getJSON('url'); + } + + function getScript() { + // $ExpectType jqXHR + $.getScript('url', (data, textStatus, jqXHR) => { + // $ExpectType string | undefined + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }); + } + + function globalEval() { + // $ExpectType void + $.globalEval('throw new Error();'); + } + + function grep() { + // $ExpectType string[] + $.grep(['myVal1', 'myVal2'], (elementOfArray, indexInArray) => { + // $ExpectType string + elementOfArray; + // $ExpectType number + indexInArray; + + return true; + }, true); + + // $ExpectType string[] + $.grep(['myVal1', 'myVal2'], (elementOfArray, indexInArray) => { + // $ExpectType string + elementOfArray; + // $ExpectType number + indexInArray; + + return true; + }); + } + + function hasData() { + // $ExpectType boolean + $.hasData(new HTMLElement()); + } + + function holdReady() { + // $ExpectType void + $.holdReady(true); + } + + function htmlPrefilter() { + // $ExpectType string + $.htmlPrefilter(''); + } + + function inArray() { + // $ExpectType number + $.inArray(1, [1, 2], 1); + + // $ExpectType number + $.inArray(1, [1, 2]); } function isArray() { function type_guard(obj: object) { if ($.isArray(obj)) { - console.log(obj[0]); + // $ExpectType any[] + obj; } } } + function isEmptyObject() { + // $ExpectType boolean + $.isEmptyObject({}); + } + function isFunction() { function type_guard(obj: object) { if ($.isFunction(obj)) { - obj(); + // $ExpectType Function + obj; } } } @@ -75,7 +4015,8 @@ function JQueryStatic() { function isNumeric() { function type_guard(obj: boolean) { if ($.isNumeric(obj)) { - obj.toFixed(); + // $ExpectType (true & number) | (false & number) + obj; } } } @@ -83,7 +4024,8 @@ function JQueryStatic() { function isPlainObject() { function type_guard(obj: object) { if ($.isPlainObject(obj)) { - obj['key'] = true; + // $ExpectType PlainObject + obj; } } } @@ -91,37 +4033,239 @@ function JQueryStatic() { function isWindow() { function type_guard(obj: object) { if ($.isWindow(obj)) { - obj.location.href === 'href'; + // $ExpectType Window + obj; } } } + function isXMLDoc() { + // $ExpectType boolean + $.isXMLDoc(new Node()); + } + + function makeArray() { + // $ExpectType number[] + $.makeArray([1, 2]); + } + function map() { - function object() { - const testObj = { - myProp: true, - name: 'Rogers', - }; + // $ExpectType number[] + $.map([1, 2, 3], (elementOfArray, indexInArray) => { + // $ExpectType number + elementOfArray; + // $ExpectType number + indexInArray; - const results = $.map(testObj, (propertyOfObject, key) => { - switch (key) { - case 'myProp': - return 1; - case 'name': - return false; - } - }); + return 200 + 10; + }); - for (const result of results) { - result === 1; + // $ExpectType (false | 1)[] + $.map({ + myProp: true, + name: 'Rogers', + }, (propertyOfObject, key) => { + // $ExpectType string | boolean + propertyOfObject; + // $ExpectType "myProp" | "name" + key; + + switch (key) { + case 'myProp': + return 1; + case 'name': + return false; } - } + }); + } + + function merge() { + // $ExpectType (string | number)[] + $.merge([1, 2, 3], ['myVal1', 'myVal2']); + } + + function noConflict() { + // $ExpectType JQueryStatic + $.noConflict(true); + + // $ExpectType JQueryStatic + $.noConflict(); + } + + function noop() { + // $ExpectType undefined + $.noop(); + } + + function now() { + // $ExpectType number + $.now(); + } + + function param() { + // $ExpectType string + $.param([true, 20], true); + + // $ExpectType string + $.param({ + myVal1: true, + myVal2: 20 + }, true); + + // $ExpectType string + $.param($('input'), true); + + // $ExpectType string + $.param([true, 20]); + + // $ExpectType string + $.param({ + myVal1: true, + myVal2: 20 + }); + + // $ExpectType string + $.param($('input')); + } + + function parseHTML() { + // $ExpectType Node[] + $.parseHTML('', document, true); + + // $ExpectType Node[] + $.parseHTML('', null, true); + + // $ExpectType Node[] + $.parseHTML('', undefined, true); + + // $ExpectType Node[] + $.parseHTML('', document); + + // $ExpectType Node[] + $.parseHTML('', null); + + // $ExpectType Node[] + $.parseHTML('', undefined); + + // $ExpectType Node[] + $.parseHTML('', false); + + // $ExpectType Node[] + $.parseHTML(''); + } + + function parseJSON() { + // $ExpectType any + $.parseJSON('{}'); + } + + function parseXML() { + // $ExpectType XMLDocument + $.parseXML(''); + } + + function post() { + // $ExpectType jqXHR + $.post('url', { myData: 'myData' }, (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }, 'script'); + + // $ExpectType jqXHR + $.post('url', 'myData', (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }, 'script'); + + // $ExpectType jqXHR + $.post('url', { myData: 'myData' }, null, 'script'); + + // $ExpectType jqXHR + $.post('url', 'myData', null, 'script'); + + // $ExpectType jqXHR + $.post('url', (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }, 'script'); + + // $ExpectType jqXHR + $.post('url', null, 'script'); + + // $ExpectType jqXHR + $.post('url', (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }, 'script'); + + // $ExpectType jqXHR + $.post('url', { myData: 'myData' }); + + // $ExpectType jqXHR + $.post('url', 'myData'); + + // $ExpectType jqXHR + $.post('url'); + + // $ExpectType jqXHR + $.post({ url: 'url' }); + + // $ExpectType jqXHR + $.post(); + } + + function proxy() { + // $ExpectType Function + $.proxy($.noop, {}, 1, 2); + + // $ExpectType Function + $.proxy($.noop, {}); + + // $ExpectType Function + $.proxy({ myFunc: $.noop }, 'myFunc', 1, 2); + + // $ExpectType Function + $.proxy({ myFunc: $.noop }, 'myFunc'); } function queue() { - const el = new HTMLElement(); - const queue = jQuery.queue(el); - queue[0] === 'inprogress'; + // $ExpectType Queue + $.queue(new HTMLElement(), 'myQueue', function(next) { + // $ExpectType HTMLElement + this; + // $ExpectType () => void + next; + }); + + // $ExpectType Queue + $.queue(new HTMLElement(), 'myQueue', [function(next) { + // $ExpectType HTMLElement + this; + // $ExpectType () => void + next; + }]); + + // $ExpectType Queue + $.queue(new HTMLElement(), 'myQueue'); + + // $ExpectType Queue + $.queue(new HTMLElement()); } function readyException() { @@ -129,15 +4273,327 @@ function JQueryStatic() { console.error(error); }; } + + function removeData() { + // $ExpectType void + $.removeData(new HTMLElement(), 'test1'); + + // $ExpectType void + $.removeData(new HTMLElement()); + } + + function speed() { + // $ExpectType EffectsOptions + $.speed(5000, 'linear', function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType EffectsOptions + $.speed(5000, 'linear'); + + // $ExpectType EffectsOptions + $.speed(5000, function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType EffectsOptions + $.speed(5000); + + // $ExpectType EffectsOptions + $.speed(function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType EffectsOptions + $.speed({ + duration: 5000, + easing: 'linear', + complete() { + // $ExpectType HTMLElement + this; + } + }); + + // $ExpectType EffectsOptions + $.speed(); + } + + function trim() { + // $ExpectType string + $.trim('myStr'); + } + + function type() { + // $ExpectType "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" | "error" | "array" | "date" | "null" | "regexp" + $.type({}); + } + + function unique() { + // $ExpectType HTMLElement[] + $.unique([new HTMLElement()]); + } + + function uniqueSort() { + // $ExpectType HTMLElement[] + $.uniqueSort([new HTMLElement()]); + } + + function when() { + const t = $.ajax() as JQuery.jqXHR; + const u = $.ajax() as JQuery.jqXHR; + const v = $.ajax() as JQuery.jqXHR; + + // $ExpectType Promise<[string | number | boolean, string, jqXHR], any, any> + $.when(t, u, v); + + // $ExpectType Promise<[string | number, string, jqXHR], any, any> + $.when(t, u); + + // $ExpectType Promise, any, any> + $.when(t); + + // $ExpectType Promise + $.when($.Deferred()); + + // $ExpectType Promise + $.when(); + } +} + +function AjaxSettings() { + $.ajax({ + accepts: { + mycustomtype: 'application/x-some-custom-type' + }, + async: true, + beforeSend(jqXHR, settings) { + // $ExpectType any + this; + // $ExpectType jqXHR + jqXHR; + // $ExpectType AjaxSettingsBase + settings; + }, + cache: false, + complete(jqXHR, textStatus) { + // $ExpectType any + this; + // $ExpectType jqXHR + jqXHR; + // $ExpectType TextStatus + textStatus; + }, + contents: { + mycustomtype: /mycustomtype/ + }, + contentType: 'application/x-some-custom-type', + converters: { + 'text mycustomtype': true, + 'mycustomtype json': (result) => { + // $ExpectType any + result; + + return result; + } + }, + crossDomain: false, + data: { + myData: 'myData' + }, + dataFilter(data, type) { + // $ExpectType string + data; + // $ExpectType string + type; + + return 'filtered'; + }, + dataType: 'mycustomtype', + error(jqXHR, textStatus, errorThrown) { + // $ExpectType any + this; + // $ExpectType jqXHR + jqXHR; + // $ExpectType ErrorTextStatus + textStatus; + // $ExpectType string + errorThrown; + }, + global: true, + headers: { + 'X-Requested-With': 'XMLHttpRequest' + }, + ifModified: false, + isLocal: true, + jsonp: 'callback', + jsonpCallback: 'callback', + method: 'PUT', + mimeType: 'mimeType', + password: 'hunter2', + processData: false, + scriptCharset: 'scriptCharset', + statusCode: { + 200(data, textStatus, jqXHR) { + // $ExpectType any + this; + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }, + 404(jqXHR, textStatus, errorThrown) { + // $ExpectType any + this; + // $ExpectType jqXHR + jqXHR; + // $ExpectType ErrorTextStatus + textStatus; + // $ExpectType string + errorThrown; + } + }, + success(data, textStatus, jqXHR) { + // $ExpectType any + this; + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }, + timeout: 10, + traditional: true, + username: 'username', + xhr() { + return new XMLHttpRequest(); + }, + xhrFields: { + withCredentials: true + } + }); + + $.ajax({ + beforeSend(jqXHR, settings) { + // $ExpectType any + this; + // $ExpectType jqXHR + jqXHR; + // $ExpectType AjaxSettingsBase + settings; + + return false; + }, + complete: [function(jqXHR, textStatus) { + // $ExpectType any + this; + // $ExpectType jqXHR + jqXHR; + // $ExpectType TextStatus + textStatus; + }], + contentType: false, + data: 'myData', + error: [function(jqXHR, textStatus, errorThrown) { + // $ExpectType any + this; + // $ExpectType jqXHR + jqXHR; + // $ExpectType ErrorTextStatus + textStatus; + // $ExpectType string + errorThrown; + }], + jsonp: false, + jsonpCallback() { + // $ExpectType any + this; + + return 'callback'; + }, + success: [function(data, textStatus, jqXHR) { + // $ExpectType any + this; + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }] + }); +} + +function EffectsOptions() { + $('p').show({ + always(animation, jumpToEnd) { + // $ExpectType HTMLElement + this; + // $ExpectType Promise + animation; + // $ExpectType boolean + jumpToEnd; + }, + complete() { + // $ExpectType HTMLElement + this; + }, + done(animation, jumpToEnd) { + // $ExpectType HTMLElement + this; + // $ExpectType Promise + animation; + // $ExpectType boolean + jumpToEnd; + }, + duration: 5000, + easing: 'linear', + fail(animation, jumpToEnd) { + // $ExpectType HTMLElement + this; + // $ExpectType Promise + animation; + // $ExpectType boolean + jumpToEnd; + }, + progress(animation, progress, remainingMs) { + // $ExpectType HTMLElement + this; + // $ExpectType Promise + animation; + // $ExpectType number + progress; + // $ExpectType number + remainingMs; + }, + queue: true, + specialEasing: { + width: 'linear', + height: 'easeOutBounce' + }, + start(animation) { + // $ExpectType HTMLElement + this; + // $ExpectType Promise + animation; + }, + step(now, tween) { + // $ExpectType HTMLElement + this; + // $ExpectType number + now; + // $ExpectType Tween + tween; + } + }); } function JQuery_Event() { - function type_guard(e: object) { - if (e instanceof JQuery.Event) { - e.isDefaultPrevented() === true; - } - } - function mixin() { const e = $.Event('keydown', { mySpecialKeyCode: JQuery.Key.CapsLock, @@ -184,7 +4640,7 @@ function jqXHR() { $.ajax('/echo').fail((jqXHR, textStatus, errorThrown) => { // $ExpectType jqXHR jqXHR; - // $ExpectType "abort" | "timeout" | "error" | "parsererror" | null + // $ExpectType ErrorTextStatus textStatus; // $ExpectType string errorThrown; diff --git a/types/jquery/test/example-tests.ts b/types/jquery/test/example-tests.ts index d2c0a8464d..404aba2013 100644 --- a/types/jquery/test/example-tests.ts +++ b/types/jquery/test/example-tests.ts @@ -1822,8 +1822,8 @@ function examples() { } function finish_0() { - var horiz = $('#path').width() - 20, - vert = $('#path').height() - 20; + var horiz = $('#path').width()! - 20, + vert = $('#path').height()! - 20; var btns: { [key: string]: () => void; } = { bstt: function() { @@ -1992,13 +1992,13 @@ function examples() { } $('#getp').click(function() { - showHeight('paragraph', $('p').height()); + showHeight('paragraph', $('p').height()!); }); $('#getd').click(function() { - showHeight('document', $(document).height()); + showHeight('document', $(document).height()!); }); $('#getw').click(function() { - showHeight('window', $(window).height()); + showHeight('window', $(window).height()!); }); } @@ -2434,7 +2434,7 @@ function examples() { } function jQuery_error_0() { - jQuery.error = console.error as any; + jQuery.error = console.error; } function jQuery_escape_selector_0() { @@ -2907,7 +2907,7 @@ function examples() { function jQuery_parse_html_0() { var $log = $('#log'), str = 'hello, my name is jQuery.', - html = $.parseHTML(str) as HTMLElement[], + html = $.parseHTML(str), nodeNames: string[] = []; // Append the parsed HTML @@ -4056,7 +4056,7 @@ function examples() { function promise_0() { var div = $('
'); - div.promise().done(function(this: JQuery, arg1: JQuery) { + div.promise().done(function(this: typeof div, arg1) { // Will fire right away and alert "true" alert(this === div && arg1 === div); }); @@ -4935,13 +4935,13 @@ function examples() { } $('#getp').click(function() { - showWidth('paragraph', $('p').width()); + showWidth('paragraph', $('p').width()!); }); $('#getd').click(function() { - showWidth('document', $(document).width()); + showWidth('document', $(document).width()!); }); $('#getw').click(function() { - showWidth('window', $(window).width()); + showWidth('window', $(window).width()!); }); } diff --git a/types/jquery/test/jquery-no-window-module-tests.ts b/types/jquery/test/jquery-no-window-module-tests.ts new file mode 100644 index 0000000000..2f2de4cc98 --- /dev/null +++ b/types/jquery/test/jquery-no-window-module-tests.ts @@ -0,0 +1,5 @@ +import jQueryFactory = require('jquery'); + +const jq = jQueryFactory(window, true); +// $ExpectType JQueryStatic +jq; diff --git a/types/jquery/test/jquery-slim-no-window-module-tests.ts b/types/jquery/test/jquery-slim-no-window-module-tests.ts new file mode 100644 index 0000000000..2e104af0eb --- /dev/null +++ b/types/jquery/test/jquery-slim-no-window-module-tests.ts @@ -0,0 +1,5 @@ +import jQueryFactory = require('jquery/dist/jquery.slim'); + +const jq = jQueryFactory(window, true); +// $ExpectType JQueryStatic +jq; diff --git a/types/jquery/test/jquery-slim-window-module-tests.ts b/types/jquery/test/jquery-slim-window-module-tests.ts new file mode 100644 index 0000000000..76870e7a04 --- /dev/null +++ b/types/jquery/test/jquery-slim-window-module-tests.ts @@ -0,0 +1,5 @@ +import * as jq from 'jquery/dist/jquery.slim'; + +const $window = jq(window); +// $ExpectType JQuery +$window; diff --git a/types/jquery/test/jquery-window-module-tests.ts b/types/jquery/test/jquery-window-module-tests.ts new file mode 100644 index 0000000000..71e20bc4a0 --- /dev/null +++ b/types/jquery/test/jquery-window-module-tests.ts @@ -0,0 +1,18 @@ +import * as jq from 'jquery'; + +const $window = jq(window); +// $ExpectType JQuery +$window; + +class CanvasLayersDirective { + private readonly $renderingCanvas: JQuery; + private readonly $offscreenCanvas: JQuery; + + constructor(elementRef: { nativeElement: any; }) { + // This type assertion results in an error when exporting 'typeof factory & JQueryStatic' where + // 'factory' is jQuery's factory function. + const $Canvas = $ as JQueryStatic; + this.$renderingCanvas = $Canvas(elementRef.nativeElement); + this.$offscreenCanvas = $Canvas(document.createElement('canvas')); + } +} diff --git a/types/jquery/test/module-tests.ts b/types/jquery/test/module-tests.ts deleted file mode 100644 index b55dee0370..0000000000 --- a/types/jquery/test/module-tests.ts +++ /dev/null @@ -1,7 +0,0 @@ -import factory = require('jquery'); -const jq = factory(window); -jq.noop(); - -import slimFactory = require('jquery/dist/jquery.slim'); -const slim = slimFactory(window); -slim.noop(); diff --git a/types/jquery/tsconfig.json b/types/jquery/tsconfig.json index ebfa01c813..21d35a63da 100644 --- a/types/jquery/tsconfig.json +++ b/types/jquery/tsconfig.json @@ -22,6 +22,9 @@ "jquery-tests.ts", "test/example-tests.ts", "test/longdesc-tests.ts", - "test/module-tests.ts" + "test/jquery-no-window-module-tests.ts", + "test/jquery-window-module-tests.ts", + "test/jquery-slim-no-window-module-tests.ts", + "test/jquery-slim-window-module-tests.ts" ] } diff --git a/types/js-data/v1/js-data-tests.ts b/types/js-data/v1/js-data-tests.ts index 0832f066d9..69a056b081 100644 --- a/types/js-data/v1/js-data-tests.ts +++ b/types/js-data/v1/js-data-tests.ts @@ -30,7 +30,7 @@ User.find(1).then(function (user:IUser) { var user:IUser = User.createInstance({name: 'John'}); var store = new JSData.DS(); -var User2 = store.defineResource('user'); +var User2 = store.defineResource('user'); var user:IUser = User2.inject({id: 1, name: 'John'}); var user2:IUser = User2.inject({id: 1, age: 30}); diff --git a/types/jsnox/index.d.ts b/types/jsnox/index.d.ts index 9587afc8f1..ad5fe5ed2e 100644 --- a/types/jsnox/index.d.ts +++ b/types/jsnox/index.d.ts @@ -2,11 +2,11 @@ // Project: https://github.com/af/jsnox // Definitions by: Steve Baker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 /// -import React = require("react"); +import * as React from "react"; /* * JSnoX requires an object with a createElement method. @@ -25,41 +25,41 @@ interface CreateElement { /** * Renders an HTML element from the given spec string, with children but without * extra props. - * @param specString A string that defines a component in a way that resembles + * @param specString A string that defines a component in a way that resembles * CSS selectors. Eg. "input:email#foo.bar.baz[name=email][required]" * @param children A single React node (string or ReactElement) or array of nodes. - * Note that unlike with React itself, multiple children must be placed into an array. + * Note that unlike with React itself, multiple children must be placed into an array. */

(specString: string, children: React.ReactNode): React.DOMElement /** - * Renders an HTML element from the given spec string, with optional props + * Renders an HTML element from the given spec string, with optional props * and children - * @param specString A string that defines a component in a way that resembles + * @param specString A string that defines a component in a way that resembles * CSS selectors. Eg. "input:email#foo.bar.baz[name=email][required]" * @param props Object of html attribute key-value pairs * @param children A single React node (string or ReactElement) or array of nodes. - * Note that unlike with React itself, multiple children must be placed into an array. + * Note that unlike with React itself, multiple children must be placed into an array. */

(specString: string, props?: React.HTMLAttributes<{}>, children?: React.ReactNode): React.DOMElement /** * Renders a React component, with children but no props - * @param component A plain React component (created from React.createClass()) or + * @param component A plain React component (created from React.createClass()) or * component factory (created from React.createFactory()) * @param children A single React node (string or ReactElement) or array of nodes. - * Note that unlike with React itself, multiple children must be placed into an array. + * Note that unlike with React itself, multiple children must be placed into an array. */

(component: React.ComponentClass

, children: React.ReactNode): React.ReactElement

- /** + /** * Renders a React component, with optional props and children - * @param component A plain React component (created from React.createClass()) or + * @param component A plain React component (created from React.createClass()) or * component factory (created from React.createFactory()) * @param props Props object to pass to the component * @param children A single React node (string or ReactElement) or array of nodes. - * Note that unlike with React itself, multiple children must be placed into an array. + * Note that unlike with React itself, multiple children must be placed into an array. */

(component: React.ComponentClass

, props?: P, children?: React.ReactNode): React.ReactElement

} diff --git a/types/jsnox/jsnox-tests.ts b/types/jsnox/jsnox-tests.ts index 5d7440e315..26014b362f 100644 --- a/types/jsnox/jsnox-tests.ts +++ b/types/jsnox/jsnox-tests.ts @@ -1,6 +1,6 @@ -import React = require('react'); -import jsnox = require('jsnox'); +import * as React from 'react'; +import * as jsnox from 'jsnox'; var $ = jsnox(React); interface PersonProps { @@ -20,7 +20,7 @@ var clickHandler: React.MouseEventHandler<{}>; // Tests with spec string function spec_string () { var result: React.ReactHTMLElement - + // just spec string result = $('div') diff --git a/types/jwt-decode/index.d.ts b/types/jwt-decode/index.d.ts index d27cdf91e9..73dacb3c00 100644 --- a/types/jwt-decode/index.d.ts +++ b/types/jwt-decode/index.d.ts @@ -1,15 +1,15 @@ -// Type definitions for jwt-decode v2.2.0 +// Type definitions for jwt-decode 2.2 // Project: https://github.com/auth0/jwt-decode -// Definitions by: Giedrius Grabauskas , Mads Madsen +// Definitions by: Giedrius Grabauskas , Mads Madsen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - declare namespace JwtDecode { - interface JwtDecodeStatic { - (token: string, options?: { header: boolean }): any; + interface Options { + header: boolean; } } -declare var jwtDecode: JwtDecode.JwtDecodeStatic; -export = jwtDecode; -export as namespace jwt_decode; \ No newline at end of file +declare function JwtDecode(token: string, options?: JwtDecode.Options): TTokenDto; + +export = JwtDecode; +export as namespace jwt_decode; diff --git a/types/jwt-decode/jwt-decode-tests.ts b/types/jwt-decode/jwt-decode-tests.ts index 7e65c2a5a4..22bb5cf6cc 100644 --- a/types/jwt-decode/jwt-decode-tests.ts +++ b/types/jwt-decode/jwt-decode-tests.ts @@ -1,7 +1,6 @@ - -import jwtDecode = require('jwt-decode'); - -let token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmb28iOiJiYXIiLCJleHAiOjEzOTMyODY4OTMsImlhdCI6MTM5MzI2ODg5M30.4-iaDojEVl0pJQMjrbM1EzUIfAZgsbK_kgnVyVxFSVo"; +import * as jwtDecode from "jwt-decode"; + +const token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmb28iOiJiYXIiLCJleHAiOjEzOTMyODY4OTMsImlhdCI6MTM5MzI2ODg5M30.4-iaDojEVl0pJQMjrbM1EzUIfAZgsbK_kgnVyVxFSVo"; interface TokenDto { foo: string; @@ -14,5 +13,7 @@ interface TokenHeaderDto { alg: string; } -let decodedTokenPayload = jwtDecode(token) as TokenDto; -let decodedTokenHeader = jwtDecode(token, { header: true }) as TokenHeaderDto; \ No newline at end of file +const decodedTokenPayloadOld = jwtDecode(token) as TokenDto; +const decodedTokenPayload = jwtDecode(token); +const decodedTokenHeaderOld = jwtDecode(token, { header: true }) as TokenHeaderDto; +const decodedTokenHeader = jwtDecode(token, { header: true }); diff --git a/types/jwt-decode/tsconfig.json b/types/jwt-decode/tsconfig.json index 34ce87d118..8d87ddb618 100644 --- a/types/jwt-decode/tsconfig.json +++ b/types/jwt-decode/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,4 +19,4 @@ "index.d.ts", "jwt-decode-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/jwt-decode/tslint.json b/types/jwt-decode/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/jwt-decode/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/jwt-decode/v1/index.d.ts b/types/jwt-decode/v1/index.d.ts new file mode 100644 index 0000000000..10ec01f10f --- /dev/null +++ b/types/jwt-decode/v1/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for jwt-decode 1.4 +// Project: https://github.com/auth0/jwt-decode +// Definitions by: Giedrius Grabauskas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace JwtDecode { } + +declare function JwtDecode(token: string): TTokenDto; + +export = JwtDecode; +export as namespace jwt_decode; diff --git a/types/jwt-decode/v1/jwt-decode-tests.ts b/types/jwt-decode/v1/jwt-decode-tests.ts new file mode 100644 index 0000000000..f1db120261 --- /dev/null +++ b/types/jwt-decode/v1/jwt-decode-tests.ts @@ -0,0 +1,12 @@ +import jwtDecode = require('jwt-decode'); + +const token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmb28iOiJiYXIiLCJleHAiOjEzOTMyODY4OTMsImlhdCI6MTM5MzI2ODg5M30.4-iaDojEVl0pJQMjrbM1EzUIfAZgsbK_kgnVyVxFSVo"; + +interface TokenDto { + foo: string; + exp: number; + iat: number; +} + +const decodedTokenOld = jwtDecode(token) as TokenDto; +const decodedToken = jwtDecode(token); diff --git a/types/jwt-decode/v1/tsconfig.json b/types/jwt-decode/v1/tsconfig.json new file mode 100644 index 0000000000..a0d0dd4f39 --- /dev/null +++ b/types/jwt-decode/v1/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "jwt-decode": [ + "jwt-decode/v1" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jwt-decode-tests.ts" + ] +} diff --git a/types/jwt-decode/v1/tslint.json b/types/jwt-decode/v1/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/jwt-decode/v1/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/kafka-node/index.d.ts b/types/kafka-node/index.d.ts index 46de85286d..89261a3c4d 100644 --- a/types/kafka-node/index.d.ts +++ b/types/kafka-node/index.d.ts @@ -6,11 +6,12 @@ // # Classes export declare class Client { - constructor(connectionString: string, clientId: string, options?: ZKOptions); + constructor(connectionString: string, clientId?: string, options?: ZKOptions); close(callback?: Function): void; topicExists(topics: Array, callback: Function): void; refreshMetadata(topics: Array, cb?: (error: any, data: any) => any): void; close(cb: (error: any) => any): void; + sendOffsetCommitV2Request(group: string, generationId: number, memberId: string, commits: Array, cb: (error: any, data: any) => any): void; } export declare class Producer { @@ -70,6 +71,8 @@ export declare class ConsumerGroup extends HighLevelConsumer { on(eventName: string, cb: (message: string) => any): void; on(eventName: string, cb: (error: any) => any): void; close(force: boolean, cb: (error: any) => any): void; + generationId: number; + memberId: string; } export declare class Offset { diff --git a/types/karma-coverage/index.d.ts b/types/karma-coverage/index.d.ts index 20ee56f43c..03ca857449 100644 --- a/types/karma-coverage/index.d.ts +++ b/types/karma-coverage/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/karma-runner/karma-coverage // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as karma from 'karma'; import * as istanbul from 'istanbul'; diff --git a/types/karma/index.d.ts b/types/karma/index.d.ts index 59590b0a6d..ab4dc9b31f 100644 --- a/types/karma/index.d.ts +++ b/types/karma/index.d.ts @@ -2,8 +2,8 @@ // Project: https://github.com/karma-runner/karma // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -/// /// // See Karma public API https://karma-runner.github.io/0.13/dev/public-api.html @@ -54,7 +54,7 @@ declare namespace karma { }; EXIT_CODE: string; } - + interface LauncherStatic { generateId(): string; //TODO: injector should be of type `di.Injector` diff --git a/types/kdbush/index.d.ts b/types/kdbush/index.d.ts index fa1581d09c..3ef758b85e 100644 --- a/types/kdbush/index.d.ts +++ b/types/kdbush/index.d.ts @@ -7,20 +7,16 @@ type Points = number[][]; type Get = (point: T) => number; type ArrayType = typeof Int32Array | typeof Array; -declare class KDBush { - ids: number[]; - coords: number[]; - nodeSize: number; - points: T[]; - range(minX: number, minY: number, maxX: number, maxY: number): number[]; - within(x: number, y: number, r: number): number[]; +declare function kdbush(points: Points): kdbush.KDBush; +declare function kdbush(points: T[], getX: Get, getY: Get, nodeSize?: number, ArrayType?: ArrayType): kdbush.KDBush; +declare namespace kdbush { + class KDBush { + ids: number[]; + coords: number[]; + nodeSize: number; + points: T[]; + range(minX: number, minY: number, maxX: number, maxY: number): number[]; + within(x: number, y: number, r: number): number[]; + } } - -interface KDBushStatic { - (points: Points): KDBush; - (points: T[], getX: Get, getY: Get, nodeSize?: number, ArrayType?: ArrayType): KDBush; -} - -declare const kdbush: KDBushStatic; -declare namespace kdbush {} export = kdbush; diff --git a/types/kdbush/kdbush-tests.ts b/types/kdbush/kdbush-tests.ts index c9fd8ae11f..fb7e268290 100644 --- a/types/kdbush/kdbush-tests.ts +++ b/types/kdbush/kdbush-tests.ts @@ -1,4 +1,5 @@ import * as kdbush from 'kdbush'; +import {KDBush} from 'kdbush'; // API const points = [[110, 60], [130, 40]]; @@ -20,7 +21,7 @@ index.within(10, 10, 5).map(id => points[id]); // custom points (object) const xy = [{x: 110, y: 60}, {x: 130, y: 40}]; -const index2 = kdbush(xy, p => p.x, p => p.y); +const index2: KDBush<{x: number, y: number}> = kdbush(xy, p => p.x, p => p.y); index2.points[0].x; index2.points[0].y; index2.points.map(p => [p.x, p.y]); diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index fa84243b76..2e301af850 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -2,9 +2,8 @@ // Project: https://github.com/tgriesser/knex // Definitions by: Qubo , Baronfel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 -/// /// import events = require("events"); diff --git a/types/knockout.validation/index.d.ts b/types/knockout.validation/index.d.ts index ad3a042aa7..480a2607e7 100644 --- a/types/knockout.validation/index.d.ts +++ b/types/knockout.validation/index.d.ts @@ -158,6 +158,7 @@ interface KnockoutValidationRuleDefinitions { required: KnockoutValidationRuleDefinition; step: KnockoutValidationRuleDefinition; unique: KnockoutValidationRuleDefinition; + [ruleName: string]: KnockoutValidationRuleDefinition; } interface KnockoutValidationRule { diff --git a/types/koa-morgan/index.d.ts b/types/koa-morgan/index.d.ts index 494f4d3f19..f9cbc249c0 100644 --- a/types/koa-morgan/index.d.ts +++ b/types/koa-morgan/index.d.ts @@ -4,19 +4,20 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 +import { IncomingMessage, ServerResponse } from 'http'; import * as Koa from 'koa'; import * as originalMorgan from 'morgan'; declare namespace morgan { interface FormatFn { - (tokens: TokenIndexer, req: Koa.Request, res: Koa.Response): string; + (tokens: TokenIndexer, req: IncomingMessage, res: ServerResponse): string; } interface TokenCallbackFn { - (req: Koa.Request, res: Koa.Response, arg?: string | number | boolean): string; + (req: IncomingMessage, res: ServerResponse, arg?: string | number | boolean): string; } - interface TokenIndexer extends originalMorgan.TokenIndexer {} + type TokenIndexer = originalMorgan.TokenIndexer; /** * Public interface of morgan logger @@ -121,7 +122,7 @@ declare namespace morgan { */ function compile(format: string): FormatFn; - interface StreamOptions extends originalMorgan.StreamOptions {} + type StreamOptions = originalMorgan.StreamOptions; /*** * Morgan accepts these properties in the options object. @@ -141,7 +142,7 @@ declare namespace morgan { /*** * Function to determine if logging is skipped, defaults to false. This function will be called as skip(req, res). */ - skip?: (req: Koa.Request, res: Koa.Response) => boolean; + skip?: (req: IncomingMessage, res: ServerResponse) => boolean; /*** * Output stream for writing log lines, defaults to process.stdout. @@ -206,6 +207,6 @@ declare function morgan(format: 'tiny', options?: morgan.Options): Koa.Middlewar * @param format * @param options */ -declare function morgan(custom: (req: Koa.Request, res: Koa.Response) => string): Koa.Middleware; +declare function morgan(custom: (req: IncomingMessage, res: ServerResponse) => string): Koa.Middleware; export = morgan; diff --git a/types/koa-morgan/koa-morgan-tests.ts b/types/koa-morgan/koa-morgan-tests.ts index c52d9dc0a5..86c8c03e05 100644 --- a/types/koa-morgan/koa-morgan-tests.ts +++ b/types/koa-morgan/koa-morgan-tests.ts @@ -1,3 +1,4 @@ +import { IncomingMessage, ServerResponse } from 'http'; import * as Koa from 'koa'; import * as morgan from 'koa-morgan'; @@ -10,6 +11,20 @@ app.use(morgan('short')); app.use(morgan('tiny')); app.use(morgan(':remote-addr :method :url')); +const tokenCallback: morgan.TokenCallbackFn = (req: IncomingMessage, res: ServerResponse): string => { + if (req.headers['request-id']) { + if (Array.isArray(req.headers['request-id'])) { + return (req.headers['request-id'] as string[]).join(';'); + } else { + return req.headers['request-id'] as string; + } + } else { + return '-'; + } +}; + +morgan.token('id', tokenCallback); + const stream: morgan.StreamOptions = { write: (str: string) => { console.log(str); @@ -19,7 +34,7 @@ const stream: morgan.StreamOptions = { app.use(morgan('combined', { buffer: true, immediate: true, - skip: (req: Koa.Request, res: Koa.Response) => res.status < 400, + skip: (req: IncomingMessage, res: ServerResponse) => res.statusCode < 400, stream })); @@ -41,10 +56,10 @@ interface ExtendedFormatFn extends morgan.FormatFn { memoizer?: FormatFnIndexer; } -const developmentExtendedFormatLine: ExtendedFormatFn = (tokens, req: Koa.Request, res: Koa.Response): string => { +const developmentExtendedFormatLine: ExtendedFormatFn = (tokens, req: IncomingMessage, res: ServerResponse): string => { // get the status code if response written - const status = res.status - ? res.status + const status = res.statusCode + ? res.statusCode : undefined; // get status color diff --git a/types/kue/index.d.ts b/types/kue/index.d.ts index afd818c8f2..5e5db964ac 100644 --- a/types/kue/index.d.ts +++ b/types/kue/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for kue 0.11.x // Project: https://github.com/Automattic/kue // Definitions by: Nicholas Penree +// Amiram Korach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -29,7 +30,7 @@ export declare class Queue extends events.EventEmitter { checkActiveJobTtl(ttlOptions: Object): void; watchStuckJobs(ms: number): void; setting(name: string, fn: Function): Queue; - process(type: string, n?: number, fn?: Function): void; + process(type: string, n?: number | ProcessCallback, fn?: ProcessCallback): void; shutdown(timeout: number, type: string, fn: Function): Queue; types(fn: Function): Queue; state(string: string, fn: Function): Queue; @@ -56,17 +57,25 @@ interface Priorities { critical: number; } +export type DoneCallback = (err?: any, result?: any) => void; +export type JobCallback = (err?: any, job?: Job) => void; +export type ProcessCallback = (job: Job, cb: DoneCallback) => void; + export declare class Job extends events.EventEmitter { public id: number; public type: string; public data: any; + public result: any; + // Should always be a number however currently it is a number when creating and a string when loading + // https://github.com/Automattic/kue/issues/1081 + public created_at: string | number; public client: redisClientFactory.RedisClient; private _max_attempts; static priorities: Priorities; static disableSearch: boolean; static jobEvents: boolean; - static get(id: number, fn: Function): void; + static get(id: number, type: string | JobCallback, fn?: JobCallback): void; static remove(id: number, fn?: Function): void; static removeBadJob(id: number): void; static log(id: number, fn: Function): void; @@ -79,6 +88,7 @@ export declare class Job extends events.EventEmitter { log(str: string): Job; set(key: string, val: string, fn?: Function): Job; get(key: string, fn?: Function): Job; + get(key: string, jobType: string, fn?: Function): Job; progress(complete: number, total: number, data?: any): Job; delay(ms: number | Date): Job; removeOnComplete(param: any): Job; diff --git a/types/kue/kue-tests.ts b/types/kue/kue-tests.ts index d69f6eaead..fd929d7aeb 100644 --- a/types/kue/kue-tests.ts +++ b/types/kue/kue-tests.ts @@ -39,6 +39,13 @@ function create() { job.save(); + kue.Job.get(job.id, function (err: any, _job: kue.Job) { + console.log('get job', _job); + }); + kue.Job.get(job.id, 'video conversion', function (err: any, _job: kue.Job) { + console.log('get job', _job); + }); + setTimeout( create, Math.random() * 2000 | 0 ); } @@ -46,25 +53,28 @@ create(); // process video conversion jobs, 1 at a time. -jobs.process('video conversion', 1, function(job: kue.Job, done: Function) { +var processCb = function(job: kue.Job, done: kue.DoneCallback) { var frames: number = job.data.frames; function next(i: number) { // pretend we are doing some work - convertFrame(i, function(err: Error) { + convertFrame(i, function(err: Error, result: any) { if (err) return done(err); // report progress, i/frames complete job.progress(i, frames); - if (i >= frames) done(); + if (i >= frames) done(null, result); else next(i + Math.random() * 10); } ); } next(0); -} ); +} + +jobs.process('video conversion', 1, processCb); +jobs.process('video conversion', processCb); function convertFrame(i: number, fn: Function) { - setTimeout(fn, Math.random() * 50); + setTimeout(() => fn(null, Math.random()), Math.random() * 50); } // one minute @@ -102,4 +112,4 @@ jobs.process('email', 10, function(job: kue.Job, done: Function) { // start the UI kue.app.listen(3000); -console.log('UI started on port 3000'); \ No newline at end of file +console.log('UI started on port 3000'); diff --git a/types/material-ui/index.d.ts b/types/material-ui/index.d.ts index 560b21f2ca..a7b13f2bb4 100644 --- a/types/material-ui/index.d.ts +++ b/types/material-ui/index.d.ts @@ -9,7 +9,7 @@ // Matthias Schlesinger // Jonathon Kelly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 /// /// @@ -109,7 +109,7 @@ declare namespace __MaterialUI { interface ThemeWrapperProps { theme: Styles.MuiTheme; } - export class ThemeWrapper extends React.Component { + export class ThemeWrapper extends React.Component { } export namespace Styles { @@ -470,7 +470,7 @@ declare namespace __MaterialUI { interface MuiThemeProviderProps { muiTheme?: Styles.MuiTheme; } - export class MuiThemeProvider extends React.Component { + export class MuiThemeProvider extends React.Component { } export function getMuiTheme(...muiTheme: MuiTheme[]): MuiTheme; @@ -519,12 +519,12 @@ declare namespace __MaterialUI { titleStyle?: React.CSSProperties; zDepth?: number; } - export class AppBar extends React.Component { + export class AppBar extends React.Component { } interface AppCanvasProps { } - export class AppCanvas extends React.Component { + export class AppCanvas extends React.Component { } namespace propTypes { @@ -584,7 +584,7 @@ declare namespace __MaterialUI { targetOrigin?: propTypes.origin; textFieldStyle?: React.CSSProperties; } - export class AutoComplete extends React.Component, {}> { + export class AutoComplete extends React.Component> { static noFilter: () => boolean; static defaultFilter: (searchText: string, key: string) => boolean; static caseSensitiveFilter: (searchText: string, key: string) => boolean; @@ -606,7 +606,7 @@ declare namespace __MaterialUI { src?: string; style?: React.CSSProperties; } - export class Avatar extends React.Component { + export class Avatar extends React.Component { } interface BadgeProps { @@ -617,7 +617,7 @@ declare namespace __MaterialUI { secondary?: boolean; style?: React.CSSProperties; } - export class Badge extends React.Component { + export class Badge extends React.Component { } interface BeforeAfterWrapperProps { @@ -628,7 +628,7 @@ declare namespace __MaterialUI { elementType?: string; style?: React.CSSProperties; } - export class BeforeAfterWrapper extends React.Component { + export class BeforeAfterWrapper extends React.Component { } // non generally overridden elements of EnhancedButton @@ -662,7 +662,7 @@ declare namespace __MaterialUI { containerElement?: React.ReactNode | string; disabled?: boolean; } - export class EnhancedButton extends React.Component { + export class EnhancedButton extends React.Component { } interface FlatButtonProps extends React.DOMAttributes<{}>, SharedEnhancedButtonProps { @@ -686,7 +686,7 @@ declare namespace __MaterialUI { secondary?: boolean; style?: React.CSSProperties; } - export class FlatButton extends React.Component { + export class FlatButton extends React.Component { } interface RaisedButtonProps extends SharedEnhancedButtonProps { @@ -716,7 +716,7 @@ declare namespace __MaterialUI { secondary?: boolean; style?: React.CSSProperties; } - export class RaisedButton extends React.Component { + export class RaisedButton extends React.Component { } interface FloatingActionButtonProps extends React.HTMLAttributes<{}>, SharedEnhancedButtonProps { @@ -738,7 +738,7 @@ declare namespace __MaterialUI { style?: React.CSSProperties; zDepth?: number; } - export class FloatingActionButton extends React.Component { + export class FloatingActionButton extends React.Component { } interface IconButtonProps extends React.HTMLAttributes<{}>, SharedEnhancedButtonProps { @@ -761,7 +761,7 @@ declare namespace __MaterialUI { tooltipStyles?: React.CSSProperties; touch?: boolean; } - export class IconButton extends React.Component { + export class IconButton extends React.Component { } namespace BottomNavigation { @@ -771,7 +771,7 @@ declare namespace __MaterialUI { style?: React.CSSProperties; } - export class BottomNavigation extends React.Component { } + export class BottomNavigation extends React.Component { } interface BottomNavigationItemProps extends SharedEnhancedButtonProps { className?: string; @@ -779,7 +779,7 @@ declare namespace __MaterialUI { label?: React.ReactNode; } - export class BottomNavigationItem extends React.Component { } + export class BottomNavigationItem extends React.Component { } } namespace Card { @@ -795,7 +795,7 @@ declare namespace __MaterialUI { showExpandableButton?: boolean; style?: React.CSSProperties; } - export class Card extends React.Component { + export class Card extends React.Component { } interface CardActionsProps { @@ -805,7 +805,7 @@ declare namespace __MaterialUI { style?: React.CSSProperties; className?: string; } - export class CardActions extends React.Component { + export class CardActions extends React.Component { } interface CardExpandableProps { @@ -813,7 +813,7 @@ declare namespace __MaterialUI { onExpanding?: (isExpanded: boolean) => void; style?: React.CSSProperties; } - export class CardExpandable extends React.Component { + export class CardExpandable extends React.Component { } interface CardHeaderProps { @@ -834,7 +834,7 @@ declare namespace __MaterialUI { closeIcon?: React.ReactNode; iconStyle?: React.CSSProperties; } - export class CardHeader extends React.Component { + export class CardHeader extends React.Component { } interface CardMediaProps { @@ -847,7 +847,7 @@ declare namespace __MaterialUI { overlayStyle?: React.CSSProperties; style?: React.CSSProperties; } - export class CardMedia extends React.Component { + export class CardMedia extends React.Component { } interface CardTextProps { @@ -857,7 +857,7 @@ declare namespace __MaterialUI { style?: React.CSSProperties; className?: string; } - export class CardText extends React.Component { + export class CardText extends React.Component { } interface CardTitleProps { @@ -872,7 +872,7 @@ declare namespace __MaterialUI { titleColor?: string; titleStyle?: React.CSSProperties; } - export class CardTitle extends React.Component { + export class CardTitle extends React.Component { } } @@ -885,7 +885,7 @@ declare namespace __MaterialUI { onTouchTap?: React.TouchEventHandler; style?: React.CSSProperties; } - export class Chip extends React.Component { + export class Chip extends React.Component { } namespace DatePicker { @@ -941,7 +941,7 @@ declare namespace __MaterialUI { underlineStyle?: React.CSSProperties; utils?: propTypes.utils; } - export class DatePicker extends React.Component { + export class DatePicker extends React.Component { } interface DatePickerDialogProps { @@ -966,7 +966,7 @@ declare namespace __MaterialUI { style?: React.CSSProperties; utils?: propTypes.utils; } - export class DatePickerDialog extends React.Component { + export class DatePickerDialog extends React.Component { public show(): void; public dismiss(): void; } @@ -1004,7 +1004,7 @@ declare namespace __MaterialUI { titleClassName?: string; titleStyle?: React.CSSProperties; } - export class Dialog extends React.Component { + export class Dialog extends React.Component { } interface DividerProps { @@ -1012,7 +1012,7 @@ declare namespace __MaterialUI { inset?: boolean; style?: React.CSSProperties; } - export class Divider extends React.Component { + export class Divider extends React.Component { } interface DrawerProps { @@ -1031,7 +1031,7 @@ declare namespace __MaterialUI { width?: number | string; zDepth?: number; } - export class Drawer extends React.Component { + export class Drawer extends React.Component { } namespace GridList { @@ -1041,7 +1041,7 @@ declare namespace __MaterialUI { padding?: number; style?: React.CSSProperties; } - export class GridList extends React.Component { + export class GridList extends React.Component { } interface GridTileProps { @@ -1057,7 +1057,7 @@ declare namespace __MaterialUI { titlePosition?: "top" | "bottom"; onTouchTap?: TouchTapEventHandler; } - export class GridTile extends React.Component { + export class GridTile extends React.Component { } } @@ -1069,7 +1069,7 @@ declare namespace __MaterialUI { onMouseLeave?: React.MouseEventHandler<{}>; style?: React.CSSProperties; } - export class FontIcon extends React.Component { + export class FontIcon extends React.Component { } interface SvgIconProps extends React.SVGAttributes<{}>, React.Props { @@ -1081,7 +1081,7 @@ declare namespace __MaterialUI { style?: React.CSSProperties; viewBox?: string; } - export class SvgIcon extends React.Component { + export class SvgIcon extends React.Component { } namespace List { @@ -1089,7 +1089,7 @@ declare namespace __MaterialUI { // is the element that get the 'other' properties style?: React.CSSProperties; } - export class List extends React.Component { + export class List extends React.Component { } interface ListItemProps extends EnhancedButtonProps { @@ -1124,7 +1124,7 @@ declare namespace __MaterialUI { secondaryTextLines?: number; // 1 or 2 style?: React.CSSProperties; } - export class ListItem extends React.Component { + export class ListItem extends React.Component { } interface SelectableProps { @@ -1157,7 +1157,7 @@ declare namespace __MaterialUI { valueLink?: ReactLink; width?: string | number; } - export class Menu extends React.Component { + export class Menu extends React.Component { } interface MenuItemProps extends List.ListItemProps { @@ -1179,7 +1179,7 @@ declare namespace __MaterialUI { value?: any; containerElement?: React.ReactNode | string; } - export class MenuItem extends React.Component { + export class MenuItem extends React.Component { } interface IconMenuProps { @@ -1217,7 +1217,7 @@ declare namespace __MaterialUI { valueLink?: ReactLink; width?: string | number; } - export class IconMenu extends React.Component { + export class IconMenu extends React.Component { } interface DropDownMenuProps { @@ -1239,7 +1239,7 @@ declare namespace __MaterialUI { underlineStyle?: React.CSSProperties; value?: any; } - export class DropDownMenu extends React.Component { + export class DropDownMenu extends React.Component { } } @@ -1250,7 +1250,7 @@ declare namespace __MaterialUI { onClick?: React.MouseEventHandler<{}>; onTouchTap?: TouchTapEventHandler; } - export class Overlay extends React.Component { + export class Overlay extends React.Component { } interface PaperProps extends React.HTMLAttributes<{}>, React.Props { @@ -1260,7 +1260,7 @@ declare namespace __MaterialUI { transitionEnabled?: boolean; zDepth?: number; } - export class Paper extends React.Component { + export class Paper extends React.Component { } namespace Popover { @@ -1284,7 +1284,7 @@ declare namespace __MaterialUI { useLayerForClickAway?: boolean; zDepth?: number; } - export class Popover extends React.Component { + export class Popover extends React.Component { } interface PopoverAnimationVerticalProps extends PopoverAnimationProps { @@ -1292,7 +1292,7 @@ declare namespace __MaterialUI { targetOrigin?: propTypes.origin; zDepth?: number; } - export class PopoverAnimationVertical extends React.Component { + export class PopoverAnimationVertical extends React.Component { } interface PopoverAnimationDefaultProps extends PopoverAnimationProps { @@ -1300,7 +1300,7 @@ declare namespace __MaterialUI { targetOrigin?: propTypes.origin; zDepth?: number; } - export class PopoverAnimationDefault extends React.Component { + export class PopoverAnimationDefault extends React.Component { } } @@ -1315,7 +1315,7 @@ declare namespace __MaterialUI { thickness?: number; value?: number; } - export class CircularProgress extends React.Component { + export class CircularProgress extends React.Component { } interface LinearProgressProps { @@ -1326,7 +1326,7 @@ declare namespace __MaterialUI { style?: React.CSSProperties; value?: number; } - export class LinearProgress extends React.Component { + export class LinearProgress extends React.Component { } interface RefreshIndicatorProps { @@ -1339,7 +1339,7 @@ declare namespace __MaterialUI { style?: React.CSSProperties; top: number; } - export class RefreshIndicator extends React.Component { + export class RefreshIndicator extends React.Component { } interface SelectFieldProps { @@ -1378,7 +1378,7 @@ declare namespace __MaterialUI { selectedMenuItemStyle?: React.CSSProperties; openImmediately?: boolean; } - export class SelectField extends React.Component { + export class SelectField extends React.Component { } interface SliderProps { @@ -1402,7 +1402,7 @@ declare namespace __MaterialUI { style?: React.CSSProperties; value?: number; } - export class Slider extends React.Component { + export class Slider extends React.Component { } namespace Switches { @@ -1445,7 +1445,7 @@ declare namespace __MaterialUI { trackStyle?: React.CSSProperties; value?: string; } - export class EnhancedSwitch extends React.Component { + export class EnhancedSwitch extends React.Component { getValue(): string; isKeyboardFocused(): boolean; isSwitched(): boolean; @@ -1466,7 +1466,7 @@ declare namespace __MaterialUI { uncheckedIcon?: React.ReactElement<{ style?: React.CSSProperties }>; // Normally an SvgIcon valueLink?: ReactLink; } - export class Checkbox extends React.Component { + export class Checkbox extends React.Component { /** @deprecated Use checked property instead */ isChecked(): void; @@ -1486,7 +1486,7 @@ declare namespace __MaterialUI { uncheckedIcon?: React.ReactElement<{ style?: React.CSSProperties }>; // Normally an SvgIcon value?: any; } - export class RadioButton extends React.Component { + export class RadioButton extends React.Component { isChecked(): boolean; getValue(): string; @@ -1501,7 +1501,7 @@ declare namespace __MaterialUI { style?: React.CSSProperties; valueSelected?: any; } - export class RadioButtonGroup extends React.Component { + export class RadioButtonGroup extends React.Component { clearValue(): void; getSelectedValue(): string; @@ -1529,7 +1529,7 @@ declare namespace __MaterialUI { trackStyle?: React.CSSProperties; valueLink?: ReactLink; } - export class Toggle extends React.Component { + export class Toggle extends React.Component { isToggled(): boolean; setToggled(newToggledValue: boolean): void; @@ -1548,7 +1548,7 @@ declare namespace __MaterialUI { open: boolean; style?: React.CSSProperties; } - export class Snackbar extends React.Component { + export class Snackbar extends React.Component { } namespace Stepper { @@ -1558,7 +1558,7 @@ declare namespace __MaterialUI { disabled?: boolean; style?: React.CSSProperties; } - export class Step extends React.Component { + export class Step extends React.Component { } interface StepButtonProps extends SharedEnhancedButtonProps { @@ -1571,7 +1571,7 @@ declare namespace __MaterialUI { onTouchStart?: React.TouchEventHandler<{}>; style?: React.CSSProperties; } - export class StepButton extends React.Component { + export class StepButton extends React.Component { } interface StepContentProps { @@ -1579,7 +1579,7 @@ declare namespace __MaterialUI { last?: boolean; style?: React.CSSProperties; } - export class StepContent extends React.Component { + export class StepContent extends React.Component { } interface StepLabelProps { @@ -1590,7 +1590,7 @@ declare namespace __MaterialUI { iconContainerStyle?: React.CSSProperties; style?: React.CSSProperties; } - export class StepLabel extends React.Component { + export class StepLabel extends React.Component { } interface SnackbarProps extends React.Props { @@ -1616,7 +1616,7 @@ declare namespace __MaterialUI { orientation?: "horizontal" | "vertical"; style?: React.CSSProperties; } - export class Stepper extends React.Component { + export class Stepper extends React.Component { } } @@ -1624,7 +1624,7 @@ declare namespace __MaterialUI { inset?: boolean; style?: React.CSSProperties; } - export class Subheader extends React.Component { + export class Subheader extends React.Component { } namespace Table { @@ -1648,7 +1648,7 @@ declare namespace __MaterialUI { style?: React.CSSProperties; wrapperStyle?: React.CSSProperties; } - export class Table extends React.Component { + export class Table extends React.Component { } interface TableRowProps { @@ -1675,7 +1675,7 @@ declare namespace __MaterialUI { striped?: boolean; style?: React.CSSProperties; } - export class TableRow extends React.Component { + export class TableRow extends React.Component { } interface TableRowColumnProps { @@ -1695,7 +1695,7 @@ declare namespace __MaterialUI { // useful attributes passed to

colSpan?: number; } - export class TableRowColumn extends React.Component { + export class TableRowColumn extends React.Component { } interface TableHeaderProps { @@ -1709,7 +1709,7 @@ declare namespace __MaterialUI { selectAllSelected?: boolean; style?: React.CSSProperties; } - export class TableHeader extends React.Component { + export class TableHeader extends React.Component { } interface TableHeaderColumnProps { @@ -1725,7 +1725,7 @@ declare namespace __MaterialUI { // useful attributes passed to colSpan?: number; } - export class TableHeaderColumn extends React.Component { + export class TableHeaderColumn extends React.Component { } interface TableBodyProps { @@ -1755,7 +1755,7 @@ declare namespace __MaterialUI { stripedRows?: boolean; style?: React.CSSProperties; } - export class TableBody extends React.Component { + export class TableBody extends React.Component { } interface TableFooterProps { @@ -1764,7 +1764,7 @@ declare namespace __MaterialUI { className?: string; style?: React.CSSProperties; } - export class TableFooter extends React.Component { + export class TableFooter extends React.Component { } } @@ -1782,7 +1782,7 @@ declare namespace __MaterialUI { tabTemplateStyle?: React.CSSProperties; value?: any; } - export class Tabs extends React.Component { + export class Tabs extends React.Component { } interface TabProps extends SharedEnhancedButtonProps { @@ -1841,7 +1841,7 @@ declare namespace __MaterialUI { step?: number; autoComplete?: string; } - export class TextField extends React.Component { + export class TextField extends React.Component { blur(): void; focus(): void; @@ -1862,6 +1862,7 @@ declare namespace __MaterialUI { dialogStyle?: React.CSSProperties; disabled?: boolean; format?: "ampm" | "24hr"; + minutesStep?: number; okLabel?: React.ReactNode; onChange?: (e: any, time: Date) => void; onDismiss?: () => void; @@ -1900,7 +1901,7 @@ declare namespace __MaterialUI { underlineShow?: boolean; underlineStyle?: React.CSSProperties; } - export class TimePicker extends React.Component { + export class TimePicker extends React.Component { focus(): void; openDialog(): void; @@ -1912,7 +1913,7 @@ declare namespace __MaterialUI { noGutter?: boolean; style?: React.CSSProperties; } - export class Toolbar extends React.Component { + export class Toolbar extends React.Component { } interface ToolbarGroupProps { @@ -1922,14 +1923,14 @@ declare namespace __MaterialUI { lastChild?: boolean; style?: React.CSSProperties; } - export class ToolbarGroup extends React.Component { + export class ToolbarGroup extends React.Component { } interface ToolbarSeparatorProps { className?: string; style?: React.CSSProperties; } - export class ToolbarSeparator extends React.Component { + export class ToolbarSeparator extends React.Component { } interface ToolbarTitleProps extends React.HTMLAttributes<{}>, React.Props { @@ -1937,7 +1938,7 @@ declare namespace __MaterialUI { style?: React.CSSProperties; text?: string; } - export class ToolbarTitle extends React.Component { + export class ToolbarTitle extends React.Component { } } @@ -8586,14 +8587,14 @@ declare module "material-ui/svg-icons" { declare module 'material-ui/internal/AppCanvas' { interface AppCanvasProps extends React.Props { } - class AppCanvas extends React.Component { } + class AppCanvas extends React.Component { } export default AppCanvas; } declare module 'material-ui/internal/AutoLockScrolling' { interface AutoLockScrollingProps extends React.Props { lock: boolean; } - class AutoLockScrolling extends React.Component { } + class AutoLockScrolling extends React.Component { } export default AutoLockScrolling; } declare module 'material-ui/internal/BeforeAfterWrapper' { @@ -8605,7 +8606,7 @@ declare module 'material-ui/internal/BeforeAfterWrapper' { elementType?: string, style?: React.CSSProperties, } - class BeforeAfterWrapper extends React.Component { } + class BeforeAfterWrapper extends React.Component { } export default BeforeAfterWrapper; } declare module 'material-ui/internal/CircleRipple' { @@ -8615,33 +8616,33 @@ declare module 'material-ui/internal/CircleRipple' { opacity?: number; style?: React.CSSProperties; } - class CircleRipple extends React.Component { } + class CircleRipple extends React.Component { } export default CircleRipple; } declare module 'material-ui/internal/ClearFix' { interface ClearFixProps extends React.Props { style?: React.CSSProperties; } - class ClearFix extends React.Component { } + class ClearFix extends React.Component { } export default ClearFix; } declare module 'material-ui/internal/ClickAwayListener' { interface ClickAwayListenerProps extends React.Props { onClickAway?: any, } - class ClickAwayListener extends React.Component { } + class ClickAwayListener extends React.Component { } export default ClickAwayListener; } declare module 'material-ui/internal/EnhancedButton' { interface EnhancedButtonProps extends __MaterialUI.SharedEnhancedButtonProps { } - class EnhancedButton extends React.Component { } + class EnhancedButton extends React.Component { } export default EnhancedButton; } declare module 'material-ui/internal/EnhancedSwitch' { interface EnhancedSwitchProps extends __MaterialUI.Switches.CommonEnhancedSwitchProps { } - class EnhancedSwitch extends React.Component { } + class EnhancedSwitch extends React.Component { } export default EnhancedSwitch; } declare module 'material-ui/internal/ExpandTransition' { @@ -8653,7 +8654,7 @@ declare module 'material-ui/internal/ExpandTransition' { transitionDelay?: number; transitionDuration?: number; } - class ExpandTransition extends React.Component { } + class ExpandTransition extends React.Component { } export default ExpandTransition; } declare module 'material-ui/internal/ExpandTransitionChild' { @@ -8663,7 +8664,7 @@ declare module 'material-ui/internal/ExpandTransitionChild' { transitionDelay?: number; transitionDuration?: number; } - class ExpandTransitionChild extends React.Component { } + class ExpandTransitionChild extends React.Component { } export default ExpandTransitionChild; } declare module 'material-ui/internal/FocusRipple' { @@ -8674,7 +8675,7 @@ declare module 'material-ui/internal/FocusRipple' { show?: boolean, style?: React.CSSProperties } - class FocusRipple extends React.Component { } + class FocusRipple extends React.Component { } export default FocusRipple; } declare module 'material-ui/internal/Overlay' { @@ -8686,7 +8687,7 @@ declare module 'material-ui/internal/Overlay' { onClick?: React.MouseEventHandler<{}>; onTouchTap?: __MaterialUI.TouchTapEventHandler; } - class Overlay extends React.Component { } + class Overlay extends React.Component { } export default Overlay; } declare module 'material-ui/internal/RenderToLayer' { @@ -8696,7 +8697,7 @@ declare module 'material-ui/internal/RenderToLayer' { render: Function; useLayerForClickAway?: boolean; } - class RenderToLayer extends React.Component { } + class RenderToLayer extends React.Component { } export default RenderToLayer; } declare module 'material-ui/internal/ScaleIn' { @@ -8706,7 +8707,7 @@ declare module 'material-ui/internal/ScaleIn' { maxScale?: number; minScale?: number; } - class ScaleIn extends React.Component { } + class ScaleIn extends React.Component { } export default ScaleIn; } declare module 'material-ui/internal/ScaleInChild' { @@ -8716,7 +8717,7 @@ declare module 'material-ui/internal/ScaleInChild' { minScale?: number; style?: React.CSSProperties; } - class ScaleInChild extends React.Component { } + class ScaleInChild extends React.Component { } export default ScaleInChild; } declare module 'material-ui/internal/SlideIn' { @@ -8726,7 +8727,7 @@ declare module 'material-ui/internal/SlideIn' { enterDelay?: number; style?: React.CSSProperties; } - class SlideIn extends React.Component { } + class SlideIn extends React.Component { } export default SlideIn; } declare module 'material-ui/internal/SlideInChild' { @@ -8736,7 +8737,7 @@ declare module 'material-ui/internal/SlideInChild' { getLeaveDirection: Function; style?: React.CSSProperties; } - class SlideInChild extends React.Component { } + class SlideInChild extends React.Component { } export default SlideInChild; } declare module 'material-ui/internal/Tooltip' { @@ -8749,7 +8750,7 @@ declare module 'material-ui/internal/Tooltip' { touch?: boolean; verticalPosition?: __MaterialUI.propTypes.vertical; } - class Tooltip extends React.Component { } + class Tooltip extends React.Component { } export default Tooltip; } declare module 'material-ui/internal/TouchRipple' { @@ -8760,6 +8761,6 @@ declare module 'material-ui/internal/TouchRipple' { opacity?: number; style?: React.CSSProperties } - class TouchRipple extends React.Component { } + class TouchRipple extends React.Component { } export default TouchRipple; } diff --git a/types/material-ui/material-ui-tests.tsx b/types/material-ui/material-ui-tests.tsx index 9a0eddd0b9..506d70bce8 100644 --- a/types/material-ui/material-ui-tests.tsx +++ b/types/material-ui/material-ui-tests.tsx @@ -305,7 +305,7 @@ const lightBaseTheme = { const lightMuiTheme = getMuiTheme(lightBaseTheme); -class DeepDownTheTree extends React.Component<{} & {muiTheme: MuiTheme}, {}> { +class DeepDownTheTree extends React.Component<{} & {muiTheme: MuiTheme}> { static propTypes: React.ValidationMap = { muiTheme: React.PropTypes.object.isRequired, }; @@ -329,7 +329,7 @@ const MuiThemeableFunction = muiThemeable(), Pro }); @muiThemeable() -class MuiThemeableClass extends React.Component<{label: string} & {muiTheme?: MuiTheme}, {}> { +class MuiThemeableClass extends React.Component<{label: string} & {muiTheme?: MuiTheme}> { render() { return ( @@ -1075,7 +1075,7 @@ const ChipExampleSimple = () => ( ); -class ChipExampleComplex extends React.Component<{}, {}> { +class ChipExampleComplex extends React.Component { handleRequestDelete = () => { alert('You clicked the delete button.'); } diff --git a/types/methods/index.d.ts b/types/methods/index.d.ts new file mode 100644 index 0000000000..eb59911c82 --- /dev/null +++ b/types/methods/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for methods 1.1 +// Project: https://github.com/jshttp/methods +// Definitions by: Carlos Precioso +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare const methods: string[]; +export = methods; diff --git a/types/methods/methods-tests.ts b/types/methods/methods-tests.ts new file mode 100644 index 0000000000..69fab6bd2e --- /dev/null +++ b/types/methods/methods-tests.ts @@ -0,0 +1,5 @@ +import * as methods from "methods"; + +methods + .slice(0) + .map(method => method.toUpperCase()); diff --git a/types/methods/tsconfig.json b/types/methods/tsconfig.json new file mode 100644 index 0000000000..720595fa80 --- /dev/null +++ b/types/methods/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "methods-tests.ts" + ] +} diff --git a/types/methods/tslint.json b/types/methods/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/methods/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mime/index.d.ts b/types/mime/index.d.ts index 71b4677ac6..7debcca6f3 100644 --- a/types/mime/index.d.ts +++ b/types/mime/index.d.ts @@ -7,7 +7,7 @@ export as namespace mime; -export function lookup(path: string, fallback: string): string; +export function lookup(path: string, fallback?: string): string; export function extension(mime: string): string; export function load(filepath: string): void; export function define(mimes: { [key: string]: any }): void; diff --git a/types/moment-range/index.d.ts b/types/moment-range/index.d.ts index d6c3bde7b2..eb9bb30910 100644 --- a/types/moment-range/index.d.ts +++ b/types/moment-range/index.d.ts @@ -1,104 +1,67 @@ // Type definitions for Moment-range.js 3.0 // Project: https://github.com/gf3/moment-range -// Definitions by: Bart van den Burg , Wilgert Velinga , Juan Francisco Adame +// Definitions by: Bart van den Burg +// Wilgert Velinga +// Juan Francisco Adame +// MartynasZilinskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as moment from 'moment'; -export = moment; +export class DateRange { + start: moment.Moment; + end: moment.Moment; -declare module 'moment' { - class DateRange implements Range { - start: Moment; - end: Moment; + constructor(range: string | Date[] | moment.Moment[]); + constructor(start: Date | moment.Moment, end: Date | moment.Moment); - constructor(range: string | Date[] | Moment[]); - constructor(start: Date | Moment, end: Date | Moment); + contains(other: DateRange | moment.Moment | Date, options?: { exclusive?: boolean }): boolean; - contains(other: DateRange | Moment | Date, options?: { exclusive?: boolean }): boolean; + overlaps(range: DateRange, options?: { adjacent?: boolean }): boolean; - overlaps(range: DateRange, options?: { adjacent?: boolean }): boolean; + intersect(other: DateRange): DateRange; - intersect(other: DateRange): DateRange; + add(other: DateRange): DateRange; - add(other: DateRange): DateRange; + subtract(other: DateRange): DateRange[]; - subtract(other: DateRange): DateRange[]; + by(interval: moment.unitOfTime.Diff, options?: { exclusive?: boolean, step?: number }): Iterable; - by(interval: unitOfTime.Diff, options?: { exclusive?: boolean, step?: number }): Iterable; + byRange(interval: DateRange, options?: { exclusive?: boolean, step?: number }): Iterable; - byRange(interval: DateRange, options?: { exclusive?: boolean, step?: number }): Iterable; + isSame(other: DateRange): boolean; - isSame(other: DateRange): boolean; + diff(unit?: moment.unitOfTime.Diff, rounded?: boolean): number; - diff(unit?: unitOfTime.Diff, rounded?: boolean): number; + toDate(): Date[]; - toDate(): Date[]; + toString(): string; - toString(): string; + valueOf(): number; - valueOf(): number; + center(): moment.Moment; - center(): Moment; + clone(): DateRange; - clone(): DateRange; + isEqual(other: DateRange): boolean; - isEqual(other: DateRange): boolean; + adjacent(other: DateRange): boolean; - adjacent(other: DateRange): boolean; + duration(unit?: moment.unitOfTime.Diff, precise?: boolean): number; - duration(unit?: unitOfTime.Diff, precise?: boolean): number; + reverseBy(interval: moment.unitOfTime.Diff, options?: { exclusive?: boolean, step?: number }): Iterable; - reverseBy(interval: unitOfTime.Diff, options?: { exclusive?: boolean, step?: number }): Iterable; - - reverseByRange(interval: DateRange, options?: { exclusive?: boolean, step?: number }): Iterable; - } - - interface Range { - start: Moment; - end: Moment; - - contains(other: DateRange | Moment | Date, options?: { exclusive?: boolean }): boolean; - - overlaps(range: DateRange, options?: { adjacent?: boolean }): boolean; - - intersect(other: DateRange): DateRange; - - add(other: DateRange): DateRange; - - subtract(other: DateRange): DateRange[]; - - by(interval: unitOfTime.Diff, options?: { exclusive?: boolean, step?: number }): Iterable; - - byRange(interval: DateRange, options?: { exclusive?: boolean, step?: number }): Iterable; - - isSame(other: DateRange): boolean; - - diff(unit?: unitOfTime.Diff, rounded?: boolean): number; - - toDate(): Date[]; - - toString(): string; - - valueOf(): number; - - center(): Moment; - - clone(): DateRange; - - isEqual(other: DateRange): boolean; - - adjacent(other: DateRange): boolean; - - duration(unit?: unitOfTime.Diff, precise?: boolean): number; - - reverseBy(interval: unitOfTime.Diff, options?: { exclusive?: boolean, step?: number }): Iterable; - - reverseByRange(interval: DateRange, options?: { exclusive?: boolean, step?: number }): Iterable; - } - - function extendMoment(moment: any): any; - - function range(range: string | Date[] | Moment[]): Range; - function range(start: Date | Moment, end: Date | Moment): Range; + reverseByRange(interval: DateRange, options?: { exclusive?: boolean, step?: number }): Iterable; } + +export interface MomentRangeMethods { + range(range: string | Date[] | moment.Moment[]): DateRange; + range(start: Date | moment.Moment, end: Date | moment.Moment): DateRange; + within(range: DateRange): boolean; +} + +export interface MomentRangeExtends extends MomentRangeMethods { + (...args: any[]): MomentRangeMethods & moment.Moment; +} + +export function extendMoment(momentInstance: moment.Moment | typeof moment): MomentRangeExtends & moment.Moment; diff --git a/types/moment-range/moment-range-tests.ts b/types/moment-range/moment-range-tests.ts index 7aa63c593f..6043d3b203 100644 --- a/types/moment-range/moment-range-tests.ts +++ b/types/moment-range/moment-range-tests.ts @@ -1,7 +1,14 @@ -import * as moment from 'moment'; +import * as moment from "moment"; import * as momentRange from "moment-range"; const range: momentRange.DateRange = new momentRange.DateRange(new Date(2012, 0, 15), new Date(2012, 4, 23)); + +const extendedMoment = momentRange.extendMoment(moment); + +// Moment methods test +extendedMoment.add(); +extendedMoment().add(); + const range2: momentRange.DateRange = new momentRange.DateRange(moment("2011-04-15", "YYYY-MM-DD"), moment("2011-11-27", "YYYY-MM-DD")); const range3: momentRange.DateRange = new momentRange.DateRange([moment("2011-04-15", "YYYY-MM-DD"), moment("2011-11-27", "YYYY-MM-DD")]); const range4: momentRange.DateRange = new momentRange.DateRange("2015-01-17T09:50:04+00:00/2015-04-17T08:29:55+00:00"); @@ -11,20 +18,20 @@ const date: moment.Moment = moment('2012-05-15'); const res1: boolean = range.adjacent(range2); const it0: Iterable = range.by('days'); -const it1: Iterable = range.by('months', {exclusive: true}); -const it2: Iterable = range.by('years', {exclusive: false, step: 2}); +const it1: Iterable = range.by('months', { exclusive: true }); +const it2: Iterable = range.by('years', { exclusive: false, step: 2 }); const it3: Iterable = range.byRange(range); -const it4: Iterable = range.byRange(range, {exclusive: true}); -const it5: Iterable = range.byRange(range, {exclusive: false, step: 2}); +const it4: Iterable = range.byRange(range, { exclusive: true }); +const it5: Iterable = range.byRange(range, { exclusive: false, step: 2 }); const res2: moment.Moment = range.center(); const res3: momentRange.DateRange = range.clone(); const res4: boolean = range.contains(range); -const res5: boolean = range.contains(range, {exclusive: true}); -const res6: boolean = range.contains(range, {exclusive: false}); +const res5: boolean = range.contains(range, { exclusive: true }); +const res6: boolean = range.contains(range, { exclusive: false }); const res10: number = range.diff('months', true); const res11: number = range.diff('days'); @@ -41,16 +48,16 @@ const res17: boolean = range.isSame(range2); const res18: boolean = range.isEqual(range2); const res20: boolean = range.overlaps(range2); -const res21: boolean = range.overlaps(range2, {adjacent: true}); -const res22: boolean = range.overlaps(range2, {adjacent: false}); +const res21: boolean = range.overlaps(range2, { adjacent: true }); +const res22: boolean = range.overlaps(range2, { adjacent: false }); const it6: Iterable = range.reverseBy('days'); -const it7: Iterable = range.reverseBy('months', {exclusive: true}); -const it8: Iterable = range.reverseBy('years', {exclusive: false, step: 2}); +const it7: Iterable = range.reverseBy('months', { exclusive: true }); +const it8: Iterable = range.reverseBy('years', { exclusive: false, step: 2 }); const it9: Iterable = range.reverseByRange(range); -const it10: Iterable = range.reverseByRange(range, {exclusive: true}); -const it11: Iterable = range.reverseByRange(range, {exclusive: false, step: 2}); +const it10: Iterable = range.reverseByRange(range, { exclusive: true }); +const it11: Iterable = range.reverseByRange(range, { exclusive: false, step: 2 }); const res23: momentRange.DateRange = range.add(range2); @@ -64,3 +71,7 @@ const res27: number = range.valueOf(); const res28: moment.Moment = range.start; const res29: moment.Moment = range.end; + +const res30: boolean = extendedMoment.within(range); +const res31: boolean = extendedMoment().within(range); +const res32: momentRange.DateRange = extendedMoment().range(moment("2011-04-15", "YYYY-MM-DD"), moment("2011-11-27", "YYYY-MM-DD")); diff --git a/types/mssql/index.d.ts b/types/mssql/index.d.ts index 390f487444..63cbd69dc6 100644 --- a/types/mssql/index.d.ts +++ b/types/mssql/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for mssql 4.0.1 +// Type definitions for mssql 4.0.2 // Project: https://www.npmjs.com/package/mssql // Definitions by: COLSA Corporation , Ben Farr , Vitor Buzinaro , Matt Richardson , Jørgen Elgaard Larsen , Peter Keuter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -57,6 +57,7 @@ export declare var TVP: ISqlTypeFactoryWithTvpType; export declare var UDT: ISqlTypeFactoryWithNoParams; export declare var Geography: ISqlTypeFactoryWithNoParams; export declare var Geometry: ISqlTypeFactoryWithNoParams; +export declare var Variant: ISqlTypeFactoryWithNoParams; export declare var TYPES: { VarChar: ISqlTypeFactoryWithLength; @@ -91,6 +92,7 @@ export declare var TYPES: { UDT: ISqlTypeFactoryWithNoParams; Geography: ISqlTypeFactoryWithNoParams; Geometry: ISqlTypeFactoryWithNoParams; + Variant: ISqlTypeFactoryWithNoParams; }; export declare var MAX: number; @@ -109,7 +111,7 @@ export interface IColumnMetadata { index: number; name: string; length: number; - type: ISqlType; + type: (() => ISqlType) | ISqlType; udt?: any; } } @@ -166,6 +168,7 @@ export interface config { connectionTimeout?: number; requestTimeout?: number; stream?: boolean; + parseJSON?: boolean; options?: IOptions; pool?: IPool; } @@ -191,25 +194,38 @@ export declare class ConnectionError implements Error { public code: string; } -declare class columns { - public add(name: string, type: any, options: any): void; +export interface IColumnOptions { + nullable?: boolean; + primary?: boolean; } +export interface IColumn extends ISqlType { + name: string; + nullable: boolean; + primary: boolean; +} + +declare class columns { + public add(name: string, type: (() => ISqlType) | ISqlType, options?: IColumnOptions): number; +} + +type IRow = (string | number | boolean | Date | Buffer)[]; + declare class rows { - public add(...row: any[]): void; + public add(...row: IRow): number; } export declare class Table { public create: boolean; public columns: columns; public rows: rows; - public constructor(tableName: string); + public constructor(tableName?: string); } interface IRequestParameters { [name: string]: { name: string; - type: any; + type: (() => ISqlType) | ISqlType; io: number; value: any; length: number; @@ -233,8 +249,8 @@ export declare class Request extends events.EventEmitter { public execute(procedure: string): Promise>; public execute(procedure: string, callback: (err?: any, recordsets?: IProcedureResult, returnValue?: any) => void): void; public input(name: string, value: any): Request; - public input(name: string, type: any, value: any): Request; - public output(name: string, type: any, value?: any): Request; + public input(name: string, type: (() => ISqlType) | ISqlType, value: any): Request; + public output(name: string, type: (() => ISqlType) | ISqlType, value?: any): Request; public pipe(stream: NodeJS.WritableStream): NodeJS.WritableStream; public query(command: string): Promise>; public query(command: string): Promise>; @@ -280,8 +296,8 @@ export declare class PreparedStatement extends events.EventEmitter { public parameters: IRequestParameters; public stream: any; public constructor(connection?: ConnectionPool); - public input(name: string, type: ISqlType): PreparedStatement; - public output(name: string, type: ISqlType): PreparedStatement; + public input(name: string, type: (() => ISqlType) | ISqlType): PreparedStatement; + public output(name: string, type: (() => ISqlType) | ISqlType): PreparedStatement; public prepare(statement?: string): Promise; public prepare(statement?: string, callback?: (err?: Error) => void): PreparedStatement; public execute(values: Object): Promise; diff --git a/types/mssql/mssql-tests.ts b/types/mssql/mssql-tests.ts index c5e4535e44..9922364dc1 100644 --- a/types/mssql/mssql-tests.ts +++ b/types/mssql/mssql-tests.ts @@ -1,6 +1,6 @@ -import sql = require('mssql'); +import * as sql from 'mssql'; -interface Entity{ +interface Entity { value: number; } @@ -26,15 +26,14 @@ var connection: sql.ConnectionPool = new sql.ConnectionPool(config, function (er console.warn("Issue with connecting to SQL Server!"); } else { - connection.query`SELECT ${1} as value`.then(res => { }); + connection.query`SELECT ${1} as value`.then(res => { }); var requestQuery = new sql.Request(connection); var getArticlesQuery = "SELECT * FROM TABLE"; requestQuery.query(getArticlesQuery, function (err, result) { if (err) { - console.error('Error happened calling Query: ' + err.name + " " + err.message); - + console.error(`Error happened calling Query: ${err.name} ${err.message}`); } // checking to see if the articles returned as at least one. else if (result.recordset.length > 0) { @@ -45,7 +44,7 @@ var connection: sql.ConnectionPool = new sql.ConnectionPool(config, function (er requestQuery.query(getArticlesQuery, function (err, result) { if (err) { - console.error('Error happened calling Query: ' + err.name + " " + err.message); + console.error(`Error happened calling Query: ${err.name} ${err.message}`); } // checking to see if the articles returned as at least one. @@ -63,7 +62,7 @@ var connection: sql.ConnectionPool = new sql.ConnectionPool(config, function (er requestStoredProcedure.execute('StoredProcedureName', function (err, recordsets, returnValue) { if (err != null) { - console.error('Error happened calling Query: ' + err.name + " " + err.message); + console.error(`Error happened calling Query: ${err.name} ${err.message}`); } else { console.info(returnValue); @@ -72,7 +71,7 @@ var connection: sql.ConnectionPool = new sql.ConnectionPool(config, function (er requestStoredProcedure.execute('StoredProcedureName', function (err, recordsets, returnValue) { if (err != null) { - console.error('Error happened calling Query: ' + err.name + " " + err.message); + console.error(`Error happened calling Query: ${err.name} ${err.message}`); } else { console.info(returnValue); @@ -97,7 +96,7 @@ var connection: sql.ConnectionPool = new sql.ConnectionPool(config, function (er requestStoredProcedure.execute('StoredProcedureName', function (err, recordsets, returnValue) { if (err != null) { - console.error('Error happened calling Query: ' + err.name + " " + err.message); + console.error(`Error happened calling Query: ${err.name} ${err.message}`); } else { console.info(requestStoredProcedureWithOutput.parameters['output'].value); @@ -106,7 +105,7 @@ var connection: sql.ConnectionPool = new sql.ConnectionPool(config, function (er requestStoredProcedure.execute('StoredProcedureName', function (err, recordsets, returnValue) { if (err != null) { - console.error('Error happened calling Query: ' + err.name + " " + err.message); + console.error(`Error happened calling Query: ${err.name} ${err.message}`); } else { console.info(requestStoredProcedureWithOutput.parameters['output'].value); @@ -128,6 +127,25 @@ function test_table() { table.rows.add('name2', 7, 3.14); } +function test_table2() { + var table = new sql.Table('#temp_table2'); + + table.create = true; + + ([ + { name: 'name', type: { typeName: 'VarChar', length: sql.MAX }, nullable: false }, + { name: 'type', type: { typeName: 'Int' }, nullable: false }, + { name: 'type', type: { typeName: 'Decimal', precision: 7, scale: 2 }, nullable: false } + ] as any[]) + .forEach((col: sql.IColumn) => + table.columns.add(col.name, _getSqlType(col.type), { nullable: col.nullable })); + + [['name', 42, 3.50], ['name2', 7, 3.14]].forEach((row: sql.IRow) => table.rows.add(...row)); +} + +function _getSqlType(type: any): sql.ISqlType { + return sql.TYPES[type.typeName](type.length | type.precision, type.scale); +} function test_promise_returns() { // Methods return a promises if the callback is omitted. @@ -150,7 +168,7 @@ function test_promise_returns() { request.batch('create procedure #temporary as select * from table;select 1 as value').then((recordset) => { }); request.bulk(new sql.Table("table_name")).then(() => { }); request.query('SELECT 1').then((recordset) => { }); - request.query('SELECT 1 as value').then(res => { }); + request.query('SELECT 1 as value').then(res => { }); request.execute('procedure_name').then((recordset) => { }); } diff --git a/types/mssql/tsconfig.json b/types/mssql/tsconfig.json index fc4c11febd..0c0bd7a996 100644 --- a/types/mssql/tsconfig.json +++ b/types/mssql/tsconfig.json @@ -6,6 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, + "suppressImplicitAnyIndexErrors": true, "strictNullChecks": false, "baseUrl": "../", "typeRoots": [ @@ -19,4 +20,4 @@ "index.d.ts", "mssql-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/natsort/index.d.ts b/types/natsort/index.d.ts new file mode 100644 index 0000000000..bf448f218d --- /dev/null +++ b/types/natsort/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for natsort 1.0 +// Project: https://github.com/bubkoo/natsort +// Definitions by: Melvin Groenhoff +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function natsort(options?: natsort.Options): (a: any, b: any) => number; + +declare namespace natsort { + interface Options { + desc?: boolean; + insensitive?: boolean; + } +} + +export = natsort; +export as namespace nasort; diff --git a/types/natsort/natsort-tests.ts b/types/natsort/natsort-tests.ts new file mode 100644 index 0000000000..4e9d0c0fcb --- /dev/null +++ b/types/natsort/natsort-tests.ts @@ -0,0 +1,155 @@ +import * as natsort from "natsort"; + +const someArr = [2, 5, 3, 4, 1, 'a', 'B']; + +someArr.sort(natsort()); +someArr.sort(natsort({ desc: true })); +someArr.sort(natsort({ insensitive: true })); + +// sort with object array +const objArr = [ + { val: 'B' }, + { val: 'a' }, + { val: 'D' }, + { val: 'c' } +]; + +const sorter = natsort(); + +objArr.sort((a, b) => { + return sorter(a.val, b.val); +}); + +// simple numerics +['10', 9, 2, '1', '4'].sort(natsort()); +// ['1',2,'4',9,'10'] + +// floats +[ + '10.0401', + 10.022, + 10.042, + '10.021999' +].sort(natsort()); +// [ +// '10.021999', +// 10.022, +// '10.0401', +// 10.042 +// ] + +// float & decimal notation +[ + '10.04f', + '10.039F', + '10.038d', + '10.037D' +].sort(natsort()); +// [ +// '10.037D', +// '10.038d', +// '10.039F', +// '10.04f' +// ] + +// scientific notation +[ + '1.528535047e5', + '1.528535047e7', + '1.528535047e3' +].sort(natsort()); +// [ +// '1.528535047e3', +// '1.528535047e5', +// '1.528535047e7' +// ] + +// ip addresses +[ + '192.168.0.100', + '192.168.0.1', + '192.168.1.1' +].sort(natsort()); +// [ +// '192.168.0.1', +// '192.168.0.100', +// '192.168.1.1' +// ] + +// Filenames +[ + 'car.mov', + '01alpha.sgi', + '001alpha.sgi', + 'my.string_41299.tif' +].sort(natsort()); +// [ +// '001alpha.sgi', +// '01alpha.sgi', +// 'car.mov', +// 'my.string_41299.tif' +// ] + +// dates +[ + '10/12/2008', + '10/11/2008', + '10/11/2007', + '10/12/2007' +].sort(natsort()); +// [ +// '10/11/2007', +// '10/12/2007', +// '10/11/2008', +// '10/12/2008' +// ] + +// money +[ + '$10002.00', + '$10001.02', + '$10001.01' +].sort(natsort()); +// [ +// '$10001.01', +// '$10001.02', +// '$10002.00' +// ] + +// versions +[ + '1.0.2', + '1.0.1', + '1.0.0', + '1.0.9' +].sort(natsort()); +// [ +// '1.0.0', +// '1.0.1', +// '1.0.2', +// '1.0.9' +// ] + +// movie titles +[ + '1 Title - The Big Lebowski', + '1 Title - Gattaca', + '1 Title - Last Picture Show' +].sort(natsort()); +// [ +// '1 Title - Gattaca', +// '1 Title - Last Picture Show', +// '1 Title - The Big Lebowski' +// ] + +// by default - case-sensitive sorting +['a', 'B'].sort(natsort()); +// ['B', 'a'] + +// enable case-insensitive sorting +['a', 'B'].sort(natsort({ insensitive: true })); +// ['a', 'B'] + +// desc +[4, 2, 3, 5, 1].sort(natsort({ desc: true })); +// [1, 2, 3, 4, 5] diff --git a/types/natsort/tsconfig.json b/types/natsort/tsconfig.json new file mode 100644 index 0000000000..8fd932f326 --- /dev/null +++ b/types/natsort/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "natsort-tests.ts" + ] +} diff --git a/types/natsort/tslint.json b/types/natsort/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/natsort/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/navigation-react/index.d.ts b/types/navigation-react/index.d.ts index a4dd084b84..0c85dac138 100644 --- a/types/navigation-react/index.d.ts +++ b/types/navigation-react/index.d.ts @@ -2,7 +2,7 @@ // Project: http://grahammendick.github.io/navigation/ // Definitions by: Graham Mendick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 import { StateNavigator } from 'navigation'; import { Component, HTMLProps } from 'react'; @@ -58,7 +58,7 @@ export interface RefreshLinkProps extends LinkProps { /** * Hyperlink Component the navigates to the current State */ -export class RefreshLink extends Component { } +export class RefreshLink extends Component { } /** * Defines the Navigation Link Props contract @@ -73,7 +73,7 @@ export interface NavigationLinkProps extends RefreshLinkProps { /** * Hyperlink Component the navigates to a State */ -export class NavigationLink extends Component { } +export class NavigationLink extends Component { } /** * Defines the Navigation Back Link Props contract @@ -88,4 +88,4 @@ export interface NavigationBackLinkProps extends RefreshLinkProps { /** * Hyperlink Component the navigates back along the crumb trail */ -export class NavigationBackLink extends Component { } +export class NavigationBackLink extends Component { } diff --git a/types/ng-stomp/index.d.ts b/types/ng-stomp/index.d.ts index 3a91a64844..2a2e9c2496 100644 --- a/types/ng-stomp/index.d.ts +++ b/types/ng-stomp/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/beevelop/ng-stomp // Definitions by: Lukasz Potapczuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/ngstorage/index.d.ts b/types/ngstorage/index.d.ts index 83c740ff0e..ca86f3d1a8 100644 --- a/types/ngstorage/index.d.ts +++ b/types/ngstorage/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/gsklee/ngStorage // Definitions by: Jakub Pistek // Definitions: https://github.com/kubiq/DefinitelyTyped +// TypeScript Version: 2.3 export namespace ngStorage { interface StorageService { diff --git a/types/node-getopt/index.d.ts b/types/node-getopt/index.d.ts index afd0a89adf..cb08791fc3 100644 --- a/types/node-getopt/index.d.ts +++ b/types/node-getopt/index.d.ts @@ -122,7 +122,7 @@ declare class Getopt { * equals new Getopt(options) * @param options */ - static create(options: string[]): Getopt; + static create(options: string[][]): Getopt; } export = Getopt; diff --git a/types/node-getopt/node-getopt-tests.ts b/types/node-getopt/node-getopt-tests.ts index 7427731ca8..2ba3afd01d 100644 --- a/types/node-getopt/node-getopt-tests.ts +++ b/types/node-getopt/node-getopt-tests.ts @@ -34,7 +34,7 @@ function help() { function onedragon() { // examples/onedragon.js - var opt = require('node-getopt').create([ + var opt = Getopt.create([ ['s' , '' , 'short option.'], ['' , 'long' , 'long option.'], ['S' , 'short-with-arg=ARG' , 'option with argument'], @@ -52,7 +52,7 @@ function onedragon() { function online(){ // node-getopt oneline example. - var opt = require('..').create([ + var opt = Getopt.create([ ['s' , '' , 'short option.'], ['' , 'long' , 'long option.'], ['S' , 'short-with-arg=ARG' , 'option with argument'], diff --git a/types/node-mysql-wrapper/index.d.ts b/types/node-mysql-wrapper/index.d.ts index 7785d8a7b4..c887da3368 100644 --- a/types/node-mysql-wrapper/index.d.ts +++ b/types/node-mysql-wrapper/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/nodets/node-mysql-wrapper // Definitions by: Makis Maropoulos // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// @@ -49,20 +50,20 @@ interface IQueryConstructor { declare class Helper { - /** + /** * Callback like forEach * @name valueCallback * @function - * @param {T} the value of the object's key + * @param {T} the value of the object's key * @returnTye {U} * @return {U} */ - + /** * CallbaforEach * @name keyCallback * @function - * @param {string} the name of the object's key + * @param {string} the name of the object's key * @returnTye {U} * @return {U} */ @@ -158,7 +159,7 @@ declare class CriteriaParts implements ICriteriaParts { noDatabaseProperties: string[]; /** - * The converted/exported where clause. + * The converted/exported where clause. */ whereClause: string; @@ -472,7 +473,7 @@ declare class Connection extends EventEmitter { eventTypes: string[]; /** - * Force to fetch ONLY these Database table names {array of string}. + * Force to fetch ONLY these Database table names {array of string}. */ tableNamesToUseOnly: any[]; @@ -495,7 +496,7 @@ declare class Connection extends EventEmitter { * Attach a real connection. * @param {Mysql.IConnection} connection the real connection object. * @returnType {nothing} - * @return {nothing} + * @return {nothing} */ attach(connection: Mysql.IConnection): void; @@ -503,13 +504,13 @@ declare class Connection extends EventEmitter { * Close the entire real connection and remove all event's listeners (if exist). * @param {function} callback If error occurs when closing the connection, this callback has the responsibility to catch it. * @returnType {nothing} - * @return {nothing} + * @return {nothing} */ end(callback?: (error: any) => void): void; /** * Close the entire real connection and remove all event's listeners (if exist). - * the difference from the 'end' is that this method doesn't care about errors so no callback passing here. + * the difference from the 'end' is that this method doesn't care about errors so no callback passing here. */ destroy(): void; @@ -545,7 +546,7 @@ declare class Connection extends EventEmitter { /** * Escape the query column's value and return it. - * @param {string} val the value which will be escaped. + * @param {string} val the value which will be escaped. * @returnType {string} * @return {string} */ @@ -565,7 +566,7 @@ declare class Connection extends EventEmitter { * Adds an event listener/watcher on a table for a 'database event'. * @param {string} tableName the table name which you want to add the event listener. * @param {string or string[]} evtType the event(s) type you want to watch, one of these(string) or an array of them(string[]): ["INSERT", "UPDATE", "REMOVE", "SAVE"]. - * @param {function} callback Callback which has one parameter(typeof any[]) which filled by the rawRows (results after query executed and before parsed to object(s)). + * @param {function} callback Callback which has one parameter(typeof any[]) which filled by the rawRows (results after query executed and before parsed to object(s)). * @returnType {nothing} * @return {nothing} */ @@ -573,7 +574,7 @@ declare class Connection extends EventEmitter { /** * Removes an event listener/watcher from a table for a specific event type. - * @param {string} tableName the table name which you want to remove the event listener. + * @param {string} tableName the table name which you want to remove the event listener. * @param {string} evtType the Event type you want to remove, one of these: "INSERT", "UPDATE", "REMOVE", "SAVE". * @param {function} callbackToRemove the callback that you were used for watch this event type. * @returnType {nothing} @@ -587,13 +588,13 @@ declare class Connection extends EventEmitter { * @param {function} callback the function will be called and fill the one and only parameter when an errors occurs. * @param {any[]} queryArguments (optional) the query arguments you want to pass into query. ['arg1','arg2']... * @returnType {nothing} - * @return {nothing} + * @return {nothing} */ query(queryStr: string, callback: (err: Mysql.IError, results: any) => any, queryArguments?: any[]): void; /** * Returns a MysqlTable object from the database factory. (Note: this method doesn't create anything, just finds and returns the correct table, you don't have to create anything at all. Tables are fetched by the library itself.) - * If you are using typescript you can pass a class (generic) in order to use the auto completion assistance on table's results methods(find,findById,findAll,save,remove,safeRemove). + * If you are using typescript you can pass a class (generic) in order to use the auto completion assistance on table's results methods(find,findById,findAll,save,remove,safeRemove). * @param {string} tableName the table name which you want to get, on the form of: 'anyDatabaseTable' OR 'any_database_table' (possible your real table name into your database). * @returnType {MysqlTable} * @return {MysqlTable} @@ -602,7 +603,7 @@ declare class Connection extends EventEmitter { } declare class Table { - /** Private keywords here are useless but I put them. + /** Private keywords here are useless but I put them. * If the developer wants to see the properties of the Table class, he/she just comes here. */ @@ -630,17 +631,17 @@ declare class Table { primaryKey: string; /** - * The MysqlConnection object which this MysqlTable belongs. + * The MysqlConnection object which this MysqlTable belongs. */ connection: Connection; /** - * The real database name of the table. Autofilled by library. + * The real database name of the table. Autofilled by library. */ name: string; /** - * Set of the query rules that will be applied after the 'where clause' on each select query executed by this table. + * Set of the query rules that will be applied after the 'where clause' on each select query executed by this table. * @return {SelectQueryRules} */ rules: SelectQueryRules; @@ -661,7 +662,7 @@ declare class Table { /** * Adds or turn on an event listener/watcher on a table for a 'database event'. * @param {string} evtType the event type you want to watch, one of these: ["INSERT", "UPDATE", "REMOVE", "SAVE"]. - * @param {function} callback Callback which has one parameter(typeof any[]) which filled by the rawResults (results after query executed and before exports to object(s)). + * @param {function} callback Callback which has one parameter(typeof any[]) which filled by the rawResults (results after query executed and before exports to object(s)). * @returnType {nothing} * @return {nothing} */ @@ -689,7 +690,7 @@ declare class Table { * @param {string} functionName the function name you want to use, this is used when you want to call this function later. * @param {function} theFunction the function with any optional parameters you want to pass along. * @returnType {nothing} - * @return {nothing} + * @return {nothing} */ extend(functionName: string, theFunction: (...args: any[]) => any): void; @@ -726,9 +727,9 @@ declare class Table { getPrimaryKeyValue(jsObject: any): number | string; /** - * + * */ - find(criteriaRawJsObject: any): Promise; // only criteria + find(criteriaRawJsObject: any): Promise; // only criteria find(criteriaRawJsObject: any, callback: ((_results: T[]) => any)): Promise; // criteria and callback find(criteriaRawJsObject: any, callback?: (_results: T[]) => any): Promise; @@ -792,7 +793,7 @@ declare class Database { /** * Close the entire real connection and remove all event's listeners (if exist). - * the difference from the 'end' is that this method doesn't care about errors so no callback passing here. + * the difference from the 'end' is that this method doesn't care about errors so no callback passing here. */ destroy(): void; @@ -800,7 +801,7 @@ declare class Database { * Close the entire real connection and remove all event's listeners (if exist). * @param {function} maybeAcallbackError If error occurs when closing the connection, this callback has the responsibility to catch it. * @returnType {nothing} - * @return {nothing} + * @return {nothing} */ end(maybeAcallbackError: (err: any) => void): void; diff --git a/types/node-static/node-static-tests.ts b/types/node-static/node-static-tests.ts index 4bf2673ab4..471a8fde50 100644 --- a/types/node-static/node-static-tests.ts +++ b/types/node-static/node-static-tests.ts @@ -2,6 +2,6 @@ import {Server, version, mime} from 'node-static'; let server = new Server(__dirname); let pathname = server.resolve('./tsconfig.json'); -let mimetype = mime.lookup(pathname); +let mimetype = mime.lookup(pathname, ''); let versionNum = version.join('.'); console.log(`The node-static server constructed an instance of itself, fetched the mimetype of ${pathname} (${mimetype}), and has a version of ${versionNum}! The package is working.`); diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 022a71313e..131dbc96a1 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -288,10 +288,10 @@ declare namespace NodeJS { } export class EventEmitter { - addListener(event: string | symbol, listener: Function): this; - on(event: string | symbol, listener: Function): this; - once(event: string | symbol, listener: Function): this; - removeListener(event: string | symbol, listener: Function): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; removeAllListeners(event?: string | symbol): this; setMaxListeners(n: number): this; getMaxListeners(): number; @@ -299,8 +299,8 @@ declare namespace NodeJS { emit(event: string | symbol, ...args: any[]): boolean; listenerCount(type: string | symbol): number; // Added in Node 6... - prependListener(event: string | symbol, listener: Function): this; - prependOnceListener(event: string | symbol, listener: Function): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; eventNames(): (string | symbol)[]; } @@ -340,10 +340,10 @@ declare namespace NodeJS { intercept(cb: (data: any) => any): any; dispose(): void; - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; removeAllListeners(event?: string): this; } @@ -382,7 +382,19 @@ declare namespace NodeJS { "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | - "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ"; + "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; + + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListender = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error) => void; + type UnhandledRejectionListener = (reason: any, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: any, sendHandle: any) => void; + type SignalsListener = () => void; + type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; export interface Socket extends ReadWriteStream { isTTY?: true; @@ -467,63 +479,93 @@ declare namespace NodeJS { * 6. uncaughtException * 7. unhandledRejection * 8. warning - * 9. + * 9. message + * 10. + * 11. newListener/removeListener inherited from EventEmitter */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListender): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "newListener", listener: NewListenerListener): this; + addListener(event: "removeListener", listener: RemoveListenerListener): this; - addListener(event: "beforeExit", listener: (code: number) => void): this; - addListener(event: "disconnect", listener: () => void): this; - addListener(event: "exit", listener: (code: number) => void): this; - addListener(event: "rejectionHandled", listener: (promise: Promise) => void): this; - addListener(event: "uncaughtException", listener: (error: Error) => void): this; - addListener(event: "unhandledRejection", listener: (reason: any, promise: Promise) => void): this; - addListener(event: "warning", listener: (warning: Error) => void): this; - addListener(event: Signals, listener: () => void): this; + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "unhandledRejection", reason: any, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: any, sendHandle: any): this; + emit(event: Signals): boolean; + emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; - emit(event: "beforeExit", listener: (code: number) => void): boolean; - emit(event: "disconnect", listener: () => void): boolean; - emit(event: "exit", listener: (code: number) => void): boolean; - emit(event: "rejectionHandled", listener: (promise: Promise) => void): boolean; - emit(event: "uncaughtException", listener: (error: Error) => void): boolean; - emit(event: "unhandledRejection", listener: (reason: any, promise: Promise) => void): boolean; - emit(event: "warning", listener: (warning: Error) => void): boolean; - emit(event: Signals, listener: () => void): boolean; + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListender): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "newListener", listener: NewListenerListener): this; + on(event: "removeListener", listener: RemoveListenerListener): this; - on(event: "beforeExit", listener: (code: number) => void): this; - on(event: "disconnect", listener: () => void): this; - on(event: "exit", listener: (code: number) => void): this; - on(event: "rejectionHandled", listener: (promise: Promise) => void): this; - on(event: "uncaughtException", listener: (error: Error) => void): this; - on(event: "unhandledRejection", listener: (reason: any, promise: Promise) => void): this; - on(event: "warning", listener: (warning: Error) => void): this; - on(event: "message", listener: (message: any, sendHandle: any) => void): this; - on(event: Signals, listener: () => void): this; + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListender): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "newListener", listener: NewListenerListener): this; + once(event: "removeListener", listener: RemoveListenerListener): this; - once(event: "beforeExit", listener: (code: number) => void): this; - once(event: "disconnect", listener: () => void): this; - once(event: "exit", listener: (code: number) => void): this; - once(event: "rejectionHandled", listener: (promise: Promise) => void): this; - once(event: "uncaughtException", listener: (error: Error) => void): this; - once(event: "unhandledRejection", listener: (reason: any, promise: Promise) => void): this; - once(event: "warning", listener: (warning: Error) => void): this; - once(event: Signals, listener: () => void): this; + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListender): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "newListener", listener: NewListenerListener): this; + prependListener(event: "removeListener", listener: RemoveListenerListener): this; - prependListener(event: "beforeExit", listener: (code: number) => void): this; - prependListener(event: "disconnect", listener: () => void): this; - prependListener(event: "exit", listener: (code: number) => void): this; - prependListener(event: "rejectionHandled", listener: (promise: Promise) => void): this; - prependListener(event: "uncaughtException", listener: (error: Error) => void): this; - prependListener(event: "unhandledRejection", listener: (reason: any, promise: Promise) => void): this; - prependListener(event: "warning", listener: (warning: Error) => void): this; - prependListener(event: Signals, listener: () => void): this; + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListender): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "newListener", listener: NewListenerListener): this; + prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; - prependOnceListener(event: "beforeExit", listener: (code: number) => void): this; - prependOnceListener(event: "disconnect", listener: () => void): this; - prependOnceListener(event: "exit", listener: (code: number) => void): this; - prependOnceListener(event: "rejectionHandled", listener: (promise: Promise) => void): this; - prependOnceListener(event: "uncaughtException", listener: (error: Error) => void): this; - prependOnceListener(event: "unhandledRejection", listener: (reason: any, promise: Promise) => void): this; - prependOnceListener(event: "warning", listener: (warning: Error) => void): this; - prependOnceListener(event: Signals, listener: () => void): this; + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListender[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "newListener"): NewListenerListener[]; + listeners(event: "removeListener"): RemoveListenerListener[]; } export interface Global { @@ -696,12 +738,12 @@ declare module "events" { static listenerCount(emitter: EventEmitter, event: string | symbol): number; // deprecated static defaultMaxListeners: number; - addListener(event: string | symbol, listener: Function): this; - on(event: string | symbol, listener: Function): this; - once(event: string | symbol, listener: Function): this; - prependListener(event: string | symbol, listener: Function): this; - prependOnceListener(event: string | symbol, listener: Function): this; - removeListener(event: string | symbol, listener: Function): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; removeAllListeners(event?: string | symbol): this; setMaxListeners(n: number): this; getMaxListeners(): number; @@ -719,13 +761,14 @@ declare module "http" { import * as events from "events"; import * as net from "net"; import * as stream from "stream"; + import { URL } from "url"; export interface RequestOptions { protocol?: string; host?: string; hostname?: string; family?: number; - port?: number; + port?: number | string; localAddress?: string; socketPath?: string; method?: string; @@ -748,6 +791,11 @@ declare module "http" { export interface ServerRequest extends IncomingMessage { connection: net.Socket; } + + export interface ServerResponseHeaders { + [key: string]: number | string | string[]; + } + export interface ServerResponse extends stream.Writable { // Extended base methods write(buffer: Buffer): boolean; @@ -756,20 +804,23 @@ declare module "http" { write(str: string, encoding?: string, cb?: Function): boolean; write(str: string, encoding?: string, fd?: string): boolean; - writeContinue(): void; - writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; - writeHead(statusCode: number, headers?: any): void; - statusCode: number; - statusMessage: string; + addTrailers(headers: ServerResponseHeaders): void; + finished: boolean; + getHeader(name: string): number | string | string[] | undefined; + getHeaderNames(): string[] + getHeaders(): any + hasHeader(name: string): boolean headersSent: boolean; + removeHeader(name: string): void; + sendDate: boolean; setHeader(name: string, value: string | string[]): void; setTimeout(msecs: number, callback: Function): ServerResponse; - sendDate: boolean; - getHeader(name: string): string; - removeHeader(name: string): void; + statusCode: number; + statusMessage: string; write(chunk: any, encoding?: string): any; - addTrailers(headers: any): void; - finished: boolean; + writeContinue(): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: ServerResponseHeaders): void; + writeHead(statusCode: number, headers?: ServerResponseHeaders): void; // Extended base methods end(): void; @@ -885,8 +936,8 @@ declare module "http" { }; export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; export function createClient(port?: number, host?: string): any; - export function request(options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; - export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; + export function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + export function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; export var globalAgent: Agent; } @@ -940,7 +991,7 @@ declare module "cluster" { * 5. message * 6. online */ - addListener(event: string, listener: Function): this; + addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "disconnect", listener: () => void): this; addListener(event: "error", listener: (code: number, signal: string) => void): this; addListener(event: "exit", listener: (code: number, signal: string) => void): this; @@ -948,15 +999,15 @@ declare module "cluster" { addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. addListener(event: "online", listener: () => void): this; - emit(event: string, listener: Function): boolean - emit(event: "disconnect", listener: () => void): boolean - emit(event: "error", listener: (code: number, signal: string) => void): boolean - emit(event: "exit", listener: (code: number, signal: string) => void): boolean - emit(event: "listening", listener: (address: Address) => void): boolean - emit(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): boolean - emit(event: "online", listener: () => void): boolean + emit(event: string, listener: (...args: any[]) => void): boolean + emit(event: "disconnect"): boolean + emit(event: "error", code: number, signal: string): boolean + emit(event: "exit", code: number, signal: string): boolean + emit(event: "listening", address: Address): boolean + emit(event: "message", message: any, handle: net.Socket | net.Server): boolean + emit(event: "online"): boolean - on(event: string, listener: Function): this; + on(event: string, listener: (...args: any[]) => void): this; on(event: "disconnect", listener: () => void): this; on(event: "error", listener: (code: number, signal: string) => void): this; on(event: "exit", listener: (code: number, signal: string) => void): this; @@ -964,7 +1015,7 @@ declare module "cluster" { on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. on(event: "online", listener: () => void): this; - once(event: string, listener: Function): this; + once(event: string, listener: (...args: any[]) => void): this; once(event: "disconnect", listener: () => void): this; once(event: "error", listener: (code: number, signal: string) => void): this; once(event: "exit", listener: (code: number, signal: string) => void): this; @@ -972,7 +1023,7 @@ declare module "cluster" { once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. once(event: "online", listener: () => void): this; - prependListener(event: string, listener: Function): this; + prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "disconnect", listener: () => void): this; prependListener(event: "error", listener: (code: number, signal: string) => void): this; prependListener(event: "exit", listener: (code: number, signal: string) => void): this; @@ -980,7 +1031,7 @@ declare module "cluster" { prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. prependListener(event: "online", listener: () => void): this; - prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "disconnect", listener: () => void): this; prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this; prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; @@ -1013,7 +1064,7 @@ declare module "cluster" { * 6. online * 7. setup */ - addListener(event: string, listener: Function): this; + addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "disconnect", listener: (worker: Worker) => void): this; addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; addListener(event: "fork", listener: (worker: Worker) => void): this; @@ -1022,16 +1073,16 @@ declare module "cluster" { addListener(event: "online", listener: (worker: Worker) => void): this; addListener(event: "setup", listener: (settings: any) => void): this; - emit(event: string, listener: Function): boolean; - emit(event: "disconnect", listener: (worker: Worker) => void): boolean; - emit(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): boolean; - emit(event: "fork", listener: (worker: Worker) => void): boolean; - emit(event: "listening", listener: (worker: Worker, address: Address) => void): boolean; - emit(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): boolean; - emit(event: "online", listener: (worker: Worker) => void): boolean; - emit(event: "setup", listener: (settings: any) => void): boolean; + emit(event: string, listener: (...args: any[]) => void): boolean; + emit(event: "disconnect", worker: Worker): boolean; + emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + emit(event: "fork", worker: Worker): boolean; + emit(event: "listening", worker: Worker, address: Address): boolean; + emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online", worker: Worker): boolean; + emit(event: "setup", settings: any): boolean; - on(event: string, listener: Function): this; + on(event: string, listener: (...args: any[]) => void): this; on(event: "disconnect", listener: (worker: Worker) => void): this; on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; on(event: "fork", listener: (worker: Worker) => void): this; @@ -1040,7 +1091,7 @@ declare module "cluster" { on(event: "online", listener: (worker: Worker) => void): this; on(event: "setup", listener: (settings: any) => void): this; - once(event: string, listener: Function): this; + once(event: string, listener: (...args: any[]) => void): this; once(event: "disconnect", listener: (worker: Worker) => void): this; once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; once(event: "fork", listener: (worker: Worker) => void): this; @@ -1049,7 +1100,7 @@ declare module "cluster" { once(event: "online", listener: (worker: Worker) => void): this; once(event: "setup", listener: (settings: any) => void): this; - prependListener(event: string, listener: Function): this; + prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "disconnect", listener: (worker: Worker) => void): this; prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; prependListener(event: "fork", listener: (worker: Worker) => void): this; @@ -1058,7 +1109,7 @@ declare module "cluster" { prependListener(event: "online", listener: (worker: Worker) => void): this; prependListener(event: "setup", listener: (settings: any) => void): this; - prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; @@ -1091,7 +1142,7 @@ declare module "cluster" { * 6. online * 7. setup */ - export function addListener(event: string, listener: Function): Cluster; + export function addListener(event: string, listener: (...args: any[]) => void): Cluster; export function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; export function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; export function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; @@ -1100,16 +1151,16 @@ declare module "cluster" { export function addListener(event: "online", listener: (worker: Worker) => void): Cluster; export function addListener(event: "setup", listener: (settings: any) => void): Cluster; - export function emit(event: string, listener: Function): boolean; - export function emit(event: "disconnect", listener: (worker: Worker) => void): boolean; - export function emit(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): boolean; - export function emit(event: "fork", listener: (worker: Worker) => void): boolean; - export function emit(event: "listening", listener: (worker: Worker, address: Address) => void): boolean; - export function emit(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): boolean; - export function emit(event: "online", listener: (worker: Worker) => void): boolean; - export function emit(event: "setup", listener: (settings: any) => void): boolean; + export function emit(event: string, listener: (...args: any[]) => void): boolean; + export function emit(event: "disconnect", worker: Worker): boolean; + export function emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + export function emit(event: "fork", worker: Worker): boolean; + export function emit(event: "listening", worker: Worker, address: Address): boolean; + export function emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + export function emit(event: "online", worker: Worker): boolean; + export function emit(event: "setup", settings: any): boolean; - export function on(event: string, listener: Function): Cluster; + export function on(event: string, listener: (...args: any[]) => void): Cluster; export function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; export function on(event: "fork", listener: (worker: Worker) => void): Cluster; @@ -1118,7 +1169,7 @@ declare module "cluster" { export function on(event: "online", listener: (worker: Worker) => void): Cluster; export function on(event: "setup", listener: (settings: any) => void): Cluster; - export function once(event: string, listener: Function): Cluster; + export function once(event: string, listener: (...args: any[]) => void): Cluster; export function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; export function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; export function once(event: "fork", listener: (worker: Worker) => void): Cluster; @@ -1127,14 +1178,14 @@ declare module "cluster" { export function once(event: "online", listener: (worker: Worker) => void): Cluster; export function once(event: "setup", listener: (settings: any) => void): Cluster; - export function removeListener(event: string, listener: Function): Cluster; + export function removeListener(event: string, listener: (...args: any[]) => void): Cluster; export function removeAllListeners(event?: string): Cluster; export function setMaxListeners(n: number): Cluster; export function getMaxListeners(): number; export function listeners(event: string): Function[]; export function listenerCount(type: string): number; - export function prependListener(event: string, listener: Function): Cluster; + export function prependListener(event: string, listener: (...args: any[]) => void): Cluster; export function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; export function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; export function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; @@ -1143,7 +1194,7 @@ declare module "cluster" { export function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; export function prependListener(event: "setup", listener: (settings: any) => void): Cluster; - export function prependOnceListener(event: string, listener: Function): Cluster; + export function prependOnceListener(event: string, listener: (...args: any[]) => void): Cluster; export function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; export function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; export function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; @@ -1442,6 +1493,7 @@ declare module "https" { import * as tls from "tls"; import * as events from "events"; import * as http from "http"; + import { URL } from "url"; export interface ServerOptions { pfx?: any; @@ -1494,8 +1546,8 @@ declare module "https" { }; export interface Server extends tls.Server { } export function createServer(options: ServerOptions, requestListener?: (req: IncomingMessage, res: ServerResponse) => void): Server; - export function request(options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; - export function get(options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + export function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + export function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; export var globalAgent: Agent; } @@ -1541,29 +1593,29 @@ declare module "repl" { * 2. reset **/ - addListener(event: string, listener: Function): this; + addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "exit", listener: () => void): this; - addListener(event: "reset", listener: Function): this; + addListener(event: "reset", listener: (...args: any[]) => void): 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: string, listener: (...args: any[]) => void): this; on(event: "exit", listener: () => void): this; - on(event: "reset", listener: Function): this; + on(event: "reset", listener: (...args: any[]) => void): this; - once(event: string, listener: Function): this; + once(event: string, listener: (...args: any[]) => void): this; once(event: "exit", listener: () => void): this; - once(event: "reset", listener: Function): this; + once(event: "reset", listener: (...args: any[]) => void): this; - prependListener(event: string, listener: Function): this; + prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "exit", listener: () => void): this; - prependListener(event: "reset", listener: Function): this; + prependListener(event: "reset", listener: (...args: any[]) => void): this; - prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "exit", listener: () => void): this; - prependOnceListener(event: "reset", listener: Function): this; + prependOnceListener(event: "reset", listener: (...args: any[]) => void): this; } export function start(options: ReplOptions): REPLServer; @@ -1601,7 +1653,7 @@ declare module "readline" { * 7. SIGTSTP **/ - addListener(event: string, listener: Function): this; + addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "close", listener: () => void): this; addListener(event: "line", listener: (input: any) => void): this; addListener(event: "pause", listener: () => void): this; @@ -1619,7 +1671,7 @@ declare module "readline" { emit(event: "SIGINT"): boolean; emit(event: "SIGTSTP"): boolean; - on(event: string, listener: Function): this; + on(event: string, listener: (...args: any[]) => void): this; on(event: "close", listener: () => void): this; on(event: "line", listener: (input: any) => void): this; on(event: "pause", listener: () => void): this; @@ -1628,7 +1680,7 @@ declare module "readline" { on(event: "SIGINT", listener: () => void): this; on(event: "SIGTSTP", listener: () => void): this; - once(event: string, listener: Function): this; + once(event: string, listener: (...args: any[]) => void): this; once(event: "close", listener: () => void): this; once(event: "line", listener: (input: any) => void): this; once(event: "pause", listener: () => void): this; @@ -1637,7 +1689,7 @@ declare module "readline" { once(event: "SIGINT", listener: () => void): this; once(event: "SIGTSTP", listener: () => void): this; - prependListener(event: string, listener: Function): this; + prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: () => void): this; prependListener(event: "line", listener: (input: any) => void): this; prependListener(event: "pause", listener: () => void): this; @@ -1646,7 +1698,7 @@ declare module "readline" { prependListener(event: "SIGINT", listener: () => void): this; prependListener(event: "SIGTSTP", listener: () => void): this; - prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "line", listener: (input: any) => void): this; prependOnceListener(event: "pause", listener: () => void): this; @@ -1737,7 +1789,7 @@ declare module "child_process" { * 5. message **/ - addListener(event: string, listener: Function): this; + addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "close", listener: (code: number, signal: string) => void): this; addListener(event: "disconnect", listener: () => void): this; addListener(event: "error", listener: (err: Error) => void): this; @@ -1751,28 +1803,28 @@ declare module "child_process" { 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: string, listener: (...args: any[]) => void): this; on(event: "close", listener: (code: number, signal: string) => void): this; on(event: "disconnect", 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: string, listener: (...args: any[]) => void): this; once(event: "close", listener: (code: number, signal: string) => void): this; once(event: "disconnect", 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: string, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: (code: number, signal: string) => void): this; prependListener(event: "disconnect", 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: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: (code: number, signal: string) => void): this; prependOnceListener(event: "disconnect", listener: () => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this; @@ -2204,7 +2256,7 @@ declare module "net" { * 7. lookup * 8. timeout */ - addListener(event: string, listener: Function): this; + addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "close", listener: (had_error: boolean) => void): this; addListener(event: "connect", listener: () => void): this; addListener(event: "data", listener: (data: Buffer) => void): this; @@ -2224,7 +2276,7 @@ declare module "net" { emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; emit(event: "timeout"): boolean; - on(event: string, listener: Function): this; + on(event: string, listener: (...args: any[]) => void): this; on(event: "close", listener: (had_error: boolean) => void): this; on(event: "connect", listener: () => void): this; on(event: "data", listener: (data: Buffer) => void): this; @@ -2234,7 +2286,7 @@ declare module "net" { on(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; on(event: "timeout", listener: () => void): this; - once(event: string, listener: Function): this; + once(event: string, listener: (...args: any[]) => void): this; once(event: "close", listener: (had_error: boolean) => void): this; once(event: "connect", listener: () => void): this; once(event: "data", listener: (data: Buffer) => void): this; @@ -2244,7 +2296,7 @@ declare module "net" { once(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; once(event: "timeout", listener: () => void): this; - prependListener(event: string, listener: Function): this; + prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: (had_error: boolean) => void): this; prependListener(event: "connect", listener: () => void): this; prependListener(event: "data", listener: (data: Buffer) => void): this; @@ -2254,7 +2306,7 @@ declare module "net" { prependListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; prependListener(event: "timeout", listener: () => void): this; - prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: (had_error: boolean) => void): this; prependOnceListener(event: "connect", listener: () => void): this; prependOnceListener(event: "data", listener: (data: Buffer) => void): this; @@ -2303,7 +2355,7 @@ declare module "net" { * 3. error * 4. listening */ - addListener(event: string, listener: Function): this; + addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "close", listener: () => void): this; addListener(event: "connection", listener: (socket: Socket) => void): this; addListener(event: "error", listener: (err: Error) => void): this; @@ -2315,25 +2367,25 @@ declare module "net" { emit(event: "error", err: Error): boolean; emit(event: "listening"): boolean; - on(event: string, listener: Function): this; + on(event: string, listener: (...args: any[]) => void): this; on(event: "close", listener: () => void): this; on(event: "connection", listener: (socket: Socket) => void): this; on(event: "error", listener: (err: Error) => void): this; on(event: "listening", listener: () => void): this; - once(event: string, listener: Function): this; + once(event: string, listener: (...args: any[]) => void): this; once(event: "close", listener: () => void): this; once(event: "connection", listener: (socket: Socket) => void): this; once(event: "error", listener: (err: Error) => void): this; once(event: "listening", listener: () => void): this; - prependListener(event: string, listener: Function): this; + prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: () => void): this; prependListener(event: "connection", listener: (socket: Socket) => void): this; prependListener(event: "error", listener: (err: Error) => void): this; prependListener(event: "listening", listener: () => void): this; - prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this; @@ -2341,7 +2393,7 @@ declare module "net" { } export function createServer(connectionListener?: (socket: Socket) => void): Server; export function createServer(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void): Server; - export function connect(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function connect(options: { port: number, host?: string, localAddress?: string, localPort?: number, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; export function connect(port: number, host?: string, connectionListener?: Function): Socket; export function connect(path: string, connectionListener?: Function): Socket; export function createConnection(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; @@ -2406,7 +2458,7 @@ declare module "dgram" { * 3. listening * 4. message **/ - addListener(event: string, listener: Function): this; + addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "close", listener: () => void): this; addListener(event: "error", listener: (err: Error) => void): this; addListener(event: "listening", listener: () => void): this; @@ -2418,25 +2470,25 @@ declare module "dgram" { emit(event: "listening"): boolean; emit(event: "message", msg: Buffer, rinfo: AddressInfo): boolean; - on(event: string, listener: Function): this; + on(event: string, listener: (...args: any[]) => void): this; on(event: "close", listener: () => void): this; on(event: "error", listener: (err: Error) => void): this; on(event: "listening", listener: () => void): this; on(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - once(event: string, listener: Function): this; + once(event: string, listener: (...args: any[]) => void): this; once(event: "close", listener: () => void): this; once(event: "error", listener: (err: Error) => void): this; once(event: "listening", listener: () => void): this; once(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - prependListener(event: string, listener: Function): this; + prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: () => void): this; prependListener(event: "error", listener: (err: Error) => void): this; prependListener(event: "listening", listener: () => void): this; prependListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this; prependOnceListener(event: "listening", listener: () => void): this; @@ -2480,23 +2532,23 @@ declare module "fs" { * 1. change * 2. error */ - addListener(event: string, listener: Function): this; + addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; addListener(event: "error", listener: (code: number, signal: string) => void): this; - on(event: string, listener: Function): this; + on(event: string, listener: (...args: any[]) => void): this; on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; on(event: "error", listener: (code: number, signal: string) => void): this; - once(event: string, listener: Function): this; + once(event: string, listener: (...args: any[]) => void): this; once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; once(event: "error", listener: (code: number, signal: string) => void): this; - prependListener(event: string, listener: Function): this; + prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; prependListener(event: "error", listener: (code: number, signal: string) => void): this; - prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this; } @@ -2512,23 +2564,23 @@ declare module "fs" { * 1. open * 2. close */ - addListener(event: string, listener: Function): this; + addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "open", listener: (fd: number) => void): this; addListener(event: "close", listener: () => void): this; - on(event: string, listener: Function): this; + on(event: string, listener: (...args: any[]) => void): this; on(event: "open", listener: (fd: number) => void): this; on(event: "close", listener: () => void): this; - once(event: string, listener: Function): this; + once(event: string, listener: (...args: any[]) => void): this; once(event: "open", listener: (fd: number) => void): this; once(event: "close", listener: () => void): this; - prependListener(event: string, listener: Function): this; + prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "open", listener: (fd: number) => void): this; prependListener(event: "close", listener: () => void): this; - prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "open", listener: (fd: number) => void): this; prependOnceListener(event: "close", listener: () => void): this; } @@ -2543,23 +2595,23 @@ declare module "fs" { * 1. open * 2. close */ - addListener(event: string, listener: Function): this; + addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "open", listener: (fd: number) => void): this; addListener(event: "close", listener: () => void): this; - on(event: string, listener: Function): this; + on(event: string, listener: (...args: any[]) => void): this; on(event: "open", listener: (fd: number) => void): this; on(event: "close", listener: () => void): this; - once(event: string, listener: Function): this; + once(event: string, listener: (...args: any[]) => void): this; once(event: "open", listener: (fd: number) => void): this; once(event: "close", listener: () => void): this; - prependListener(event: string, listener: Function): this; + prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "open", listener: (fd: number) => void): this; prependListener(event: "close", listener: () => void): this; - prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "open", listener: (fd: number) => void): this; prependOnceListener(event: "close", listener: () => void): this; } @@ -3322,7 +3374,7 @@ declare module "tls" { * 1. OCSPResponse * 2. secureConnect **/ - addListener(event: string, listener: Function): this; + addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; addListener(event: "secureConnect", listener: () => void): this; @@ -3330,19 +3382,19 @@ declare module "tls" { emit(event: "OCSPResponse", response: Buffer): boolean; emit(event: "secureConnect"): boolean; - on(event: string, listener: Function): this; + on(event: string, listener: (...args: any[]) => void): this; on(event: "OCSPResponse", listener: (response: Buffer) => void): this; on(event: "secureConnect", listener: () => void): this; - once(event: string, listener: Function): this; + once(event: string, listener: (...args: any[]) => void): this; once(event: "OCSPResponse", listener: (response: Buffer) => void): this; once(event: "secureConnect", listener: () => void): this; - prependListener(event: string, listener: Function): this; + prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; prependListener(event: "secureConnect", listener: () => void): this; - prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; prependOnceListener(event: "secureConnect", listener: () => void): this; } @@ -3412,7 +3464,7 @@ declare module "tls" { * 4. resumeSession * 5. secureConnection **/ - addListener(event: string, listener: Function): this; + addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; addListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; @@ -3426,28 +3478,28 @@ declare module "tls" { emit(event: "resumeSession", sessionId: any, callback: (err: Error, sessionData: any) => void): boolean; emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; - on(event: string, listener: Function): this; + on(event: string, listener: (...args: any[]) => void): this; on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; on(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; on(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - once(event: string, listener: Function): this; + once(event: string, listener: (...args: any[]) => void): this; once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; once(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; once(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - prependListener(event: string, listener: Function): this; + prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; prependListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; prependListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; prependOnceListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; @@ -3702,8 +3754,8 @@ declare module "stream" { * 4. readable * 5. error **/ - addListener(event: string, listener: Function): this; - addListener(event: string, listener: Function): this; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "close", listener: () => void): this; addListener(event: "data", listener: (chunk: Buffer | string) => void): this; addListener(event: "end", listener: () => void): this; @@ -3717,35 +3769,35 @@ declare module "stream" { emit(event: "readable"): boolean; emit(event: "error", err: Error): boolean; - on(event: string, listener: Function): this; + on(event: string, listener: (...args: any[]) => void): this; on(event: "close", listener: () => void): this; on(event: "data", listener: (chunk: Buffer | string) => void): this; on(event: "end", listener: () => void): this; on(event: "readable", listener: () => void): this; on(event: "error", listener: (err: Error) => void): this; - once(event: string, listener: Function): this; + once(event: string, listener: (...args: any[]) => void): this; once(event: "close", listener: () => void): this; once(event: "data", listener: (chunk: Buffer | string) => void): this; once(event: "end", listener: () => void): this; once(event: "readable", listener: () => void): this; once(event: "error", listener: (err: Error) => void): this; - prependListener(event: string, listener: Function): this; + prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: () => void): this; prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; prependListener(event: "end", listener: () => void): this; prependListener(event: "readable", listener: () => void): this; prependListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; prependOnceListener(event: "end", listener: () => void): this; prependOnceListener(event: "readable", listener: () => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this; - removeListener(event: string, listener: Function): this; + removeListener(event: string, listener: (...args: any[]) => void): this; removeListener(event: "close", listener: () => void): this; removeListener(event: "data", listener: (chunk: Buffer | string) => void): this; removeListener(event: "end", listener: () => void): this; @@ -3782,7 +3834,7 @@ declare module "stream" { * 5. pipe * 6. unpipe **/ - addListener(event: string, listener: Function): this; + addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "close", listener: () => void): this; addListener(event: "drain", listener: () => void): this; addListener(event: "error", listener: (err: Error) => void): this; @@ -3798,7 +3850,7 @@ declare module "stream" { emit(event: "pipe", src: Readable): boolean; emit(event: "unpipe", src: Readable): boolean; - on(event: string, listener: Function): this; + on(event: string, listener: (...args: any[]) => void): this; on(event: "close", listener: () => void): this; on(event: "drain", listener: () => void): this; on(event: "error", listener: (err: Error) => void): this; @@ -3806,7 +3858,7 @@ declare module "stream" { on(event: "pipe", listener: (src: Readable) => void): this; on(event: "unpipe", listener: (src: Readable) => void): this; - once(event: string, listener: Function): this; + once(event: string, listener: (...args: any[]) => void): this; once(event: "close", listener: () => void): this; once(event: "drain", listener: () => void): this; once(event: "error", listener: (err: Error) => void): this; @@ -3814,7 +3866,7 @@ declare module "stream" { once(event: "pipe", listener: (src: Readable) => void): this; once(event: "unpipe", listener: (src: Readable) => void): this; - prependListener(event: string, listener: Function): this; + prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: () => void): this; prependListener(event: "drain", listener: () => void): this; prependListener(event: "error", listener: (err: Error) => void): this; @@ -3822,7 +3874,7 @@ declare module "stream" { prependListener(event: "pipe", listener: (src: Readable) => void): this; prependListener(event: "unpipe", listener: (src: Readable) => void): this; - prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "drain", listener: () => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this; @@ -3830,7 +3882,7 @@ declare module "stream" { prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; - removeListener(event: string, listener: Function): this; + removeListener(event: string, listener: (...args: any[]) => void): this; removeListener(event: "close", listener: () => void): this; removeListener(event: "drain", listener: () => void): this; removeListener(event: "error", listener: (err: Error) => void): this; diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 1752683835..aeefc2bbdc 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -88,7 +88,7 @@ namespace assert_tests { namespace events_tests { let emitter: events.EventEmitter; let event: string | symbol; - let listener: Function; + let listener: (...args: any[]) => void; let any: any; { @@ -1892,6 +1892,21 @@ namespace process_tests { } { process.on("message", (req: any) => { }); + process.addListener("beforeExit", (code: number) => { }); + process.once("disconnect", () => { }); + process.prependListener("exit", (code: number) => { }); + process.prependOnceListener("rejectionHandled", (promise: Promise) => { }); + process.on("uncaughtException", (error: Error) => { }); + process.addListener("unhandledRejection", (reason: any, promise: Promise) => { }); + process.once("warning", (warning: Error) => { }); + process.prependListener("message", (message: any, sendHandle: any) => { }); + process.prependOnceListener("SIGBREAK", () => { }); + process.on("newListener", (event: string, listener: Function) => { }); + process.once("removeListener", (event: string, listener: Function) => { }); + + const listeners = process.listeners('uncaughtException'); + const oldHandler = listeners[listeners.length - 1]; + process.addListener('uncaughtException', oldHandler); } } diff --git a/types/nodemailer-smtp-transport/index.d.ts b/types/nodemailer-smtp-transport/index.d.ts index 7f0f8d7cca..4e4e11afe0 100644 --- a/types/nodemailer-smtp-transport/index.d.ts +++ b/types/nodemailer-smtp-transport/index.d.ts @@ -24,16 +24,16 @@ declare namespace smtpTransport { /** is the registered client secret of the application */ clientSecret?: string; - + /** is an optional refresh token. If it is provided then Nodemailer tries to generate a new access token if existing one expires or fails */ refreshToken?: string; - + /** is the access token for the user. Required only if refreshToken is not available and there is no token refresh callback specified */ accessToken?: string; - + /** is an optional expiration time for the current accessToken */ expires?: number; - + /** is an optional HTTP endpoint for requesting new access tokens. This value defaults to Gmail */ accessUrl?: string; diff --git a/types/nodemailer/index.d.ts b/types/nodemailer/index.d.ts index 88a82f073a..833873c45e 100644 --- a/types/nodemailer/index.d.ts +++ b/types/nodemailer/index.d.ts @@ -4,11 +4,9 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// import directTransport = require("nodemailer-direct-transport"); import smtpTransport = require("nodemailer-smtp-transport"); -import * as Promise from 'bluebird'; /** * Transporter plugin @@ -36,7 +34,7 @@ export interface Transporter { * Send mail using a template. */ templateSender(template?: any, defaults?: any): (mailData: any, context: any) => Promise; - + /** * Send mail using a template with a callback. */ @@ -50,7 +48,7 @@ export interface Transporter { * @param pluginFunc is a function that takes two arguments: the mail object and a callback function */ use(step: string, plugin: Plugin): void; - + /** * Verifies connection with server */ diff --git a/types/oauth2-server/index.d.ts b/types/oauth2-server/index.d.ts index 0e3ff61006..d328e06fc4 100644 --- a/types/oauth2-server/index.d.ts +++ b/types/oauth2-server/index.d.ts @@ -1,423 +1,469 @@ -// Type definitions for Node OAuth2 Server -// Project: https://github.com/thomseddon/node-oauth2-server -// Definitions by: Robbie Van Gorkom +// Type definitions for Node OAuth2 Server 3.0 +// Project: https://github.com/oauthjs/node-oauth2-server +// Definitions by: Robbie Van Gorkom , +// Charles Irick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/* =================== USAGE =================== +import { RequestHandler } from "express"; +import { Request } from "express"; - import * as oauthserver from "oauth2-server"; - var oauth = oauthserver(); +/** + * Represents an OAuth2 server instance. + */ +declare class OAuth2Server { + static OAuth2Server: typeof OAuth2Server; - =============================================== */ + /** + * Instantiates OAuth2Server using the supplied model + * + * @param options + */ + constructor(options: OAuth2Server.ServerOptions); + /** + * Authenticates a request. + * + * @param request + * @param response + * @param options + * @param callback + */ + authenticate( + request: OAuth2Server.Request, + response: OAuth2Server.Response, + options?: OAuth2Server.AuthenticateOptions, + callback?: OAuth2Server.Callback + ): Promise; + /** + * Authorizes a token request. + * + * @param request + * @param response + * @param options + * @param callback + */ + authorize( + request: OAuth2Server.Request, + response: OAuth2Server.Response, + options?: OAuth2Server.AuthorizeOptions, + callback?: OAuth2Server.Callback + ): Promise; + /** + * Retrieves a new token for an authorized token request. + * + * @param request + * @param response + * @param options + * @param callback + */ + token( + request: OAuth2Server.Request, + response: OAuth2Server.Response, + options?: OAuth2Server.TokenOptions, + callback?: OAuth2Server.Callback + ): Promise; +} -import {RequestHandler} from "express"; -import {Request} from "express"; +declare namespace OAuth2Server { + /** + * Represents an incoming HTTP request. + */ + class Request { + body?: any; + headers?: { [key: string]: string; }; + method?: string; + query?: { [key: string]: string; }; -declare function o(config: o.Config): o.OAuth2Server; + /** + * Instantiates Request using the supplied options. + * + * @param options + */ + constructor(options?: { [key: string]: any } | Express.Request); -declare namespace o { - interface OAuth2Server { - grant(): RequestHandler; - authorise(): any; - errorHandler(): any; + /** + * Returns the specified HTTP header field. The match is case-insensitive. + * + * @param field + */ + get(field: string): any | undefined; + + /** + * Checks if the request’s Content-Type HTTP header matches any of the given MIME types. + * + * @param types + */ + is(types: string[]): string | false; } - interface Config { + /** + * Represents an outgoing HTTP response. + */ + class Response { + body?: any; + headers?: { [key: string]: string; }; + status?: number; + + /** + * Instantiates Response using the supplied options. + * + * @param options + */ + constructor(options?: { [key: string]: any; } | Express.Response); + + /** + * Returns the specified HTTP header field. The match is case-insensitive. + * + * @param field + */ + get(field: string): any | undefined; + + /** + * Sets the specified HTTP header field. The match is case-insensitive. + * + * @param field + * @param value + */ + set(field: string, value: string): void; + + /** + * Redirects to the specified URL using 302 Found. + * + * @param url + */ + redirect(url: string): void; + } + + interface ServerOptions extends AuthenticateOptions, AuthorizeOptions, TokenOptions { /** * Model object */ - model: {}; + model: AuthorizationCodeModel | ClientCredentialsModel | RefreshTokenModel | PasswordModel | ExtensionModel; + } + interface AuthenticateOptions { /** - * grant types you wish to support, currently the module supports authorization_code, - * password, refresh_token and client_credentials + * The scope(s) to authenticate. */ - grants: string[]; + scope?: string | undefined; /** - * If true errors will be logged to console. You may also pass a custom function, in - * which case that function will be called with the error as its first argument - * Default: false + * Set the X-Accepted-OAuth-Scopes HTTP header on response objects. */ - debug?: boolean; + addAcceptedScopesHeader?: boolean; /** - * Life of access tokens in seconds - * If null, tokens will considered to never expire - * Default: 3600 + * Set the X-OAuth-Scopes HTTP header on response objects. + */ + addAuthorizedScopesHeader?: boolean; + + /** + * Allow clients to pass bearer tokens in the query string of a request. + */ + allowBearerTokensInQueryString?: boolean; + } + + interface AuthorizeOptions { + /** + * The authenticate handler + */ + authenticateHandler?: {}; + + /** + * Allow clients to specify an empty state + */ + allowEmptyState?: boolean; + + /** + * Lifetime of generated authorization codes in seconds (default = 5 minutes). + */ + authorizationCodeLifetime?: number; + } + + interface TokenOptions { + /** + * Lifetime of generated access tokens in seconds (default = 1 hour) */ accessTokenLifetime?: number; /** - * Life of refresh tokens in seconds - * If null, tokens will considered to never expire - * Default: 1209600 + * Lifetime of generated refresh tokens in seconds (default = 2 weeks) */ refreshTokenLifetime?: number; /** - * Life of auth codes in seconds - * Default: 30 + * Allow extended attributes to be set on the returned token */ - authCodeLifetime?: number; + allowExtendedTokenAttributes?: boolean; /** - * Regex to sanity check client id against before checking model. Note: the default - * just matches common client_id structures, change as needed - * Default: /^[a-z0-9-_]{3,40}$/i + * Require a client secret. Defaults to true for all grant types. */ - clientIdRegex?: RegExp; + requireClientAuthentication?: {}; /** - * If true, non grant errors will not be handled internally (so you can ensure a - * consistent format with the rest of your api) + * Always revoke the used refresh token and issue a new one for the refresh_token grant. */ - passthroughErrors?: boolean; - - /** - * If true, next will be called even if a response has been sent (you probably don't want this) - */ - continueAfterResponse?: boolean; + alwaysIssueNewRefreshToken?: boolean; } + /** + * Represents a generic callback structure for model callbacks + */ + type Callback = (err?: any, result?: T) => void; + + /** + * For returning falsey parameters in cases of failure + */ + type Falsey = '' | 0 | false | null | undefined; + interface BaseModel { /** + * Invoked to generate a new access token. * - * @param bearerToken - The bearer token (access token) that has been provided - * @param callback - */ - getAccessToken(bearerToken: string, - callback: GetAccessTokenCallback): void; - - /** - * - * @param clientId - * @param clientSecret - If null, omit from search query (only search by clientId) - * @param callback - */ - getClient(clientId: string, - clientSecret: string, - callback: GetClientCallback): void; - - /** - * - * @param clientId - * @param grantType - * @param callback - */ - grantTypeAllowed(clientId: string, - grantType: string, - callback: GrantTypeAllowedCallback): void; - - /** - * - * @param accessToken - * @param clientId - * @param expires + * @param client * @param user + * @param scope * @param callback */ - saveAccessToken(accessToken: string, - clientId: string, - expires: Date, - user: User, - callback: SaveAccessTokenCallback): void; - } - - interface AuthorizationCodeModel extends BaseModel { - /** - * - * @param authCode - * @param callback - */ - getAuthCode(authCode: string, - callback: GetAuthCodeCallback): void; + generateAccessToken?(client: Client, user: User, scope: string, callback?: Callback): Promise; /** - * - * @param authCode - * @param clientId - * @param expires - * @param user - Whatever was passed as user to the codeGrant function (see example) - * @param callback - */ - saveAuthCode(authCode: string, - clientId: string, - expires: Date, - user: User | string, - callback: SaveAuthCodeCallback): void; - } - - interface PasswordModel extends BaseModel { - /** - * - * @param username - * @param password - * @param callback - */ - getUser(username: string, - password: string, - callback: GetUserCallback): void; - } - - interface RefreshTokenModel extends BaseModel { - /** - * - * @param refreshToken - * @param clientId - * @param expires - * @param user - * @param callback - */ - saveRefreshToken(refreshToken: string, - clientId: string, - expires: Date, - user: User, - callback: SaveRefreshTokenCallback): void; - - /** - * - * @param refreshToken - The bearer token (refresh token) that has been provided - * @param callback - */ - getRefreshToken(refreshToken: string, - callback: GetRefreshTokenCallback): void; - - /** - * The spec does not actually require that you revoke the old token - hence this is - * optional (Last paragraph: http://tools.ietf.org/html/rfc6749#section-6) - * @param refreshToken - * @param callback - */ - revokeRefreshToken?(refreshToken: string, - callback: RevokeRefreshTokenCallback): void; - } - - interface ExtensionModel extends BaseModel { - /** - * - * @param grantType - * @param req - * @param callback - */ - extendedGrant(grantType: string, - req: Request, - callback: ExtendedGrantCallback): void; - } - - interface ClientCredentialsModel extends BaseModel { - /** + * Invoked to retrieve a client using a client id or a client id/client secret combination, depending on the grant type. * * @param clientId * @param clientSecret * @param callback */ - getUserFromClient(clientId: string, - clientSecret: string, - callback: GetUserFromClientCallback): void; + getClient(clientId: string, clientSecret: string, callback?: Callback): Promise; /** + * Invoked to save an access token and optionally a refresh token, depending on the grant type. * - * @param type - accessToken or refreshToken - * @param req - The current express request + * @param token + * @param client + * @param user * @param callback */ - generateToken?(type: string, - req: Request, - callback: GenerateTokenCallback): void; + saveToken(token: Token, client: Client, user: User, callback?: Callback): Promise; } - interface GenerateTokenCallback { + interface RequestAuthenticationModel { /** + * Invoked to retrieve an existing access token previously saved through Model#saveToken(). * - * @param error - Truthy to indicate an error - * @param token - string indicates success - * null indicates to revert to the default token generator - * object indicates a reissue (i.e. will not be passed to saveAccessToken/saveRefreshToken) - * Must contain the following keys (if object): - * string accessToken OR refreshToken dependant on type + * @param accessToken + * @param callback */ - (error: any, token: string | Object): void; - } + getAccessToken(accessToken: string, callback?: Callback): Promise; - interface GetUserFromClientCallback { /** + * Invoked during request authentication to check if the provided access token was authorized the requested scopes. * - * @param error - Truthy to indicate an error - * @param user - The user retrieved from storage or falsey to indicate an invalid user - * Saved in req.user + * @param token + * @param scope + * @param callback */ - (error: any, user: User): void; + verifyScope(token: Token, scope: string, callback?: Callback): Promise; } - interface ExtendedGrantCallback { + interface AuthorizationCodeModel extends BaseModel, RequestAuthenticationModel { /** + * Invoked to generate a new refresh token. * - * @param error - Truthy to indicate an error - * @param supported - Whether you support the grant type - * @param user - The user retrieved from storage or falsey to indicate an invalid user - * Saved in req.user + * @param client + * @param user + * @param scope + * @param callback */ - (error: any, supported: boolean, user: User): void; - } + generateRefreshToken?(client: Client, user: User, scope: string, callback?: Callback): Promise; - interface RevokeRefreshTokenCallback { - /** - * Truthy to indicate an error - * @param error - */ - (error: any): void; - } - - interface GetRefreshTokenCallback { /** + * Invoked to generate a new authorization code. * - * @param error - Truthy to indicate an error - * @param refreshToken - The refresh token retrieved form storage or falsey to indicate invalid refresh token + * @param callback */ - (error: any, refreshToken: RefreshToken): void; - } + generateAuthorizationCode?(callback?: Callback): Promise; - interface SaveRefreshTokenCallback { /** + * Invoked to retrieve an existing authorization code previously saved through Model#saveAuthorizationCode(). * - * @param error - Truthy to indicate an error + * @param authorizationCode + * @param callback */ - (error: any): void; - } + getAuthorizationCode(authorizationCode: string, callback?: Callback): Promise; - interface GetUserCallback { /** + * Invoked to save an authorization code. * - * @param error - Truthy to indicate an error - * @param user - The user retrieved from storage or falsey to indicate an invalid user - * Saved in req.user + * @param code + * @param client + * @param user + * @param callback */ - (error: any, user: User): void; - } + saveAuthorizationCode(code: AuthorizationCode, client: Client, user: User, callback?: Callback): Promise; - interface SaveAuthCodeCallback { /** + * Invoked to revoke an authorization code. * - * @param error - Truthy to indicate an error + * @param code + * @param callback */ - (error: any): void; - } + revokeAuthorizationCode(code: AuthorizationCode, callback?: Callback): Promise; - interface GetAuthCodeCallback { /** + * Invoked to check if the requested scope is valid for a particular client/user combination. * - * @param error - Truthy to indicate an error - * @param authCode - The authorization code retrieved form storage or falsey to indicate invalid code + * @param user + * @param client + * @param string + * @param callback */ - (error: String, authCode: AuthCode): void + validateScope?(user: User, client: Client, scope: string, callback?: Callback): Promise; } - interface SaveAccessTokenCallback { + interface PasswordModel extends BaseModel, RequestAuthenticationModel { /** + * Invoked to generate a new refresh token. * - * @param error - Truthy to indicate an error + * @param client + * @param user + * @param scope + * @param callback */ - (error: any): void; - } + generateRefreshToken?(client: Client, user: User, scope: string, callback?: Callback): Promise; - interface GetAccessTokenCallback { /** + * Invoked to retrieve a user using a username/password combination. * - * @param error - Truthy to indicate an error - * @param accessToken - The access token retrieved form storage or falsey to indicate invalid access token + * @param username + * @param password + * @param callback */ - (error: any, accessToken: AccessToken): void; - } + getUser(username: string, password: string, callback?: Callback): Promise; - interface GetClientCallback { /** + * Invoked to check if the requested scope is valid for a particular client/user combination. * - * @param error - Truthy to indicate an error - * @param client - The client retrieved from storage or falsey to indicate an invalid client - * Saved in req.client + * @param user + * @param client + * @param string + * @param callback */ - (error: any, client: Client): void; + validateScope?(user: User, client: Client, scope: string, callback?: Callback): Promise; } - interface GrantTypeAllowedCallback { + interface RefreshTokenModel extends BaseModel, RequestAuthenticationModel { /** + * Invoked to generate a new refresh token. * - * @param error - Truthy to indicate an error - * @param allowed - Indicates whether the grantType is allowed for this clientId + * @param client + * @param user + * @param scope + * @param callback */ - (error: any, allowed: boolean): void; - } - - interface RefreshToken { - /** - * client id associated with this token - */ - clientId: string; - - /** - * The date when it expires - * null to indicate the token never expires - */ - expires: Date; + generateRefreshToken?(client: Client, user: User, scope: string, callback?: Callback): Promise; /** + * Invoked to retrieve an existing refresh token previously saved through Model#saveToken(). * + * @param refreshToken + * @param callback */ - userId: string; + getRefreshToken(refreshToken: string, callback?: Callback): Promise; + + /** + * Invoked to revoke a refresh token. + * + * @param token + * @param callback + */ + revokeToken(token: Token, callback?: Callback): Promise; } - interface AuthCode { + interface ClientCredentialsModel extends BaseModel, RequestAuthenticationModel { /** - * client id associated with this auth code + * Invoked to retrieve the user associated with the specified client. + * + * @param client + * @param callback */ - clientId: string; + getUserFromClient(client: Client, callback?: Callback): Promise; /** - * The date when it expires + * Invoked to check if the requested scope is valid for a particular client/user combination. + * + * @param user + * @param client + * @param string + * @param callback */ - expires: Date; - - /** - * The userId - */ - userId: string; + validateScope?(user: User, client: Client, scope: string, callback?: Callback): Promise; } + interface ExtensionModel extends BaseModel, RequestAuthenticationModel {} + + /** + * An interface representing the user. + * A user object is completely transparent to oauth2-server and is simply used as input to model functions. + */ interface User { id: string; + [key: string]: any; } + /** + * An interface representing the client and associated data + */ interface Client { - clientId: string; - - /** - * authorization_code grant type only - */ - redirectUri: string; + id: string; + redirectUris?: string[]; + grants: string[]; + accessTokenLifetime?: number; + refreshTokenLifetime?: number; + [key: string]: any; } - interface AccessToken { - /** - * The date when it expires - * null to indicate the token never expires - */ - expires: Date; + /** + * An interface representing the authorization code and associated data. + */ + interface AuthorizationCode { + authorizationCode: string; + expiresAt: Date; + redirectUri: string; + scope?: string; + client: Client; + user: User; + [key: string]: any; + } - /** - * If a user key exists, this is saved as req.user - */ - user?: User; + /** + * An interface representing the token(s) and associated data. + */ + interface Token { + accessToken: string; + accessTokenExpiresAt?: Date; + refreshToken?: string; + refreshTokenExpiresAt?: Date; + scope?: string; + client: Client; + user: User; + [key: string]: any; + } - /** - * If a user key exists, this is saved as req.user - * Otherwise a userId key must exist, which is saved in req.user.id - */ - userId?: string; + /** + * An interface representing the refresh token and associated data. + */ + interface RefreshToken { + refreshToken: string; + refreshTokenExpiresAt?: Date; + scope?: string; + client: Client; + user: User; + [key: string]: any; } } -export = o; +export = OAuth2Server; diff --git a/types/oauth2-server/oauth2-server-tests.ts b/types/oauth2-server/oauth2-server-tests.ts index 56216edc8f..be8fa83705 100644 --- a/types/oauth2-server/oauth2-server-tests.ts +++ b/types/oauth2-server/oauth2-server-tests.ts @@ -1,18 +1,95 @@ - - import * as express from "express"; -import * as oauthserver from "oauth2-server"; +import * as OAuth2Server from "oauth2-server"; -var oauth = oauthserver({ - model: {}, - grants: ['password'], - debug: true +const oauth2Model: OAuth2Server.AuthorizationCodeModel = { + getClient: async (clientId: string, clientSecret: string): Promise => { + return undefined; + }, + saveToken: async (token: OAuth2Server.Token, client: OAuth2Server.Client, user: OAuth2Server.User): Promise => { + return token; + }, + getAccessToken: async (accessToken: string): Promise => { + return { + accessToken, + client: {id: "testClient", grants: ["access_token"]}, + user: {id: "testUser"} + }; + }, + verifyScope: async (token: OAuth2Server.Token, scope: string): Promise => { + return true; + }, + getAuthorizationCode: async (authorizationCode: string): Promise => { + return { + authorizationCode, + expiresAt: new Date(), + redirectUri: "www.test.com", + client: {id: "testClient", grants: ["access_token"]}, + user: {id: "testUser"} + }; + }, + saveAuthorizationCode: async (code: OAuth2Server.AuthorizationCode, client: OAuth2Server.Client, user: OAuth2Server.User): Promise => { + return code; + }, + revokeAuthorizationCode: async (code: OAuth2Server.AuthorizationCode): Promise => { + return true; + } +}; + +const oauth2Server = new OAuth2Server({ + model: oauth2Model }); -var app = express(); +// Authenticate user with supplied bearer token +const authenticate = (authenticateOptions?: {}) => { + const options: undefined | {} = authenticateOptions || {}; + return async (req: express.Request & {user: OAuth2Server.Token}, res: express.Response, next: express.NextFunction) => { + const request = new OAuth2Server.Request(req); + const response = new OAuth2Server.Response(res); -app.all('/oauth/token', oauth.grant()); -app.get('/', oauth.authorise(), function (req, res) { - res.send('Secret area'); + try { + // Test async method of accessing oauth2Server + const token = await oauth2Server.authenticate(request, response, options); + req.user = token; + next(); + } catch (err) { + res.status(err.code || 500).json(err); + } + }; +}; + +const app = express(); +app.all('/oauth2/token', (req: express.Request, res: express.Response, next: express.NextFunction) => { + const request = new OAuth2Server.Request(req); + const response = new OAuth2Server.Response(res); + + oauth2Server.token(request, response) + .then((token: OAuth2Server.Token) => { + res.json(token); + }).catch((err: any) => { + res.status(err.code || 500).json(err); + }); }); -app.use(oauth.errorHandler()); + +app.post('/oauth2/authorize', (req, res) => { + const request = new OAuth2Server.Request(req); + const response = new OAuth2Server.Response(res); + + oauth2Server.authorize(request, response) + .then((success: OAuth2Server.AuthorizationCode) => { + res.json(success); + }).catch((err: any) => { + res.status(err.code || 500).json(err); + }); +}); + +app.get('/secure', authenticate(), (req: express.Request & {user: OAuth2Server.Token}, res: express.Response, next: express.NextFunction) => { + res.json({message: 'Secure data'}); +}); + +app.get('/profile', authenticate({scope: 'profile'}), (req: express.Request & {user: OAuth2Server.Token}, res: express.Response, next: express.NextFunction) => { + res.json({ + profile: req.user + }); +}); + +app.listen(3000); diff --git a/types/oauth2-server/tsconfig.json b/types/oauth2-server/tsconfig.json index 0345961931..fdafde9f35 100644 --- a/types/oauth2-server/tsconfig.json +++ b/types/oauth2-server/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es2017" ], "noImplicitAny": true, "noImplicitThis": true, @@ -13,10 +13,11 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "target": "es6" }, "files": [ "index.d.ts", "oauth2-server-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/oauth2-server/tslint.json b/types/oauth2-server/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/oauth2-server/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/orientjs/index.d.ts b/types/orientjs/index.d.ts index 571aeebe7c..679fc7c70a 100644 --- a/types/orientjs/index.d.ts +++ b/types/orientjs/index.d.ts @@ -2,6 +2,8 @@ // Project: https://github.com/orientechnologies/orientjs // Definitions by: Saeed Tabrizi // Definitions: https://github.com/borisyankov/DefinitelyTyped +// TypeScript Version: 2.3 + // Developed with love in www.nowcando.com /// diff --git a/types/page/index.d.ts b/types/page/index.d.ts index 229cfd273c..0f9317c6a4 100644 --- a/types/page/index.d.ts +++ b/types/page/index.d.ts @@ -26,6 +26,17 @@ declare namespace PageJS { * Links that are not of the same origin are disregarded and will not be dispatched. */ (path: string, ...callbacks: Callback[]): void; + /** + * Defines a route mapping path to the given callback(s). + * + * page('/', user.list) + * page('/user/:id', user.load, user.show) + * page('/user/:id/edit', user.load, user.edit) + * page('*', notfound) + * + * Links that are not of the same origin are disregarded and will not be dispatched. + */ + (path: RegExp, ...callbacks: Callback[]): void; /** * This is equivalent to page('*', callback) for generic "middleware". */ diff --git a/types/paho-mqtt/index.d.ts b/types/paho-mqtt/index.d.ts new file mode 100644 index 0000000000..7df5863532 --- /dev/null +++ b/types/paho-mqtt/index.d.ts @@ -0,0 +1,445 @@ +// Type definitions for paho-mqtt 1.0 +// Project: https://github.com/eclipse/paho.mqtt.javascript#readme +// Definitions by: Alex Mikhalev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Paho { + /** + * Send and receive messages using web browsers. + *

+ * This programming interface lets a JavaScript client application use the MQTT V3.1 or + * V3.1.1 protocol to connect to an MQTT-supporting messaging server. + * + * The function supported includes: + *

    + *
  1. Connecting to and disconnecting from a server. The server is identified by its host name and port number. + *
  2. Specifying options that relate to the communications link with the server, + * for example the frequency of keep-alive heartbeats, and whether SSL/TLS is required. + *
  3. Subscribing to and receiving messages from MQTT Topics. + *
  4. Publishing messages to MQTT Topics. + *
+ *

+ * The API consists of two main objects: + *

+ *
{@link Paho.MQTT.Client}
+ *
This contains methods that provide the functionality of the API, + * including provision of callbacks that notify the application when a message + * arrives from or is delivered to the messaging server, + * or when the status of its connection to the messaging server changes.
+ *
{@link Paho.MQTT.Message}
+ *
This encapsulates the payload of the message along with various attributes + * associated with its delivery, in particular the destination to which it has + * been (or is about to be) sent.
+ *
+ *

+ * The programming interface validates parameters passed to it, and will throw + * an Error containing an error message intended for developer use, if it detects + * an error with any parameter. + *

+ * + * @namespace Paho.MQTT + */ + namespace MQTT { + /** + * The Quality of Service used to deliver a message. + *

+ *
0 Best effort (default).
+ *
1 At least once.
+ *
2 Exactly once.
+ *
+ */ + type Qos = 0 | 1 | 2; + + interface MQTTError { + /** A number indicating the nature of the error. */ + errorCode: number; + + /** Text describing the error */ + errorMessage: string; + } + interface WithInvocationContext { + /** + * invocationContext as passed in with the corresponding field in the connectOptions or + * subscribeOptions. + */ + invocationContext: any; + } + interface ErrorWithInvocationContext extends MQTTError, WithInvocationContext { + } + interface OnSubscribeSuccessParams extends WithInvocationContext { + grantedQos: Qos; + } + + /** + * Called when the connect acknowledgement has been received from the server. + * @param o + * A single response object parameter is passed to the onSuccess callback containing the following fields: + *
  • invocationContext as passed in with the corresponding field in the connectOptions. + */ + type OnSuccessCallback = (o: WithInvocationContext) => void; + + /** + * Called when the subscribe acknowledgement has been received from the server. + * @param o + * A single response object parameter is passed to the onSuccess callback containing the following fields: + *
  • invocationContext as passed in with the corresponding field in the connectOptions. + */ + type OnSubscribeSuccessCallback = (o: OnSubscribeSuccessParams) => void; + + /** + * Called when the connect request has failed or timed out. + * @param e + * A single response object parameter is passed to the onFailure callback containing the following fields: + *
  • invocationContext as passed in with the corresponding field in the connectOptions. + *
  • errorCode a number indicating the nature of the error. + *
  • errorMessage text describing the error. + */ + type OnFailureCallback = (e: ErrorWithInvocationContext) => void; + + /** + * Called when a connection has been lost. + * @param error A single response object parameter is passed to the onConnectionLost callback containing the + * following fields: + *
  • errorCode + *
  • errorMessage + */ + type OnConnectionLostHandler = (error: MQTTError) => void; + + /** + * Called when a message was delivered or has arrived. + * @param message The {@link Paho.MQTT.Message} that was delivered or has arrived. + */ + type OnMessageHandler = (message: Message) => void; + + /** + * Attributes used with a connection. + */ + interface ConnectionOptions { + /** + * If the connect has not succeeded within this number of seconds, it is deemed to have failed. + * @default The default is 30 seconds. + */ + timeout?: number; + /** Authentication username for this connection. */ + userName?: string; + /** Authentication password for this connection. */ + password?: string; + /** Sent by the server when the client disconnects abnormally. */ + willMessage?: Message; + /** + * The server disconnects this client if there is no activity for this number of seconds. + * @default The default value of 60 seconds is assumed if not set. + */ + keepAliveInterval?: number; + /** + * If true(default) the client and server persistent state is deleted on successful connect. + * @default true + */ + cleanSession?: boolean; + /** If present and true, use an SSL Websocket connection. */ + useSSL?: boolean; + /** Passed to the onSuccess callback or onFailure callback. */ + invocationContext?: any; + /** + * Called when the connect acknowledgement has been received from the server. + */ + onSuccess?: OnSuccessCallback; + /** + * Specifies the mqtt version to use when connecting + *
    + *
    3 - MQTT 3.1
    + *
    4 - MQTT 3.1.1 (default)
    + *
    + * @default 4 + */ + mqttVersion?: 3 | 4; + /** + * Called when the connect request has failed or timed out. + */ + onFailure?: OnFailureCallback; + /** + * If present this contains either a set of hostnames or fully qualified + * WebSocket URIs (ws://example.com:1883/mqtt), that are tried in order in place of the host and port + * paramater on the construtor. The hosts are tried one at at time in order until one of then succeeds. + */ + hosts?: string[]; + /** + * If present the set of ports matching the hosts. If hosts contains URIs, this property is not used. + */ + ports?: number[]; + } + + /** + * Used to control a subscription + */ + interface SubscribeOptions { + /** the maximum qos of any publications sent as a result of making this subscription. */ + qos?: Qos; + /** passed to the onSuccess callback or onFailure callback. */ + invocationContext?: any; + /** called when the subscribe acknowledgement has been received from the server. */ + onSuccess?: OnSubscribeSuccessCallback; + /** called when the subscribe request has failed or timed out. */ + onFailure?: OnFailureCallback; + /** + * timeout which, if present, determines the number of seconds after which the onFailure calback is called. + * The presence of a timeout does not prevent the onSuccess callback from being called when the subscribe + * completes. + */ + timeout?: number; + } + + interface UnsubscribeOptions { + /** passed to the onSuccess callback or onFailure callback. */ + invocationContext?: any; + /** called when the unsubscribe acknowledgement has been received from the server. */ + onSuccess?: OnSuccessCallback; + /** called when the unsubscribe request has failed or timed out. */ + onFailure?: OnFailureCallback; + /** + * timeout which, if present, determines the number of seconds after which the onFailure calback is called. + * The presence of a timeout does not prevent the onSuccess callback from being called when the unsubscribe + * completes. + */ + timeout?: number; + } + + interface TraceElement { + severity: "Debug"; + message: string; + } + + type TraceFunction = (element: TraceElement) => void; + + /** + * The JavaScript application communicates to the server using a {@link Paho.MQTT.Client} object. + * + * Most applications will create just one Client object and then call its connect() method, + * however applications can create more than one Client object if they wish. + * In this case the combination of host, port and clientId attributes must be different for each Client object. + * + * The send, subscribe and unsubscribe methods are implemented as asynchronous JavaScript methods + * (even though the underlying protocol exchange might be synchronous in nature). + * This means they signal their completion by calling back to the application, + * via Success or Failure callback functions provided by the application on the method in question. + * Such callbacks are called at most once per method invocation and do not persist beyond the lifetime + * of the script that made the invocation. + * + * In contrast there are some callback functions, most notably {@link onMessageArrived}, + * that are defined on the {@link Paho.MQTT.Client} object. + * These may get called multiple times, and aren't directly related to specific method invocations made by the + * client. + * + */ + class Client { + /** read only used when connecting to the server. */ + readonly clientId: string; + + /** read only the server's DNS hostname or dotted decimal IP address. */ + readonly host: string; + + /** read only the server's path. */ + readonly path: string; + + /** read only the server's port. */ + readonly port: number; + + /** function called with trace information, if set */ + trace?: TraceFunction; + + /** + * called when a connection has been lost. after a connect() method has succeeded. + * Establish the call back used when a connection has been lost. The connection may be + * lost because the client initiates a disconnect or because the server or network + * cause the client to be disconnected. The disconnect call back may be called without + * the connectionComplete call back being invoked if, for example the client fails to + * connect. + * A single response object parameter is passed to the onConnectionLost callback containing the following + * fields: + *
  • errorCode + *
  • errorMessage + */ + onConnectionLost: OnConnectionLostHandler; + + /** + * called when a message has been delivered. + * All processing that this Client will ever do has been completed. So, for example, + * in the case of a Qos=2 message sent by this client, the PubComp flow has been received from the server + * and the message has been removed from persistent storage before this callback is invoked. + * Parameters passed to the onMessageDelivered callback are: + *
  • {@link Paho.MQTT.Message} that was delivered. + */ + onMessageDelivered: OnMessageHandler; + + /** + * called when a message has arrived in this Paho.MQTT.client. + * Parameters passed to the onMessageArrived callback are: + *
  • {@link Paho.MQTT.Message} that has arrived. + */ + onMessageArrived: OnMessageHandler; + + /* tslint:disable:unified-signatures */ + /* these cannot actually be neatly unified */ + + /** + * @param host - the address of the messaging server as a DNS name or dotted decimal IP address. + * @param port - the port number to connect to + * @param path - the path on the host to connect to - only used if host is not a URI. Default: '/mqtt'. + * @param clientId - the Messaging client identifier, between 1 and 23 characters in length. + */ + constructor(host: string, port: number, path: string, clientId: string); + + /** + * @param host - the address of the messaging server as a DNS name or dotted decimal IP address. + * @param port - the port number to connect to + * @param clientId - the Messaging client identifier, between 1 and 23 characters in length. + */ + constructor(host: string, port: number, clientId: string); + + /** + * @param hostUri - the address of the messaging server as a fully qualified WebSocket URI + * @param clientId - the Messaging client identifier, between 1 and 23 characters in length. + */ + constructor(hostUri: string, clientId: string); + + /* tslint:enable:unified-signatures */ + + /** + * Connect this Messaging client to its server. + * @throws {InvalidState} if the client is not in disconnected state. The client must have received + * connectionLost or disconnected before calling connect for a second or subsequent time. + */ + connect(connectionOptions?: ConnectionOptions): void; + + /** + * Normal disconnect of this Messaging client from its server. + * + * @throws {InvalidState} if the client is already disconnected. + */ + disconnect(): void; + + /** + * @returns True if the client is currently connected + */ + isConnected(): boolean; + + /** + * Get the contents of the trace log. + * + * @return {Object[]} tracebuffer containing the time ordered trace records. + */ + getTraceLog(): any[]; + + /** + * Start tracing. + */ + startTrace(): void; + + /** + * Stop tracing. + */ + stopTrace(): void; + + /** + * Send a message to the consumers of the destination in the Message. + * + * @param {Paho.MQTT.Message} message - mandatory The {@link Paho.MQTT.Message} object to be sent. + * @throws {InvalidState} if the client is not connected. + */ + send(message: Message): void; + + /** + * Send a message to the consumers of the destination in the Message. + * + * @param {string} topic - mandatory The name of the destination to which the message is to be sent. + * @param {string|ArrayBuffer} payload - The message data to be sent. + * @param {number} qos The Quality of Service used to deliver the message. + *
    + *
    0 Best effort (default). + *
    1 At least once. + *
    2 Exactly once. + *
    + * @param {Boolean} retained If true, the message is to be retained by the server and delivered to both + * current and future subscriptions. If false the server only delivers the message to current subscribers, + * this is the default for new Messages. A received message has the retained boolean set to true if the + * message was published with the retained boolean set to true and the subscrption was made after the + * message has been published. + * @throws {InvalidState} if the client is not connected. + */ + send(topic: string, payload: string | ArrayBuffer, qos?: Qos, retained?: boolean): void; + + /** + * Subscribe for messages, request receipt of a copy of messages sent to the destinations described by the + * filter. + * + * @param filter A filter describing the destinations to receive messages from. + * @param subcribeOptions Used to control the subscription + * @throws {InvalidState} if the client is not in connected state. + */ + subscribe(filter: string, subcribeOptions?: SubscribeOptions): void; + + /** + * Unsubscribe for messages, stop receiving messages sent to destinations described by the filter. + * + * @param filter - describing the destinations to receive messages from. + * @param unsubscribeOptions - used to control the subscription + * @throws {InvalidState} if the client is not in connected state. + */ + unsubscribe(filter: string, unsubcribeOptions?: UnsubscribeOptions): void; + } + + /** + * An application message, sent or received. + */ + class Message { + /** + * mandatory The name of the destination to which the message is to be sent + * (for messages about to be sent) or the name of the destination from which the message has been received. + * (for messages received by the onMessage function). + */ + destinationName?: string; + + /** + * read only If true, this message might be a duplicate of one which has already been received. + * This is only set on messages received from the server. + */ + readonly duplicate: boolean; + + /** read only The payload as an ArrayBuffer. */ + readonly payloadBytes: ArrayBuffer; + + /** + * read only The payload as a string if the payload consists of valid UTF-8 characters. + * @throw {Error} if the payload is not valid UTF-8 + */ + readonly payloadString: string; + + /** + * The Quality of Service used to deliver the message. + *
    + *
    0 Best effort (default). + *
    1 At least once. + *
    2 Exactly once. + *
    + * + * @default 0 + */ + qos: number; + + /** + * If true, the message is to be retained by the server and delivered to both current and future + * subscriptions. If false the server only delivers the message to current subscribers, this is the default + * for new Messages. A received message has the retained boolean set to true if the message was published + * with the retained boolean set to true and the subscription was made after the message has been published. + * + * @default false + */ + retained: boolean; + + /** + * @param {String|ArrayBuffer} payload The message data to be sent. + */ + constructor(payload: string | ArrayBuffer); + } + } +} diff --git a/types/paho-mqtt/paho-mqtt-tests.ts b/types/paho-mqtt/paho-mqtt-tests.ts new file mode 100644 index 0000000000..b06c36cd0e --- /dev/null +++ b/types/paho-mqtt/paho-mqtt-tests.ts @@ -0,0 +1,87 @@ +let client = new Paho.MQTT.Client("ws://localhost/mqtt", "client-1"); +client = new Paho.MQTT.Client("localhost", 80, "client-2"); +client = new Paho.MQTT.Client("localhost", 80, "/mqtt", "client-3"); + +const willMsg = new Paho.MQTT.Message(""); + +declare var console: any; + +client.connect({ + timeout: 10, + userName: "username", + password: "pa$$word", + willMessage: willMsg, + keepAliveInterval: 10, + cleanSession: true, + useSSL: true, + invocationContext: { + asdf: true + }, + onSuccess: (o) => { + console.log("connected: ", o.invocationContext.asdf); + }, + mqttVersion: 3, + onFailure: (e) => { + console.error("could not connect: ", e.errorMessage); + }, + hosts: ["localhost", "8.8.8.8"], + ports: [80, 443], +}); + +console.log(`created new client on "${client.host}:${client.port}/${client.path}" with id "${client.clientId}"`); + +console.log(`connected?: ${client.isConnected()}`); + +client.trace = (msg) => { + console.log(`mqtt trace msg: ${msg}`); +}; + +client.startTrace(); +console.log(`trace log: ${client.getTraceLog()}`); +client.stopTrace(); + +client.onMessageArrived = (msg) => { + console.log(`arrived: ${msg.destinationName}: ${msg.payloadString}`); + console.log(`len: ${msg.payloadBytes.byteLength}, retained: ${msg.retained}, dup: ${msg.duplicate}, qos: ${msg.qos}`); +}; + +client.onConnectionLost = (err) => { + console.log(`connection lost (code ${err.errorCode}): ${err.errorMessage}`); +}; + +client.onMessageDelivered = (msg) => { + console.log(`delivered: ${msg.destinationName}: ${msg.payloadString}`); + console.log(`len: ${msg.payloadBytes.byteLength}, retained: ${msg.retained}, dup: ${msg.duplicate}, qos: ${msg.qos}`); +}; + +client.subscribe("test/topic", { + qos: 2, + invocationContext: { asdf: true }, + onSuccess: (o) => { + console.log(`subscribed: ${o.invocationContext.asdf}`); + }, + onFailure: (e) => { + console.error("error subscribing: ", e.errorMessage); + }, + timeout: 10, +}); + +client.unsubscribe("test/topic", { + invocationContext: { asdf: true }, + onSuccess: (o) => { + console.log(`subscribed: ${o.invocationContext.asdf}`); + }, + onFailure: (e) => { + console.error("error subscribing: ", e.errorMessage); + }, + timeout: 10, +}); + +client.send("test/topic2", "hello world!", 0, true); +client.send("test/topic3", "hello world 2!", 1); +client.send("test/topic4", new ArrayBuffer(3)); +const msg = new Paho.MQTT.Message(new ArrayBuffer(4)); +msg.destinationName = "test/topic5"; +msg.qos = 2; + +client.disconnect(); diff --git a/types/paho-mqtt/tsconfig.json b/types/paho-mqtt/tsconfig.json new file mode 100644 index 0000000000..e4666b9ef5 --- /dev/null +++ b/types/paho-mqtt/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "paho-mqtt-tests.ts" + ] +} diff --git a/types/paho-mqtt/tslint.json b/types/paho-mqtt/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/paho-mqtt/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/papaparse/index.d.ts b/types/papaparse/index.d.ts index 35353f3aba..bc1e1645a0 100644 --- a/types/papaparse/index.d.ts +++ b/types/papaparse/index.d.ts @@ -63,6 +63,7 @@ declare namespace PapaParse { interface ParseConfig { delimiter?: string; // default: "" newline?: string; // default: "" + quoteChar?: string; // default: '"' header?: boolean; // default: false dynamicTyping?: boolean; // default: false preview?: number; // default: 0 @@ -72,13 +73,14 @@ declare namespace PapaParse { download?: boolean; // default: false skipEmptyLines?: boolean; // default: false fastMode?: boolean; // default: undefined + withCredentials?: boolean; // default: undefined // Callbacks step?(results: ParseResult, parser: Parser): void; // default: undefined complete?(results: ParseResult, file?: File): void; // default: undefined error?(error: ParseError, file?: File): void; // default: undefined chunk?(results: ParseResult, parser: Parser): void; // default: undefined - beforeFirstChunk?(chunk: string): string | void; // default: undefined + beforeFirstChunk?(chunk: string): string | void; // default: undefined } interface UnparseConfig { diff --git a/types/parse/index.d.ts b/types/parse/index.d.ts index 95d173fffe..b4cd725529 100644 --- a/types/parse/index.d.ts +++ b/types/parse/index.d.ts @@ -327,11 +327,12 @@ declare namespace Parse { constructor(attributes?: string[], options?: any); static extend(className: string, protoProps?: any, classProps?: any): any; + static fromJSON(json: any, override: boolean): any; + static fetchAll(list: T[], options: SuccessFailureOptions): Promise; static fetchAllIfNeeded(list: T[], options: SuccessFailureOptions): Promise; static destroyAll(list: T[], options?: Object.DestroyAllOptions): Promise; static saveAll(list: T[], options?: Object.SaveAllOptions): Promise; - static registerSubclass(className: string, clazz: new (options?: any) => T): void; initialize(): void; diff --git a/types/parse/parse-tests.ts b/types/parse/parse-tests.ts index 282913d17e..ad1a2a2a83 100644 --- a/types/parse/parse-tests.ts +++ b/types/parse/parse-tests.ts @@ -56,6 +56,8 @@ function test_object() { gameScore.addUnique("skills", "kungfu"); game.set("gameScore", gameScore); + + var gameCopy = Game.fromJSON(JSON.parse(JSON.stringify(game)), true); } function test_query() { diff --git a/types/pdf/index.d.ts b/types/pdfjs-dist/index.d.ts similarity index 99% rename from types/pdf/index.d.ts rename to types/pdfjs-dist/index.d.ts index c3d7bc8788..31c9ed7800 100644 --- a/types/pdf/index.d.ts +++ b/types/pdfjs-dist/index.d.ts @@ -474,3 +474,8 @@ interface PDFJSStatic { } declare var PDFJS: PDFJSStatic; + +declare module "pdfjs-dist" { + export = PDFJS; +} + diff --git a/types/pdf/pdf-tests.ts b/types/pdfjs-dist/pdfjs-dist-tests.ts similarity index 100% rename from types/pdf/pdf-tests.ts rename to types/pdfjs-dist/pdfjs-dist-tests.ts diff --git a/types/pdf/tsconfig.json b/types/pdfjs-dist/tsconfig.json similarity index 93% rename from types/pdf/tsconfig.json rename to types/pdfjs-dist/tsconfig.json index ad7d35deb6..110e5b444a 100644 --- a/types/pdf/tsconfig.json +++ b/types/pdfjs-dist/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "pdf-tests.ts" + "pdfjs-dist-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/pg/pg-tests.ts b/types/pg/pg-tests.ts index 2fe301935a..73c18ac1b7 100644 --- a/types/pg/pg-tests.ts +++ b/types/pg/pg-tests.ts @@ -1,6 +1,4 @@ - import * as pg from "pg"; -import * as bluebird from "bluebird"; var conString = "postgres://username:password@localhost/database"; @@ -55,7 +53,7 @@ var config = { port: 5432, //env var: PGPORT max: 10, // max number of clients in the pool idleTimeoutMillis: 30000, // how long a client is allowed to remain idle before being closed - Promise: bluebird + Promise, }; var pool = new pg.Pool(config); diff --git a/types/pify/pify-tests.ts b/types/pify/pify-tests.ts index 2252005b85..87e1ba28ae 100644 --- a/types/pify/pify-tests.ts +++ b/types/pify/pify-tests.ts @@ -1,8 +1,4 @@ - -/// - import * as pify from 'pify'; -import * as Bluebird from 'bluebird'; function assert(actual: string, expected: string): void { if (actual !== expected) { @@ -28,4 +24,4 @@ const fsP = pify(fs); fsP.readFile('foo.txt').then((result: string) => assert(result, 'foo')); pify(fs.readFile)('foo.txt').then((result: string) => assert(result, 'foo')); -pify(fs.readFile, Bluebird)('bar.txt').then((result: string) => assert(result, 'bar')); \ No newline at end of file +pify(fs.readFile, Promise)('bar.txt').then((result: string) => assert(result, 'bar')); \ No newline at end of file diff --git a/types/plotly.js/index.d.ts b/types/plotly.js/index.d.ts index c35811aa4d..04de340c22 100644 --- a/types/plotly.js/index.d.ts +++ b/types/plotly.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for plotly.js 1.22 +// Type definitions for plotly.js 1.27 // Project: https://plot.ly/javascript/ // Definitions by: Chris Gervang , Martin Duparc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -40,11 +40,27 @@ declare namespace Plotly { 'xaxis.autorange': boolean; 'yaxis.autorange': boolean; shapes: Array>; + legend: Partial; + } + + interface Legend { + traceorder: "grouped" | "normal" | "reversed"; + x: number; + y: number; + font: Partial; + bgcolor: string; + bordercolor: string; + borderwidth: number; + orientation: "v" | "h"; + tracegroupgap: number; + xanchor: 'auto' | 'left' | 'center' | 'right'; + yanchor: 'auto' | 'top' | 'middle' | 'bottom'; } type AxisType = "date" | "log" | "linear"; interface Axis { + title: string; showgrid: boolean; fixedrange: boolean; rangemode: "tozero" | 'normal' | 'nonnegative'; @@ -104,7 +120,7 @@ declare namespace Plotly { type Dash = 'solid' | 'dot' | 'dash' | 'longdash' | 'dashdot' | 'longdashdot'; - type Data = ScatterData | BarData; + type Data = Partial | Partial; // Bar interface BarData { @@ -132,9 +148,10 @@ declare namespace Plotly { } interface ScatterMarker { - symbol: ""; // Drawing.symbolList - opacity: number; - size: number; + symbol: string | string[]; // Drawing.symbolList + color: string | string[]; + opacity: number | number[]; + size: number | number[]; maxdisplayed: number; sizeref: number; sizemin: number; diff --git a/types/popper.js/index.d.ts b/types/popper.js/index.d.ts index 96f93b3192..2af9ae2298 100644 --- a/types/popper.js/index.d.ts +++ b/types/popper.js/index.d.ts @@ -1,71 +1,103 @@ -// Type definitions for popper.js 1.8 +// Type definitions for popper.js 1.10 // Project: https://github.com/FezVrasta/popper.js/ -// Definitions by: rhysd , joscha , seckardt +// Definitions by: rhysd , joscha , seckardt , marcfallows // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace Popper { + type Position = 'top' | 'right' | 'bottom' | 'left'; + type Placement = 'auto-start' + | 'auto' + | 'auto-end' + | 'top-start' + | 'top' + | 'top-end' + | 'right-start' + | 'right' + | 'right-end' + | 'bottom-end' + | 'bottom' + | 'bottom-start' + | 'left-end' + | 'left' + | 'left-start'; interface PopperOptions { - placement?: string; - boundariesPadding?: number; - modifiers?: { - order?: number, - enabled?: boolean, - fn?: Function, - 'function'?: Function, - onLoad?: Function, - applyStyle?: { - gpuAcceleration?: boolean - }, - preventOverflow?: { - boundariesElement?: string | Element, - priority?: Array<'left' | 'right' | 'top' | 'bottom'> - }, - offset?: { - offset?: number | string - }, - flip?: { - behavior?: string | string[], - boundariesElement?: string | Element - }, - }; - modifiersIgnored?: string[]; + placement?: Placement; + eventsEnabled?: boolean; + modifiers?: Modifiers; removeOnDestroy?: boolean; - arrowElement?: string | Element; - onCreate?(data: Popper.Data): void; - onUpdate?(data: Popper.Data): void; + onCreate?(data: Data): void; + onUpdate?(data: Data): void; + } + type ModifierFn = (data: Data, options: Object) => Data; + interface BaseModifier { + order?: number; + enabled?: boolean; + fn?: ModifierFn; } class Modifiers { - applyStyle(data: Object): Object; - shift(data: Object): Object; - preventOverflow(data: Object): Object; - keepTogether(data: Object): Object; - flip(data: Object): Object; - offset(data: Object): Object; - arrow(data: Object): Object; + shift?: BaseModifier; + offset?: BaseModifier & { + offset?: number | string, + }; + preventOverflow?: BaseModifier & { + priority?: Position[], + padding?: number, + boundariesElement?: string | Element, + }; + keepTogether?: BaseModifier; + arrow?: BaseModifier & { + element?: string | Element, + }; + flip?: BaseModifier & { + behavior?: 'flip' | 'clockwise' | 'counterclockwise' | Position[], + padding?: number, + boundariesElement?: string | Element, + }; + inner?: BaseModifier; + hide?: BaseModifier; + applyStyle?: BaseModifier & { + onLoad?: Function, + gpuAcceleration?: boolean, + }; + } + interface Offset { + top: number; + left: number; + width: number; + height: number; } interface Data { - placement: string; + instance: Popper; + placement: Placement; + originalPlacement: Placement; + flipped: boolean; + hide: boolean; + arrowElement: Element; + styles: Object; + boundaries: Object; offsets: { - popper: { - position: string; - top: number; - left: number; - }; + popper: Offset, + reference: Offset, + arrow: { + top: number, + left: number, + }, }; } } declare class Popper { - modifiers: Popper.Modifiers; - placement: string; + static modifiers: Object[]; + static placements: Popper.Placement[]; + static Defaults: Popper.PopperOptions; constructor(reference: Element, popper: Element | Object, options?: Popper.PopperOptions); destroy(): void; update(): void; - parse(config: Object): Element; - runModifiers(data: Object, modifiers: string[], ends: Function): void; - isModifierRequired(): boolean; + scheduleUpdate(): void; + enableEventListeners(): void; + disableEventListeners(): void; } declare module 'popper.js' { diff --git a/types/popper.js/popper.js-tests.ts b/types/popper.js/popper.js-tests.ts index 143de99ccc..484e7b43ef 100644 --- a/types/popper.js/popper.js-tests.ts +++ b/types/popper.js/popper.js-tests.ts @@ -1,27 +1,89 @@ import Popper from 'popper.js'; var reference = document.querySelector('.my-button'); +var popper = document.querySelector('.my-popper'); +var boundary = document.querySelector('.my-boundary'); +var arrow = document.querySelector('.my-arrow'); + var thePopper = new Popper( - reference, { - content: 'My awesome popper!' - } + reference, + popper, ); thePopper.update(); +thePopper.scheduleUpdate(); thePopper.destroy(); +thePopper.enableEventListeners(); +thePopper.disableEventListeners(); -var options = { - placement: 'bottom', - offset: 0, - arrowElement: document.querySelector('.arrow'), - modifiersIgnored: ['applyStyle'], - } as Popper.PopperOptions; +Popper.modifiers.forEach(console.log.bind(console)); +Popper.placements.forEach(console.log.bind(console)); var thePopperWithOptions = new Popper( - reference, { - content: 'My awesome popper!', - }, options); + reference, + popper, + { + placement: 'bottom', + eventsEnabled: true, + removeOnDestroy: true, + modifiers: { + shift: { + enabled: true, + fn: (data) => data, + order: 100, + }, + offset: { + enabled: true, + fn: (data) => data, + order: 100, + offset: 0, + }, + preventOverflow: { + enabled: true, + fn: (data) => data, + order: 100, + priority: ['top', 'bottom'], + padding: 1, + boundariesElement: boundary, + }, + keepTogether: { + enabled: false, + fn: (data) => data, + order: 200, + }, + arrow: { + enabled: true, + fn: (data) => data, + order: 400, + element: arrow, + }, + flip: { + enabled: true, + fn: (data) => data, + order: 400, + behavior: ['top', 'right'], + padding: 5, + boundariesElement: boundary, + }, + inner: { + enabled: true, + fn: (data) => data, + order: 400, + }, + hide: { + enabled: true, + fn: (data) => data, + order: 400, + }, + applyStyle: { + enabled: true, + fn: (data) => data, + order: 400, + onLoad: () => 0, + }, + } + } +); -var popper = document.querySelector('.my-popper'); var anotherPopper = new Popper( reference, popper @@ -30,9 +92,15 @@ var anotherPopper = new Popper( var reference = document.querySelector('.my-button'); var popper = document.querySelector('.my-popper'); var anotherPopper = new Popper(reference, popper, { + modifiers: { + flip: { + behavior: 'clockwise' + } + }, onCreate: (data => console.log(data)), - onUpdate: ((data) => { + onUpdate: (data => { + data.instance.scheduleUpdate(); var p = data.offsets.popper; - console.log(`top: ${p.top}, left: ${p.left}`); + console.log(`top: ${p.top}, left: ${p.left}, width: ${p.width}, height: ${p.height}`); }) }); diff --git a/types/project-oxford/index.d.ts b/types/project-oxford/index.d.ts index db322e3fa8..5a85f26ad6 100644 --- a/types/project-oxford/index.d.ts +++ b/types/project-oxford/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/felixrieseberg/project-oxford // Definitions by: Scott Southwood // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/promise-dag/index.d.ts b/types/promise-dag/index.d.ts new file mode 100644 index 0000000000..d5c401a8c5 --- /dev/null +++ b/types/promise-dag/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for promise-dag 1.0 +// Project: https://github.com/vvvvalvalval/promise-dag#readme +// Definitions by: Sjoerd Diepen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type Step = string | ((...args: any[]) => PromiseLike); + +export type Run

    > = (steps: { [name: string]: Step[]; }, required?: string[]) => { [name: string]: P; }; + +export interface PromiseImplementation

    > { + resolve(value: any): P; + reject(value: any): P; + all(values: any[]): P; +} + +export const run: Run>; + +export function implement

    >(implementation: PromiseImplementation

    ): Run

    ; diff --git a/types/promise-dag/promise-dag-tests.ts b/types/promise-dag/promise-dag-tests.ts new file mode 100644 index 0000000000..4286915970 --- /dev/null +++ b/types/promise-dag/promise-dag-tests.ts @@ -0,0 +1,35 @@ +import * as promiseDag from "promise-dag"; + +// describe the computation as steps which depend on previous steps. +// in this cooking example, functions which return a promise are prefixed with `p_`. +const mushroomPastaRecipe = { + hotWater: [(): Promise => p_boilWater("1L")], + rawPasta: [(): Promise => p_pickIngredient("pasta")], + cookedPasta: ["hotWater", "rawPasta", (hotWater: string, rawPasta: string) => p_boil(hotWater, rawPasta, "10 minutes")], + + meal: ["cookedPasta", (preparedMeal: string): Promise => Promise.resolve(preparedMeal)] +}; + +const runCustomPromise = promiseDag.implement({ + resolve: (v: any): Promise => Promise.resolve(v), + reject: (err: any): Promise => Promise.resolve(err), + all: (ps: any[] | Array>): Promise => Promise.all(ps) +}); + +runCustomPromise(mushroomPastaRecipe, ["meal"])["meal"].then(eat); + +function eat(meal: string) { + let consume = `eating ${meal}`; +} + +function p_boilWater(volume: string): Promise { + return Promise.resolve(volume); +} + +function p_pickIngredient(ingredient: string): Promise { + return Promise.resolve(ingredient); +} + +function p_boil(volume: string, ingredient: string, duration: string): Promise { + return Promise.resolve(`cooked ${ingredient} in ${volume} for ${duration}`); +} diff --git a/types/promise-dag/tsconfig.json b/types/promise-dag/tsconfig.json new file mode 100644 index 0000000000..97423097e2 --- /dev/null +++ b/types/promise-dag/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "promise-dag-tests.ts" + ] +} diff --git a/types/promise-dag/tslint.json b/types/promise-dag/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/promise-dag/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/qlik-visualizationextensions/index.d.ts b/types/qlik-visualizationextensions/index.d.ts index d4296fca5b..741e9db805 100644 --- a/types/qlik-visualizationextensions/index.d.ts +++ b/types/qlik-visualizationextensions/index.d.ts @@ -2,6 +2,7 @@ // Project: http://help.qlik.com/en-US/sense-developer/3.2/Subsystems/Extensions/Content/extensions-introduction.htm // Definitions by: Konrad Mattheis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/qrcode.react/index.d.ts b/types/qrcode.react/index.d.ts index 4de6ba60db..7771e04293 100644 --- a/types/qrcode.react/index.d.ts +++ b/types/qrcode.react/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/zpao/qrcode.react // Definitions by: Mleko // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 /// diff --git a/types/quill/index.d.ts b/types/quill/index.d.ts index cf7440f428..73a877815f 100644 --- a/types/quill/index.d.ts +++ b/types/quill/index.d.ts @@ -7,7 +7,21 @@ declare namespace Quill { type Key = { key: string, shortKey?: boolean }; type Sources = "api" | "user" | "silent"; - type Formats = { [key: string]: any }; + type StringMap = { [key: string]: any }; + type OptionalAttributes = { attributes?: StringMap }; + /** + * A stricter type definition would be: + * + * type DeltaOperation ({ insert: any } | { delete: number } | { retain: number }) & OptionalAttributes; + * + * But this would break a lot of existing code as it would require manual discrimination of the union types. + */ + type DeltaOperation = { insert?: any, delete?: number, retain?: number } & OptionalAttributes; + + type TextChangeHandler = (delta: DeltaStatic, oldContents: DeltaStatic, source: Sources) => any; + type SelectionChangeHandler = (range: RangeStatic, oldRange: RangeStatic, source: Sources) => any; + type EditorChangeHandler = ((name: "text-change", delta: DeltaStatic, oldContents: DeltaStatic, source: Sources) => any) + | ((name: "selection-change", range: RangeStatic, oldRange: RangeStatic, source: Sources) => any); export interface KeyboardStatic { addBinding(key: Key, callback: (range: RangeStatic, context: any) => void): void; @@ -23,7 +37,7 @@ declare namespace Quill { export interface QuillOptionsStatic { debug?: string, - modules?: Formats, + modules?: StringMap, placeholder?: string, readOnly?: boolean, theme?: string, @@ -38,26 +52,26 @@ declare namespace Quill { } export interface DeltaStatic { - new (ops: Array) : DeltaStatic; - new (ops: any) : DeltaStatic; - ops?: Array; - retain(length: number, attributes: any) : DeltaStatic; + new (ops?: DeltaOperation[] | { ops: DeltaOperation[] }) : DeltaStatic; + ops?: DeltaOperation[]; + retain(length: number, attributes?: StringMap) : DeltaStatic; delete(length: number) : DeltaStatic; - filter(predicate: any) : DeltaStatic; - forEach(predicate: any) : DeltaStatic; - insert(text: any, attributes: any): DeltaStatic; - map(predicate: any) : DeltaStatic; - partition(predicate: any) : DeltaStatic; - reduce(predicate: any, initial: number): DeltaStatic; + filter(predicate: (op: DeltaOperation) => boolean) : DeltaOperation[]; + forEach(predicate: (op: DeltaOperation) => void) : void; + insert(text: any, attributes?: StringMap): DeltaStatic; + map(predicate: (op: DeltaOperation) => T) : T[]; + partition(predicate: (op: DeltaOperation) => boolean) : [DeltaOperation[], DeltaOperation[]]; + reduce(predicate: (acc: T, curr: DeltaOperation, idx: number, arr: DeltaOperation[]) => T, initial: T): T; chop() : DeltaStatic; length(): number; - slice(start: number, end: number): DeltaStatic; - compose(other: any): DeltaStatic; + slice(start?: number, end?: number): DeltaStatic; + compose(other: DeltaStatic): DeltaStatic; concat(other: DeltaStatic): DeltaStatic; - diff(other: DeltaStatic, index: number) : DeltaStatic; - eachLine(predicate: any, newline: any) : DeltaStatic; - transform(other: any, priority: any) : DeltaStatic; - transformPosition(index: number, priority: any) : DeltaStatic; + diff(other: DeltaStatic, index?: number) : DeltaStatic; + eachLine(predicate: (line: DeltaStatic, attributes: StringMap, idx: number) => any, newline?: string) : DeltaStatic; + transform(index: number) : number; + transform(other: DeltaStatic, priority: boolean) : DeltaStatic; + transformPosition(index: number) : number; } export interface RangeStatic { @@ -66,7 +80,19 @@ declare namespace Quill { length: number; } - export interface Quill { + export interface EventEmitter { + on(eventName: "text-change", handler: TextChangeHandler): EventEmitter; + on(eventName: "selection-change", handler: SelectionChangeHandler): EventEmitter; + on(eventName: "editor-change", handler: EditorChangeHandler): EventEmitter; + once(eventName: "text-change", handler: TextChangeHandler): EventEmitter; + once(eventName: "selection-change", handler: SelectionChangeHandler): EventEmitter; + once(eventName: "editor-change", handler: EditorChangeHandler): EventEmitter; + off(eventName: "text-change", handler: TextChangeHandler): EventEmitter; + off(eventName: "selection-change", handler: SelectionChangeHandler): EventEmitter; + off(eventName: "editor-change", handler: EditorChangeHandler): EventEmitter; + } + + export interface Quill extends EventEmitter { new (container: string | Element, options?: QuillOptionsStatic): Quill; deleteText(index: number, length: number, source?: Sources): void; disable(): void; @@ -77,7 +103,7 @@ declare namespace Quill { insertEmbed(index: number, type: string, value: any, source?: Sources): void; insertText(index: number, text: string, source?: Sources): DeltaStatic; insertText(index: number, text: string, format: string, value: any, source?: Sources): DeltaStatic; - insertText(index: number, text: string, formats: Formats, source?: Sources): DeltaStatic; + insertText(index: number, text: string, formats: StringMap, source?: Sources): DeltaStatic; /** * @deprecated Use clipboard.dangerouslyPasteHTML(index: number, html: string, source: Sources) */ @@ -94,12 +120,12 @@ declare namespace Quill { format(name: string, value: any, source?: Sources): DeltaStatic; formatLine(index: number, length: number, source?: Sources): DeltaStatic; formatLine(index: number, length: number, format: string, value: any, source?: Sources): DeltaStatic; - formatLine(index: number, length: number, formats: Formats, source?: Sources): DeltaStatic; + formatLine(index: number, length: number, formats: StringMap, source?: Sources): DeltaStatic; formatText(index: number, length: number, source?: Sources): DeltaStatic; formatText(index: number, length: number, format: string, value: any, source?: Sources): DeltaStatic; - formatText(index: number, length: number, formats: Formats, source?: Sources): DeltaStatic; - getFormat(range?: RangeStatic): Formats; - getFormat(index: number, length?: number): Formats; + formatText(index: number, length: number, formats: StringMap, source?: Sources): DeltaStatic; + getFormat(range?: RangeStatic): StringMap; + getFormat(index: number, length?: number): StringMap; removeFormat(index: number, length: number, source?: Sources): void; blur(): void; @@ -110,15 +136,10 @@ declare namespace Quill { setSelection(index: number, length: number, source?: Sources): void; setSelection(range: RangeStatic, source?: Sources): void; - on(eventName: string, callback: ((delta: T, oldContents: T, source: string) => void) | - ((name: string, ...args: any[]) => void)): Quill; - once(eventName: string, callback: (delta: DeltaStatic, source: string) => void): Quill; - off(eventName: string, callback: (delta: DeltaStatic, source: string) => void): Quill; - debug(level: string): void; import(path: string): any; register(path: string, def: any, suppressWarning?: boolean): void; - register(defs: Formats, suppressWarning?: boolean): void; + register(defs: StringMap, suppressWarning?: boolean): void; addContainer(className: string, refNode?: any): any; addContainer(domNode: any, refNode?: any): any; getModule(name: string): any diff --git a/types/quill/quill-tests.ts b/types/quill/quill-tests.ts index eba77f8b68..f45781a685 100644 --- a/types/quill/quill-tests.ts +++ b/types/quill/quill-tests.ts @@ -168,12 +168,22 @@ function test_addContainer() quillEditor.addContainer('ql-custom'); } -function test_on_EventType1(){ - var quillEditor = new Quill('#editor'); - quillEditor.on('text-change', (newDelta: T, oldDelta: T, source: string)=>{ - // happened - }); +function test_on_Events(){ + var textChangeHandler = function(newDelta: Quill.DeltaStatic, oldDelta: Quill.DeltaStatic, source: string) { }; + var selectionChangeHandler = function(newRange: Quill.RangeStatic, oldRange: Quill.RangeStatic, source: string) { }; + var editorChangeHandler = function(name: string, ...args: any[]) { }; + var quillEditor = new Quill('#editor'); + quillEditor + .on('text-change', textChangeHandler) + .off('text-change', textChangeHandler) + .once('text-change', textChangeHandler) + .on('selection-change', selectionChangeHandler) + .off('selection-change', selectionChangeHandler) + .once('selection-change', selectionChangeHandler) + .on('editor-change', editorChangeHandler) + .off('editor-change', editorChangeHandler) + .once('editor-change', editorChangeHandler); } function test_PasteHTML() @@ -187,3 +197,141 @@ function test_PasteHTML2() var quillEditor = new Quill('#editor'); quillEditor.pasteHTML(5, '

    Quill Rocks

    '); } + +function test_DeltaChaining() { + var delta = new Delta() + .insert('Hello', { bold: true }) + .insert('World') + .delete(5) + .retain(5) + .retain(5, { color: '#0c6' }); + +} + +function test_DeltaFilter() { + var delta = new Delta().insert('Hello', { bold: true }) + .insert({ image: 'https://octodex.github.com/images/labtocat.png' }) + .insert('World!'); + + var text = delta.filter(function(op) { + return typeof op.insert === 'string'; + }).map(function(op) { + return op.insert; + }).join(''); +} + +function test_DeltaForEach() { + var delta = new Delta(); + delta.forEach(function(op) { + console.log(op); + }); +} + +function test_DeltaMap() { + var delta = new Delta() + .insert('Hello', { bold: true }) + .insert({ image: 'https://octodex.github.com/images/labtocat.png' }) + .insert('World!'); + + var text = delta.map(function(op) { + if (typeof op.insert === 'string') { + return op.insert; + } else { + return ''; + } + }).join(''); +} + +function test_DeltaPartition() { + var delta = new Delta().insert('Hello', { bold: true }) + .insert({ image: 'https://octodex.github.com/images/labtocat.png' }) + .insert('World!'); + + var results = delta.partition(function(op) { + return typeof op.insert === 'string'; + }); + var passed = results[0]; // [{ insert: 'Hello', attributes: { bold: true }}, { insert: 'World'}] + var failed = results[1]; // [{ insert: { image: 'https://octodex.github.com/images/labtocat.png' }}] +} + +function test_DeltaReduce() { + var delta = new Delta().insert('Hello', { bold: true }) + .insert({ image: 'https://octodex.github.com/images/labtocat.png' }) + .insert('World!'); + + var length = delta.reduce(function(length, op) { + return length + (op.insert.length || 1); + }, 0); +} + +function test_DeltaSlice() { + var delta = new Delta().insert('Hello', { bold: true }).insert(' World'); + + // { + // ops: [ + // { insert: 'Hello', attributes: { bold: true } }, + // { insert: ' World' } + // ] + // } + var copy = delta.slice(); + console.log(copy.ops); + + // { ops: [{ insert: 'World' }] } + var world = delta.slice(6); + console.log(world.ops); + + // { ops: [{ insert: ' ' }] } + var space = delta.slice(5, 6); + console.log(space.ops); +} + +function test_DeltaCompose() { + var a = new Delta().insert('abc'); + var b = new Delta().retain(1).delete(1); + + var composed = a.compose(b); // composed == new Delta().insert('ac'); +} + +function test_DeltaDiff() { + var a = new Delta().insert('Hello'); + var b = new Delta().insert('Hello!'); + + var diff = a.diff(b); // { ops: [{ retain: 5 }, { insert: '!' }] } + // a.compose(diff) == b + var diff2 = a.diff(b, 0); // { ops: [{ retain: 5 }, { insert: '!' }] } + // a.compose(diff) == b +} + +function test_DeltaEachLine() { + var delta = new Delta().insert('Hello\n\n') + .insert('World') + .insert({ image: 'octocat.png' }) + .insert('\n', { align: 'right' }) + .insert('!'); + + delta.eachLine(function(line, attributes, i) { + console.log(line, attributes, i); + // Can return false to exit loop early + }); + // Should log: + // { ops: [{ insert: 'Hello' }] }, {}, 0 + // { ops: [] }, {}, 1 + // { ops: [{ insert: 'World' }, { insert: { image: 'octocat.png' } }] }, { align: 'right' }, 2 + // { ops: [{ insert: '!' }] }, {}, 3 +} + +function test_DeltaTransform() { + var a = new Delta().insert('a'); + var b = new Delta().insert('b').retain(5).insert('c'); + + var d1: Quill.DeltaStatic = a.transform(b, true); // new Delta().retain(1).insert('b').retain(5).insert('c'); + var d2: Quill.DeltaStatic = a.transform(b, false); // new Delta().insert('b').retain(6).insert('c'); + var n1: number = a.transform(5); + +} + +function test_DeltatransformPosition() { + var delta = new Delta().retain(5).insert('a'); + var n1: number = delta.transformPosition(4); // 4 + var n2: number = delta.transformPosition(5); // 6 +} diff --git a/types/quill/tsconfig.json b/types/quill/tsconfig.json index 5c353f17a3..cfef2d65ab 100644 --- a/types/quill/tsconfig.json +++ b/types/quill/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/radium/index.d.ts b/types/radium/index.d.ts index 58f9045923..b875d797e3 100644 --- a/types/radium/index.d.ts +++ b/types/radium/index.d.ts @@ -2,10 +2,9 @@ // Project: https://github.com/formidablelabs/radium // Definitions by: Alex Gorbatchev , Philipp Holzer , Alexey Svetliakov , Mikael Hermansson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 -import React = require('react'); -import ReactComponent = React.Component; +import * as React from 'react'; export = Radium; @@ -37,7 +36,7 @@ declare namespace Radium { /** *