diff --git a/notNeededPackages.json b/notNeededPackages.json index c5173ffc24..306865851b 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -186,6 +186,12 @@ "sourceRepoURL": "https://github.com/loopline-systems/electron-builder", "asOfVersion": "2.8.0" }, + { + "libraryName": "error-stack-parser", + "typingsPackageName": "error-stack-parser", + "sourceRepoURL": "https://github.com/stacktracejs/error-stack-parser", + "asOfVersion": "2.0.0" + }, { "libraryName": "eventemitter2", "typingsPackageName": "eventemitter2", diff --git a/types/angular-hotkeys/README.md b/types/angular-hotkeys/README.md deleted file mode 100644 index a31ed8a936..0000000000 --- a/types/angular-hotkeys/README.md +++ /dev/null @@ -1,55 +0,0 @@ -## What is it? - -This is a typescript interface to be used with [angular-hotkeys](https://github.com/chieffancypants/angular-hotkeys/). - -## What are declaration files? - -See the [TypeScript handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html). - - -## How do I get them? - -### npm - -This is the preferred method. This is only available for TypeScript 2.0+ users. For these typings: - -```sh -npm install --save-dev @types/angular-hotkeys -``` - -The types should then be automatically included by the compiler. -See more in the [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html). - - -### Other methods - -These can be used by TypeScript 1.0. - -* [Typings](https://github.com/typings/typings) -* ~~[NuGet](http://nuget.org/Tpackages?q=DefinitelyTyped)~~ (use preferred alternatives, nuget DT type publishing has been turned off) -* Manually download from the `master` branch of this repository - -You may need to add manual [references](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html). - -## How to use - -After installing a package you can import the definition file and begin using it as so: - -```ts - -import * as hotkeys from '../../node_modules/@types/angular-hotkeys' - -class FooController { - static $inject = [ - 'hotkeys' - ]; - - constructor( - private hotkeys: ng.hotkeys.HotkeysProvider - ) { } -} - -``` - -for a detailed explanation of the behavior of angular-hotkeys please refer to [its documentation](https://github.com/chieffancypants/angular-hotkeys/) - diff --git a/types/angular-hotkeys/angular-hotkeys-tests.ts b/types/angular-hotkeys/angular-hotkeys-tests.ts index c0bd9b974d..503080e9d8 100644 --- a/types/angular-hotkeys/angular-hotkeys-tests.ts +++ b/types/angular-hotkeys/angular-hotkeys-tests.ts @@ -1,30 +1,67 @@ -var scope: ng.IScope; -var hotkeyProvider: ng.hotkeys.HotkeysProvider; -var hotkeyObj: ng.hotkeys.Hotkey; +import { HotkeysProvider, Hotkey } from 'angular-hotkeys'; +import { module } from 'angular'; -hotkeyProvider.add("mod+s", "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => {} ); -hotkeyProvider.add(["mod+s"], "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => {} ); -hotkeyProvider.add(hotkeyObj); -hotkeyProvider.bindTo(scope); -hotkeyProvider.del("mod+s"); -hotkeyProvider.del(["mod+s"]); -hotkeyProvider.get("mod+s"); -hotkeyProvider.get(["mod+s"]); -hotkeyProvider.toggleCheatSheet(); - -hotkeyProvider.add(hotkeyObj.combo, hotkeyObj.description ,hotkeyObj.callback); - -hotkeyProvider.bindTo(scope) - .add(hotkeyObj) - .add(hotkeyObj) - .add({ - combo: 'w', - description: 'blah blah', - callback: function() {} - }) - .add({ - combo: ['w', 'mod+w'], - description: 'blah blah', - callback: function() {} +module('myApp', ['cfp.hotkeys']) + .config((hotkeysProvider: HotkeysProvider) => { + hotkeysProvider.includeCheatSheet = false; + const somehotKeyObj: Hotkey = { + combo: '', + callback: () => { } + }; }); +function someInjectionService( + scope: ng.IScope, + hotkeyProvider: ng.hotkeys.HotkeysProvider, + hotkeyObj: ng.hotkeys.Hotkey +) { + hotkeyProvider.add("mod+s", "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => { }); + hotkeyProvider.add(["mod+s"], "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => { }); + hotkeyProvider.add(hotkeyObj); + hotkeyProvider.bindTo(scope); + hotkeyProvider.del("mod+s"); + hotkeyProvider.del(["mod+s"]); + hotkeyProvider.get("mod+s"); + hotkeyProvider.get(["mod+s"]); + hotkeyProvider.toggleCheatSheet(); + + hotkeyProvider.add(hotkeyObj.combo, hotkeyObj.description, hotkeyObj.callback); + + hotkeyProvider.bindTo(scope) + .add(hotkeyObj) + .add(hotkeyObj) + .add({ + combo: 'w', + description: 'blah blah', + callback: () => { } + }) + .add({ + combo: ['w', 'mod+w'], + description: 'blah blah', + callback: () => { } + }); + + hotkeyProvider.add({ + combo: 'ctrl+w', + description: 'Description goes here', + callback: (event, hotkey) => { + event.preventDefault(); + } + }); + + hotkeyProvider.add({ + combo: 'ctrl+x', + callback: (event, hotkey) => { + // + } + }); + + hotkeyProvider.add({ + combo: 'ctrl+w', + description: 'Description goes here', + allowIn: ['INPUT', 'SELECT', 'TEXTAREA'], + callback(event, hotkey) { + event.preventDefault(); + } + }); +} diff --git a/types/angular-hotkeys/index.d.ts b/types/angular-hotkeys/index.d.ts index 0f0be68d8e..360e2cefbe 100644 --- a/types/angular-hotkeys/index.d.ts +++ b/types/angular-hotkeys/index.d.ts @@ -1,12 +1,10 @@ -// Type definitions for angular-hotkeys +// Type definitions for angular-hotkeys 1.7 // Project: https://github.com/chieffancypants/angular-hotkeys -// Definitions by: Jason Zhao , Stefan Steinhart +// Definitions by: Jason Zhao +// Stefan Steinhart +// Cyril Gandon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -//readme written by David Valentine - - -/// import * as ng from 'angular'; @@ -15,46 +13,123 @@ export type HotkeysProviderChained = ng.hotkeys.HotkeysProviderChained; export type Hotkey = ng.hotkeys.Hotkey; declare module 'angular' { - export namespace hotkeys { - + namespace hotkeys { interface HotkeysProvider { - template: string; - templateTitle: string; + /** + * Configurable setting to disable the cheatsheet entirely. + * @default true + */ includeCheatSheet: boolean; + /** + * Configurable setting to disable ngRoute hooks. + */ + useNgRoute: boolean; + /** + * Configurable setting for the cheat sheet title + * @default 'Keyboard Shortcuts' + */ + templateTitle: string; + /** + * Configurable settings for the cheat sheet header in HTML. + * This overrides the normal title if specified. + * @default null + */ + templateHeader: string | null; + /** + * Configurable settings for the cheat sheet footer in HTML. + * @default null + */ + templateFooter: string | null; + /** + * Cheat sheet template in the event you want to totally customize it. + */ + template: string; + /** + * Configurable setting for the cheat sheet hotkey. + * @default '?' + */ cheatSheetHotkey: string; + /** + * Configurable setting for the cheat sheet description. + * @default 'Show / hide this help menu' + */ cheatSheetDescription: string; - add(combo: string | string[], callback: (event: Event, hotkey?: Hotkey) => void, action?: string, allowIn?: Array, persistent?: boolean): ng.hotkeys.Hotkey; + /** + * Creates a new Hotkey and creates the Mousetrap binding. + */ + add(combo: string | string[], description?: string, callback?: (event: Event, hotkey: Hotkey) => void, action?: string, allowIn?: string[], persistent?: boolean): Hotkey; - add(combo: string | string[], description: string, callback: (event: Event, hotkey?: Hotkey) => void, action?: string, allowIn?: Array, persistent?: boolean): ng.hotkeys.Hotkey; + /** + * Creates a new Hotkey and creates the Mousetrap binding. + */ + add(hotkeyObj: Hotkey): Hotkey; - add(hotkeyObj: ng.hotkeys.Hotkey): ng.hotkeys.Hotkey; + /** + * Binds the hotkey to a particular scope. + * Useful if the scope is destroyed, we can automatically destroy the hotkey binding. + * @param scope The scope to bind to + */ + bindTo(scope: IScope): HotkeysProviderChained; - bindTo(scope: ng.IScope): ng.hotkeys.HotkeysProviderChained; + /** + * Removes and unbinds a hotkey + * @param combo The keyboard combo (shortcut) or the HotKey object + */ + del(combo: string | string[] | Hotkey): void; - del(combo: string | string[]): void; - - del(hotkeyObj: ng.hotkeys.Hotkey): void; - - get(combo: string | string[]): ng.hotkeys.Hotkey; + /** + * Returns the Hotkey object + * @param combo The keyboard combo (shortcut) + */ + get(combo: string | string[]): Hotkey; + /** + * Toggles the help menu element's visiblity + */ toggleCheatSheet(): void; - + /** + * Purges all non-persistent hotkeys (such as those defined in routes) + * + * Without this, the same hotkey would get recreated everytime + * the route is accessed. + */ purgeHotkeys(): void; } interface HotkeysProviderChained { - add(combo: string | string[], description: string, callback: (event: Event, hotkeys: ng.hotkeys.Hotkey) => void): HotkeysProviderChained; + add(combo: string | string[], description: string, callback: (event: Event, hotkeys: Hotkey) => void): HotkeysProviderChained; - add(hotkeyObj: ng.hotkeys.Hotkey): HotkeysProviderChained; + add(hotkeyObj: Hotkey): HotkeysProviderChained; } interface Hotkey { + /** + * They keyboard combo (shortcut) you want to bind to. + */ combo: string | string[]; + /** + * The description for what the combo does and is only used for the Cheat Sheet. + * If it is not supplied, it will not show up, and in effect, allows you to have unlisted hotkeys. + */ description?: string; - callback: (event: Event, hotkey: ng.hotkeys.Hotkey) => void; + /** + * The function to execute when the key(s) are pressed. Passes along two arguments, event and hotkey + */ + callback(event: Event, hotkey: Hotkey): void; + /** + * The type of event to listen for, such as keypress, keydown or keyup. + * Usage of this parameter is discouraged as the underlying library will pick the most suitable option automatically. + * This should only be necessary in advanced situations. + */ action?: string; - allowIn?: Array; + /** + * An array of tag names to allow this combo in ('INPUT', 'SELECT', and/or 'TEXTAREA') + */ + allowIn?: Array<'INPUT' | 'SELECT' | 'TEXTAREA'>; + /** + * Whether the hotkey persists navigation events + */ persistent?: boolean; } } diff --git a/types/angular-hotkeys/tsconfig.json b/types/angular-hotkeys/tsconfig.json index f277241888..acb11ff247 100644 --- a/types/angular-hotkeys/tsconfig.json +++ b/types/angular-hotkeys/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -21,4 +21,4 @@ "index.d.ts", "angular-hotkeys-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/angular-hotkeys/tslint.json b/types/angular-hotkeys/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/angular-hotkeys/tslint.json +++ b/types/angular-hotkeys/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/arr-union/arr-union-tests.ts b/types/arr-union/arr-union-tests.ts new file mode 100644 index 0000000000..7e46a3787e --- /dev/null +++ b/types/arr-union/arr-union-tests.ts @@ -0,0 +1,7 @@ +import union = require('arr-union'); + +// $ExpectType string[] +union(['a'], ['b', 'c'], ['d', 'e', 'f']); + +// $ExpectType number[] +union([1, 1], [2, 3]); diff --git a/types/arr-union/index.d.ts b/types/arr-union/index.d.ts new file mode 100644 index 0000000000..5893a55361 --- /dev/null +++ b/types/arr-union/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for arr-union 3.1 +// Project: https://github.com/jonschlinkert/arr-union +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function union(...arrays: Array>): T[]; + +export = union; diff --git a/types/arr-union/tsconfig.json b/types/arr-union/tsconfig.json new file mode 100644 index 0000000000..64a3b1efed --- /dev/null +++ b/types/arr-union/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "arr-union-tests.ts" + ] +} diff --git a/types/arr-union/tslint.json b/types/arr-union/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/arr-union/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index 57ca68a915..d24cb40081 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -529,8 +529,8 @@ export class ManagementClient { deleteEmailProvider(): Promise; deleteEmailProvider(cb?: (err: Error, data: any) => void): void; - updateEmailProvider(data: Data): Promise; - updateEmailProvider(data: Data, cb?: (err: Error, data: any) => void): void; + updateEmailProvider(params: {}, data: Data): Promise; + updateEmailProvider(params: {}, data: Data, cb?: (err: Error, data: any) => void): void; // Statistics diff --git a/types/backbone/backbone-tests.ts b/types/backbone/backbone-tests.ts index 1772ec5b89..7b6fad9b56 100644 --- a/types/backbone/backbone-tests.ts +++ b/types/backbone/backbone-tests.ts @@ -159,6 +159,9 @@ function test_collection() { var book1: Book = new Book({ title: "Title 1", author: "Mike" }); books.add(book1); + // Test adding sort option to add. + books.add(new Book(), { sort: true }); + // Objects can be added to collection by casting to model type. // Compiler will check if object properties are valid for the cast. // This gives better type checking than declaring an `any` overload. @@ -190,6 +193,7 @@ function test_collection() { let modelsDict: _.Dictionary; let num: number; + models = books.slice(); models = books.slice(1); models = books.slice(1, 3); @@ -405,6 +409,12 @@ namespace v1Changes { validate: false }); } + + function test_set() { + var collection = new EmployeeCollection(); + var model = new Employee(); + collection.set([model], { add: false, remove: true, merge: false }); + } } namespace Router { @@ -415,4 +425,10 @@ namespace v1Changes { router.navigate('/employees', true); } } + + namespace Sync { + // Test for Backbone.sync override. + Backbone.sync('create', new Employee()); + Backbone.sync('read', new EmployeeCollection()); + } } diff --git a/types/backbone/index.d.ts b/types/backbone/index.d.ts index 04f3024e98..607f6413fc 100644 --- a/types/backbone/index.d.ts +++ b/types/backbone/index.d.ts @@ -16,6 +16,13 @@ declare namespace Backbone { interface AddOptions extends Silenceable { at?: number; merge?: boolean; + sort?: boolean; + } + + interface CollectionSetOptions extends Silenceable { + add?: boolean; + remove?: boolean; + merge?: boolean; } interface HistoryOptions extends Silenceable { @@ -243,7 +250,19 @@ declare namespace Backbone { remove(model: {}|TModel, options?: Silenceable): TModel; remove(models: ({}|TModel)[], options?: Silenceable): TModel[]; reset(models?: TModel[], options?: Silenceable): TModel[]; - set(models?: TModel[], options?: Silenceable): TModel[]; + + /** + * + * The set method performs a "smart" update of the collection with the passed list of models. + * If a model in the list isn't yet in the collection it will be added; if the model is already in the + * collection its attributes will be merged; and if the collection contains any models that aren't present + * in the list, they'll be removed. All of the appropriate "add", "remove", and "change" events are fired as + * this happens. Returns the touched models in the collection. If you'd like to customize the behavior, you can + * disable it with options: {add: false}, {remove: false}, or {merge: false}. + * @param models + * @param options + */ + set(models?: TModel[], options?: CollectionSetOptions): TModel[]; shift(options?: Silenceable): TModel; sort(options?: Silenceable): Collection; unshift(model: TModel, options?: AddOptions): TModel; @@ -259,7 +278,7 @@ declare namespace Backbone { /** * Return a shallow copy of this collection's models, using the same options as native Array#slice. */ - slice(min: number, max?: number): TModel[]; + slice(min?: number, max?: number): TModel[]; // mixins from underscore @@ -442,6 +461,7 @@ declare namespace Backbone { // SYNC function sync(method: string, model: Model, options?: JQueryAjaxSettings): any; + function sync(method: string, collection: Collection, options?: JQueryAjaxSettings): any; function ajax(options?: JQueryAjaxSettings): JQueryXHR; var emulateHTTP: boolean; var emulateJSON: boolean; diff --git a/types/baconjs/baconjs-tests.ts b/types/baconjs/baconjs-tests.ts index d39a4fd466..2755bec595 100644 --- a/types/baconjs/baconjs-tests.ts +++ b/types/baconjs/baconjs-tests.ts @@ -188,10 +188,10 @@ function CommonMethodsInEventStreamsAndProperties() { return adds.takeUntil(cancel).map(x => x.val); }; - Bacon.sequentially(2, events) + Bacon.sequentially(2, events) .groupBy(keyF, limitF) .flatMap(groupedStream => groupedStream.fold(0, (acc, x) => acc + x)) - .onValue(sum => { + .onValue((sum: number) => { console.log(sum); // returns [-1, 2, 8] in an order }); } diff --git a/types/bash-glob/bash-glob-tests.ts b/types/bash-glob/bash-glob-tests.ts new file mode 100644 index 0000000000..cf63412653 --- /dev/null +++ b/types/bash-glob/bash-glob-tests.ts @@ -0,0 +1,21 @@ +import bashGlob = require('bash-glob'); + +bashGlob('pattern', (err, files) => {}); +bashGlob(['pattern'], (err, files) => {}); +bashGlob(['pattern'], {}, (err, files) => {}); +bashGlob(['pattern'], { cwd: 'cwd' }, (err, files) => { }); + +bashGlob.on('match', (match, cwd) => {}); +bashGlob.on('files', (files, cwd) => {}); +bashGlob.on('end', (files) => {}); + +bashGlob.each('pattern', (err, files) => {}); +bashGlob.each(['pattern'], (err, files) => {}); +bashGlob.each(['pattern'], {}, (err, files) => {}); +bashGlob.each(['pattern'], { cwd: 'cwd' }, (err, files) => {}); + +// $ExpectType string[] +bashGlob.sync('pattern'); +bashGlob.sync(['pattern']); +bashGlob.sync(['pattern'], {}); +bashGlob.sync(['pattern'], { cwd: 'cwd' }); diff --git a/types/bash-glob/index.d.ts b/types/bash-glob/index.d.ts new file mode 100644 index 0000000000..29582ea9bd --- /dev/null +++ b/types/bash-glob/index.d.ts @@ -0,0 +1,36 @@ +// Type definitions for bash-glob 2.0 +// Project: https://github.com/micromatch/bash-glob +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type Patterns = string | string[]; +type Callback = (err: Error, files: string[]) => void; + +declare function bashGlob(pattern: Patterns, callback: Callback): void; +declare function bashGlob(pattern: Patterns, options: bashGlob.Options, callback: Callback): void; + +declare namespace bashGlob { + interface Options { + cwd?: string; + dot?: boolean; + dotglob?: boolean; + extglob?: boolean; + failglob?: boolean; + globstar?: boolean; + nocase?: boolean; + nocaseglob?: boolean; + nullglob?: boolean; + } + + function on(event: 'match' | 'files', callback: (files: string, cwd: string) => void): void; + function on(event: 'end', callback: (files: string) => void): void; + + function each(patterns: Patterns, callback: Callback): void; + function each(patterns: Patterns, options: Options, callback: Callback): void; + + function promise(patterns: Patterns, options?: Options): Promise; + + function sync(patterns: Patterns, options?: Options): string[]; +} + +export = bashGlob; diff --git a/types/bash-glob/tsconfig.json b/types/bash-glob/tsconfig.json new file mode 100644 index 0000000000..6a45a2d74d --- /dev/null +++ b/types/bash-glob/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bash-glob-tests.ts" + ] +} diff --git a/types/bash-glob/tslint.json b/types/bash-glob/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/bash-glob/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/benchmark/benchmark-tests.ts b/types/benchmark/benchmark-tests.ts index 8fbe2b1d92..cb02940b37 100644 --- a/types/benchmark/benchmark-tests.ts +++ b/types/benchmark/benchmark-tests.ts @@ -229,6 +229,27 @@ suite.add({ 'onComplete': onComplete }); +// unregister a listener for an event type +suite.off('cycle', listener) as Benchmark.Suite; + +// unregister a listener for multiple event types +suite.off('start cycle', listener) as Benchmark.Suite; + +// unregister all listeners for an event type +suite.off('cycle') as Benchmark.Suite; + +// unregister all listeners for multiple event types +suite.off('start cycle complete') as Benchmark.Suite; + +// unregister all listeners for all event types +suite.off() as Benchmark.Suite; + +// register a listener for an event type +suite.on('cycle', listener) as Benchmark.Suite; + +// register a listener for multiple event types +suite.on('start cycle', listener) as Benchmark.Suite; + // basic usage suite.run(); diff --git a/types/benchmark/index.d.ts b/types/benchmark/index.d.ts index 01bb379a48..d8c72aef68 100644 --- a/types/benchmark/index.d.ts +++ b/types/benchmark/index.d.ts @@ -170,10 +170,10 @@ declare namespace Benchmark { join(separator?: string): string; listeners(type: string): Function[]; map(callback: Function): any[]; - off(type?: string, callback?: Function): Benchmark; - off(types: string[]): Benchmark; - on(type?: string, callback?: Function): Benchmark; - on(types: string[]): Benchmark; + off(type?: string, callback?: Function): Suite; + off(types: string[]): Suite; + on(type?: string, callback?: Function): Suite; + on(types: string[]): Suite; pluck(property: string): any[]; pop(): Function; push(benchmark: Benchmark): number; diff --git a/types/better-scroll/better-scroll-tests.ts b/types/better-scroll/better-scroll-tests.ts new file mode 100644 index 0000000000..1c8f336f4f --- /dev/null +++ b/types/better-scroll/better-scroll-tests.ts @@ -0,0 +1,70 @@ +import BScroll = require("better-scroll"); + +const BScroll1 = new BScroll('#wrapper'); +const BScroll2 = new BScroll('#wrapper', { scrollX: false, scrollY: false }); +const BScroll3 = new BScroll('#wrapper', { + snap: true, + wheel: false, + scrollbar: false, + pullDownRefresh: false, +}); +const BScroll4 = new BScroll('#wrapper', { + wheel: { + selectedIndex: 0, + }, +}); +if (document.querySelector('div-test')) { + const BScroll6 = new BScroll('#wrapper', { + snap: { + loop: false, + el: document.querySelector('div-test')!, + threshold: 0.1, + stepX: 100, + stepY: 100, + listenFlick: true, + }, + }); +} +const BScroll7 = new BScroll('#wrapper', { + scrollbar: { + fade: true, + }, +}); + +const BScroll8 = new BScroll('#wrapper', { + pullDownRefresh: { + threshold: 50, + stop: 20, + }, +}); + +BScroll1.refresh(); +BScroll1.scrollTo(0, 100); +BScroll1.scrollTo(0, 100, 200); + +BScroll1.scrollToElement('selectedElement'); +BScroll1.scrollToElement('selectedElement', 250); + +BScroll1.scrollToElement(document.getElementById('selectedElement')!); +BScroll1.scrollToElement(document.getElementById('selectedElement')!, 250); + +BScroll2.on('scrollStart', () => { console.log('scroll started'); }); + +const BScroll9 = new BScroll(document.getElementById('wrapper')!); +const BScroll10 = new BScroll(document.getElementById('wrapper')!, { freeScroll: true }); +const BScroll11 = new BScroll(document.getElementById('wrapper')!, { + preventDefaultException: { + tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT)$/, + }, +}); +const BScroll12 = new BScroll(document.getElementById('wrapper')!, { + preventDefaultException: { + className: /(^|\s)test(\s|$)/, + }, +}); + +const BScroll13 = new BScroll(document.getElementById('wrapper')!, { + swipeBounceTime: 1000, +}); + +const BScroll14 = new BScroll('#wrapper', { disableMouse: true, disableTouch: false }); diff --git a/types/better-scroll/index.d.ts b/types/better-scroll/index.d.ts new file mode 100644 index 0000000000..559b21bba2 --- /dev/null +++ b/types/better-scroll/index.d.ts @@ -0,0 +1,148 @@ +// Type definitions for better-scroll.js 1.3 +// Project: https://github.com/ustbhuangyi/better-scroll +// Definitions by: linxiaowu66 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 +interface WheelOption { + selectedIndex?: number; + rotate?: number; + adjustTime?: number; +} + +interface SlideOption { + loop?: boolean; + el?: Element; + threshold?: number; + stepX?: number; + stepY?: number; + listenFlick?: boolean; +} +interface ScrollBarOption { + fade?: boolean; +} +interface PullDownOption { + threshold?: number; + stop?: number; +} +interface PullUpOption { + threshold?: number; +} +interface BsOption { + startX?: number; + startY?: number; + scrollX?: boolean; + scrollY?: boolean; + freeScroll?: boolean; + directionLockThreshold?: number; + eventPassthrough?: string | boolean; + click?: boolean; + tap?: boolean; + bounce?: boolean; + bounceTime?: number; + momentum?: boolean; + momentumLimitTime?: number; + momentumLimitDistance?: number; + swipeTime?: number; + swipeBounceTime?: number; + deceleration?: number; + flickLimitTime?: number; + flickLimitDistance?: number; + resizePolling?: number; + probeType?: number; + preventDefault?: boolean; + preventDefaultException?: object; + HWCompositing?: boolean; + useTransition?: boolean; + useTransform?: boolean; + bindToWrapper?: boolean; + disableMouse?: boolean; + disableTouch?: boolean; + /** + * for picker + * wheel: { + * selectedIndex: 0; + * rotate: 25; + * adjustTime: 400 + * } + */ + wheel?: WheelOption | boolean; + /** + * for slide + * snap: { + * loop?: boolean; + * el: domEl; + * threshold: 0.1; + * stepX: 100; + * stepY: 100; + * listenFlick: true + * } + */ + snap?: SlideOption | boolean; + /** + * for scrollbar + * scrollbar: { + * fade: true + * } + */ + scrollbar?: ScrollBarOption | boolean; + /** + * for pull down and refresh + * pullDownRefresh: { + * threshold: 50; + * stop: 20 + * } + */ + pullDownRefresh?: PullDownOption | boolean; + /** + * for pull up and load + * pullUpLoad: { + * threshold: 50 + * } + */ + pullUpLoad?: PullUpOption | boolean; +} +declare class BScroll { + constructor(element: Element | string, options?: BsOption); + // 重新计算 better-scroll,当 DOM 结构发生变化的时候务必要调用确保滚动的效果正常 + x: number; + y: number; + + refresh(): void; + // 启用 better-scroll; 默认 开启 + enable(): void; + // 禁用 better-scroll,DOM 事件(如 touchstart、touchmove、touchend)的回调函数不再响应 + disable(): void; + // 相对于当前位置偏移滚动 x;y 的距离 + scrollBy(x: number, y: number, time?: number, easing?: object): void; + // 滚动到指定的位置 + scrollTo(x: number, y: number, time?: number, easing?: object): void; + // 滚动到指定的目标元素 + scrollToElement(el: HTMLElement | string, time?: number, offsetX?: number | boolean, offsetY?: number | boolean, easing?: object): void; + // 立即停止当前运行的滚动动画 + stop(): void; + // 销毁 better-scroll,解绑事件 + destroy(): void; + + // 当我们做 slide 组件的时候,slide 通常会分成多个页面。调用此方法可以滚动到指定的页面。 + goToPage(x: number, y: number, time?: number, easing?: object): void; + // 滚动到下一个页面 + next(time: number, easing: object): void; + // 滚动到上一个页面 + prev(time: number, easing: object): void; + // 获取当前页面的信息 + getCurrentPage(): void; + // 当我们做 picker 组件的时候,调用该方法可以滚动到索引对应的位置 + wheelTo(index: number): void; + // 获取当前选中的索引值 + getSelectedIndex(): void; + // 当下拉刷新数据加载完毕后,需要调用此方法告诉 better-scroll 数据已加载 + finishPullDown(): void; + // 当上拉加载数据加载完毕后,需要调用此方法告诉 better-scroll 数据已加载 + finishPullUp(): void; + + // 监听事件 + on(type: string, fn: (evt?: any) => void): void; + off(type: string, fn?: (evt?: any) => void): void; +} + +export = BScroll; diff --git a/types/better-scroll/tsconfig.json b/types/better-scroll/tsconfig.json new file mode 100644 index 0000000000..774ffc076f --- /dev/null +++ b/types/better-scroll/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "better-scroll-tests.ts" + ] +} \ No newline at end of file diff --git a/types/better-scroll/tslint.json b/types/better-scroll/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/better-scroll/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/blessed/blessed-tests.ts b/types/blessed/blessed-tests.ts index b143703b18..c5f857146f 100644 --- a/types/blessed/blessed-tests.ts +++ b/types/blessed/blessed-tests.ts @@ -1,150 +1,138 @@ -import * as blessed from 'blessed' +import * as blessed from "blessed"; +import { readFileSync } from "fs"; let screen: blessed.Widgets.Screen = null; // https://github.com/chjj/blessed/blob/master/test/widget-autopad.js screen = blessed.screen({ - dump: __dirname + '/logs/autopad.log', + dump: __dirname + "/logs/autopad.log", smartCSR: true, autoPadding: true, warnings: true }); -var box1 = blessed.box({ +const box1 = blessed.box({ parent: screen, - top: 'center', - left: 'center', + top: "center", + left: "center", width: 20, height: 10, - border: 'line' + border: "line" }); -var box2 = blessed.box({ +const box2 = blessed.box({ parent: box1, top: 0, left: 0, width: 10, height: 5, - border: 'line' + border: "line" }); -screen.key('q', function() { - return screen.destroy(); -}); +screen.key("q", () => screen.destroy()); screen.render(); // https://github.com/chjj/blessed/blob/master/test/widget-bigtext.js screen = blessed.screen({ - dump: __dirname + '/logs/bigtext.log', + dump: __dirname + "/logs/bigtext.log", smartCSR: true, warnings: true }); -var box = blessed.bigtext({ +const box3 = blessed.bigtext({ parent: screen, - content: 'Hello', + content: "Hello", shrink: true, - width: '80%', + width: "80%", // height: '80%', - height: 'shrink', + height: "shrink", // width: 'shrink', - border: 'line', - fch: ' ', - ch: '\u2592', + border: "line", + fch: " ", + ch: "\u2592", style: { - fg: 'red', - bg: 'blue', + fg: "red", + bg: "blue", bold: false } }); -screen.key('q', function() { - return screen.destroy(); -}); +screen.key("q", () => screen.destroy()); screen.render(); // https://github.com/chjj/blessed/blob/master/test/widget-csr.js screen = blessed.screen({ - dump: __dirname + '/logs/csr.log', + dump: __dirname + "/logs/csr.log", smartCSR: true, warnings: true }); +const lorem = readFileSync(__dirname + "/git.diff", "utf8"); -var lorem = require('fs').readFileSync(__dirname + '/git.diff', 'utf8'); - -var cleanSides = screen.cleanSides; +const cleanSides = screen.cleanSides; function expectClean(value: any) { - screen.cleanSides = function(el: blessed.widget.Element) { - var ret = cleanSides.apply(this, arguments); + screen.cleanSides = function(el: blessed.Widgets.BlessedElement) { + const ret = cleanSides.apply(this, arguments); if (ret !== value) { - throw new Error('Failed. Expected ' - + value + ' from cleanSides. Got ' - + ret + '.'); + throw new Error(`Failed. Expected ${value} from cleanSides. Got ${ret}.`); } return ret; }; } -var btext = blessed.box({ +const btext = blessed.box({ parent: screen, - left: 'center', - top: 'center', - width: '80%', - height: '80%', + left: "center", + top: "center", + width: "80%", + height: "80%", style: { - bg: 'green' + bg: "green" }, - border: 'line', - content: 'CSR should still work.' + border: "line", + content: "CSR should still work." }); -let _oscroll = btext.scroll; -btext.scroll = function(offset, always) { +btext.scroll = (offset, always) => { expectClean(true); - return _oscroll(offset, always); }; -var text = blessed.scrollabletext({ +const text = blessed.scrollabletext({ parent: screen, content: lorem, - border: 'line', - left: 'center', - top: 'center', + border: "line", + left: "center", + top: "center", draggable: true, - width: '50%', - height: '50%', + width: "50%", + height: "50%", mouse: true, keys: true, vi: true }); -_oscroll = text.scroll; text.scroll = function(offset, always) { - var el = this; - var value = true; + const el = this; + let value = true; if (el.left < 0) value = true; if (el.top < 0) value = false; if (el.left + el.width > screen.width) value = true; if (el.top + el.height > screen.height) value = false; expectClean(value); - return _oscroll(offset, always); }; text.focus(); -screen.key('q', function() { - return screen.destroy(); -}); +screen.key("q", () => screen.destroy()); screen.render(); // https://github.com/chjj/blessed/blob/master/test/widget-dock-noborder.js screen = blessed.screen({ - dump: __dirname + '/logs/dock.log', + dump: __dirname + "/logs/dock.log", smartCSR: true, dockBorders: true, warnings: true @@ -154,85 +142,85 @@ blessed.box({ parent: screen, left: -1, top: -1, - width: '50%+1', - height: '50%+1', - border: 'line', - content: 'Foo' + width: "50%+1", + height: "50%+1", + border: "line", + content: "Foo" }); blessed.box({ parent: screen, - left: '50%-1', + left: "50%-1", top: -1, - width: '50%+3', - height: '50%+1', - content: 'Bar', - border: 'line' + width: "50%+3", + height: "50%+1", + content: "Bar", + border: "line" }); blessed.box({ parent: screen, left: -1, - top: '50%-1', - width: '50%+1', - height: '50%+3', - border: 'line', - content: 'Foo' + top: "50%-1", + width: "50%+1", + height: "50%+3", + border: "line", + content: "Foo" }); -blessed.listtable({ - parent: screen, - left: '50%-1', - top: '50%-1', - width: '50%+3', - height: '50%+3', - border: 'line', - align: 'center', - tags: true, - keys: true, - vi: true, - mouse: true, - style: { - header: { - fg: 'blue', - bold: true - }, - cell: { - fg: 'magenta', - selected: { - bg: 'blue' +blessed + .listtable({ + parent: screen, + left: "50%-1", + top: "50%-1", + width: "50%+3", + height: "50%+3", + border: "line", + align: "center", + tags: true, + keys: true, + vi: true, + mouse: true, + style: { + header: { + fg: "blue", + bold: true + }, + cell: { + fg: "magenta", + selected: { + bg: "blue" + } } - } - }, - data: [ - [ 'Animals', 'Foods', 'Times', 'Numbers' ], - [ 'Elephant', 'Apple', '1:00am', 'One' ], - [ 'Bird', 'Orange', '2:15pm', 'Two' ], - [ 'T-Rex', 'Taco', '8:45am', 'Three' ], - [ 'Mouse', 'Cheese', '9:05am', 'Four' ] - ] -}).focus(); + }, + data: [ + ["Animals", "Foods", "Times", "Numbers"], + ["Elephant", "Apple", "1:00am", "One"], + ["Bird", "Orange", "2:15pm", "Two"], + ["T-Rex", "Taco", "8:45am", "Three"], + ["Mouse", "Cheese", "9:05am", "Four"] + ] + }) + .focus(); -screen.key('q', function() { - return screen.destroy(); -}); +screen.key("q", () => screen.destroy()); screen.render(); // https://raw.githubusercontent.com/chjj/blessed/master/example/simple-form.js -var form = blessed.form({ +const form = blessed.form({ parent: screen, keys: true, left: 0, top: 0, width: 30, height: 4, - bg: 'green', - content: 'Submit or cancel?' + bg: "green", + content: "Submit or cancel?" }); -var submit = blessed.button({ +const submit = blessed.button({ parent: form, mouse: true, keys: true, @@ -243,20 +231,20 @@ var submit = blessed.button({ left: 10, top: 2, shrink: true, - name: 'submit', - content: 'submit', + name: "submit", + content: "submit", style: { - bg: 'blue', + bg: "blue", focus: { - bg: 'red' + bg: "red" }, hover: { - bg: 'red' + bg: "red" } } }); -var cancel = blessed.button({ +const cancel = blessed.button({ parent: form, mouse: true, keys: true, @@ -267,15 +255,15 @@ var cancel = blessed.button({ left: 20, top: 2, shrink: true, - name: 'cancel', - content: 'cancel', + name: "cancel", + content: "cancel", style: { - bg: 'blue', + bg: "blue", focus: { - bg: 'red' + bg: "red" }, hover: { - bg: 'red' + bg: "red" } } }); @@ -283,314 +271,306 @@ var cancel = blessed.button({ // https://github.com/chjj/blessed/blob/master/test/widget-layout.js screen = blessed.screen({ - dump: __dirname + '/logs/layout.log', + dump: __dirname + "/logs/layout.log", smartCSR: true, autoPadding: true, warnings: true }); -var layout = blessed.layout({ +const layout = blessed.layout({ parent: screen, - top: 'center', - left: 'center', - width: '50%', - height: '50%', - border: 'line', - layout: process.argv[2] === 'grid' ? 'grid' : 'inline', + top: "center", + left: "center", + width: "50%", + height: "50%", + border: "line", + layout: process.argv[2] === "grid" ? "grid" : "inline", style: { - bg: 'red', + bg: "red", border: { - fg: 'blue' + fg: "blue" } } }); -var box1 = blessed.box({ +blessed.box({ parent: layout, - top: 'center', - left: 'center', + top: "center", + left: "center", width: 20, height: 10, - border: 'line', - content: '1' + border: "line", + content: "1" }); -var box2 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '2' + border: "line", + content: "2" }); -var box3 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '3' + border: "line", + content: "3" }); -var box4 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '4' + border: "line", + content: "4" }); -var box5 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '5' + border: "line", + content: "5" }); -var box6 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '6' + border: "line", + content: "6" }); -var box7 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '7' + border: "line", + content: "7" }); -var box8 = blessed.box({ +blessed.box({ parent: layout, - top: 'center', - left: 'center', + top: "center", + left: "center", width: 20, height: 10, - border: 'line', - content: '8' + border: "line", + content: "8" }); -var box9 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '9' + border: "line", + content: "9" }); -var box10 = blessed.box({ +blessed.box({ parent: layout, - top: 'center', - left: 'center', + top: "center", + left: "center", width: 20, height: 10, - border: 'line', - content: '10' + border: "line", + content: "10" }); -var box11 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '11' + border: "line", + content: "11" }); -var box12 = blessed.box({ +const box12 = blessed.box({ parent: layout, - top: 'center', - left: 'center', + top: "center", + left: "center", width: 20, height: 10, - border: 'line', - content: '12' + border: "line", + content: "12" }); -if (process.argv[2] !== 'grid') { - for (var i = 0; i < 10; i++) { +if (process.argv[2] !== "grid") { + for (let i = 0; i < 10; i++) { blessed.box({ parent: layout, // width: i % 2 === 0 ? 10 : 20, // height: i % 2 === 0 ? 5 : 10, width: Math.random() > 0.5 ? 10 : 20, height: Math.random() > 0.5 ? 5 : 10, - border: 'line', - content: (i + 1 + 12) + '' + border: "line", + content: String(i + 1 + 12) }); } } -screen.key('q', function() { - return screen.destroy(); -}); +screen.key("q", () => screen.destroy()); screen.render(); // https://github.com/chjj/blessed/blob/master/test/widget-form.js screen = blessed.screen({ - dump: __dirname + '/logs/form.log', + dump: __dirname + "/logs/form.log", warnings: true }); -type FormData = { - radio1: boolean; - radio2: boolean; - text: string; - check: boolean; -}; +interface FormData { + radio1: boolean; + radio2: boolean; + text: string; + check: boolean; +} -var form2 = blessed.form({ +const form2 = blessed.form({ parent: screen, mouse: true, keys: true, vi: true, left: 0, top: 0, - width: '100%', - //height: 12, + width: "100%", style: { - bg: 'green', + bg: "green", border: { - inverse: true + inverse: true }, scrollbar: { inverse: true } }, - content: 'foobar', + content: "foobar", scrollable: true, scrollbar: { - ch: ' ' + ch: " " } - //alwaysScroll: true }); -form2.on('submit', (data) => { +form2.on("submit", data => { output.setContent(JSON.stringify(data, null, 2)); screen.render(); }); -form2.key('d', function() { +form2.key("d", () => { form2.scroll(1, true); screen.render(); }); -form2.key('u', function() { +form2.key("u", () => { form2.scroll(-1, true); screen.render(); }); -var set = blessed.radioset({ +const set = blessed.radioset({ parent: form2, left: 1, top: 1, shrink: true, - //padding: 1, - //content: 'f', style: { - bg: 'magenta' + bg: "magenta" } }); -var radio1 = blessed.radiobutton({ +const radio1 = blessed.radiobutton({ parent: set, mouse: true, keys: true, shrink: true, style: { - bg: 'magenta' + bg: "magenta" }, height: 1, left: 0, top: 0, - name: 'radio1', - content: 'radio1' + name: "radio1", + content: "radio1" }); -var radio2 = blessed.radiobutton({ +const radio2 = blessed.radiobutton({ parent: set, mouse: true, keys: true, shrink: true, style: { - bg: 'magenta' + bg: "magenta" }, height: 1, left: 15, top: 0, - name: 'radio2', - content: 'radio2' + name: "radio2", + content: "radio2" }); -var text2 = blessed.textbox({ +const text2 = blessed.textbox({ parent: form2, mouse: true, keys: true, style: { - bg: 'blue' + bg: "blue" }, height: 1, width: 20, left: 1, top: 3, - name: 'text' + name: "text" }); -text2.on('focus', function() { - text2.readInput(); -}); +text2.on("focus", () => text2.readInput()); -var check = blessed.checkbox({ +const check = blessed.checkbox({ parent: form2, mouse: true, keys: true, shrink: true, style: { - bg: 'magenta' + bg: "magenta" }, height: 1, left: 28, top: 1, - name: 'check', - content: 'check' + name: "check", + content: "check" }); -var check2 = blessed.checkbox({ +const check2 = blessed.checkbox({ parent: form2, mouse: true, keys: true, shrink: true, style: { - bg: 'magenta' + bg: "magenta" }, height: 1, left: 28, top: 14, - name: 'foooooooo2', - content: 'foooooooo2' + name: "foooooooo2", + content: "foooooooo2" }); -var submit = blessed.button({ +const submit2 = blessed.button({ parent: form2, mouse: true, keys: true, @@ -601,69 +581,67 @@ var submit = blessed.button({ }, left: 29, top: 3, - name: 'submit', - content: 'submit', + name: "submit", + content: "submit", style: { - bg: 'blue', + bg: "blue", focus: { - bg: 'red' + bg: "red" } } }); -submit.on('press', function() { - form2.submit(); -}); +submit.on("press", () => form2.submit()); -var box1 = blessed.box({ +const box5 = blessed.box({ parent: form2, left: 1, top: 10, height: 10, width: 10, - content: 'one', + content: "one", style: { - bg: 'cyan' + bg: "cyan" } }); -var box2 = blessed.box({ - parent: box1, +const box6 = blessed.box({ + parent: box5, left: 1, top: 2, height: 8, width: 9, - content: 'two', + content: "two", style: { - bg: 'magenta' + bg: "magenta" } }); -var box3 = blessed.box({ - parent: box2, +const box7 = blessed.box({ + parent: box6, left: 1, top: 2, height: 6, width: 8, - content: 'three', + content: "three", style: { - bg: 'yellow' + bg: "yellow" } }); -var box4 = blessed.box({ - parent: box3, +blessed.box({ + parent: box7, left: 1, top: 2, height: 4, width: 7, - content: 'four', + content: "four", style: { - bg: 'blue' + bg: "blue" } }); -var output = blessed.scrollabletext({ +const output = blessed.scrollabletext({ parent: form2, mouse: true, keys: true, @@ -672,26 +650,24 @@ var output = blessed.scrollabletext({ height: 5, right: 0, style: { - bg: 'red' + bg: "red" }, - content: 'foobar' + content: "foobar" }); -var bottom = blessed.line({ +const bottom = blessed.line({ parent: form2, - type: 'line', - orientation: 'horizontal', + type: "line", + orientation: "horizontal", left: 0, right: 0, top: 50, style: { - fg: 'blue' + fg: "blue" } }); -screen.key('q', function() { - return screen.destroy(); -}); +screen.key("q", () => screen.destroy()); form2.focus(); @@ -702,70 +678,68 @@ screen.render(); // https://github.com/chjj/blessed/blob/master/test/widget-table.js screen = blessed.screen({ - dump: __dirname + '/logs/table.log', + dump: __dirname + "/logs/table.log", autoPadding: false, fullUnicode: true, warnings: true }); -var DU = '杜'; -var JUAN = '鹃'; +const DU = "杜"; +const JUAN = "鹃"; -var table = blessed.table({ - //parent: screen, - top: 'center', - left: 'center', +const table = blessed.table({ + // parent: screen, + top: "center", + left: "center", data: null, - border: 'line', - align: 'center', + border: "line", + align: "center", tags: true, - //width: '80%', - width: 'shrink', + // width: '80%', + width: "shrink", style: { border: { - fg: 'red' + fg: "red" }, header: { - fg: 'blue', + fg: "blue", bold: true }, cell: { - fg: 'magenta' + fg: "magenta" } } }); -var data1 = [ - [ 'Animals', 'Foods', 'Times' ], - [ 'Elephant', 'Apple', '1:00am' ], - [ 'Bird', 'Orange', '2:15pm' ], - [ 'T-Rex', 'Taco', '8:45am' ], - [ 'Mouse', 'Cheese', '9:05am' ] +const data1 = [ + ["Animals", "Foods", "Times"], + ["Elephant", "Apple", "1:00am"], + ["Bird", "Orange", "2:15pm"], + ["T-Rex", "Taco", "8:45am"], + ["Mouse", "Cheese", "9:05am"] ]; -data1[1][0] = '{red-fg}' + data1[1][0] + '{/red-fg}'; -data1[2][0] += ' (' + DU + JUAN + ')'; +data1[1][0] = `{red-fg} ${data1[1][0]} {/red-fg}`; +data1[2][0] += ` (${DU}${JUAN})`; -var data2 = [ - [ 'Animals', 'Foods', 'Times', 'Numbers' ], - [ 'Elephant', 'Apple', '1:00am', 'One' ], - [ 'Bird', 'Orange', '2:15pm', 'Two' ], - [ 'T-Rex', 'Taco', '8:45am', 'Three' ], - [ 'Mouse', 'Cheese', '9:05am', 'Four' ] +const data2 = [ + ["Animals", "Foods", "Times", "Numbers"], + ["Elephant", "Apple", "1:00am", "One"], + ["Bird", "Orange", "2:15pm", "Two"], + ["T-Rex", "Taco", "8:45am", "Three"], + ["Mouse", "Cheese", "9:05am", "Four"] ]; -data2[1][0] = '{red-fg}' + data2[1][0] + '{/red-fg}'; -data2[2][0] += ' (' + DU + JUAN + ')'; +data2[1][0] = `{red-fg} ${data2[1][0]} {/red-fg}`; +data2[2][0] += ` (${DU}${JUAN})`; -screen.key('q', function() { - return screen.destroy(); -}); +screen.key("q", () => screen.destroy()); table.setData(data2); screen.append(table); screen.render(); -setTimeout(function() { +setTimeout(() => { table.setData(data1); screen.render(); }, 3000); diff --git a/types/blessed/index.d.ts b/types/blessed/index.d.ts index 553942af2f..9098648240 100644 --- a/types/blessed/index.d.ts +++ b/types/blessed/index.d.ts @@ -1,2837 +1,3033 @@ -// Type definitions for blessed 0.1.6 +// Type definitions for blessed 0.1 // Project: https://github.com/chjj/blessed -// Definitions by: bryn austin bellomy +// Definitions by: Bryn Austin Bellomy , Steve Kellock // Definitions: https://github.com/borisyankov/DefinitelyTyped +// TypeScript Version: 2.1 -/// +/// -import { EventEmitter } from 'events'; +import { EventEmitter } from "events"; import * as stream from "stream"; import * as child_process from "child_process"; -declare namespace Blessed { - export class BlessedProgram { - hideCursor: () => void; - move: any; - showCursor: any; - } +export class BlessedProgram { + hideCursor: () => void; + move: any; + showCursor: any; +} - export module Widgets { +export namespace Widgets { + namespace Types { + type TTopLeft = string | number | "center"; - export module Types { + type TPosition = string | number; - export type TTopLeft = string | number | "center"; + type TMouseAction = "mousedown" | "mouseup" | "mousemove"; - export type TPosition = string | number; - - export type TMouseAction = "mousedown" | "mouseup" | "mousemove"; - - export type TStyle = { - type?: string; - bg?: string; - fg?: string; - ch?: string; - bold?: boolean; - underline?: boolean; - blink?: boolean; - inverse?: boolean; - invisible?: boolean; - transparent?: boolean; - border?: "line" | "bg" | TBorder; - hover?: boolean; - focus?: boolean; - label?: string; - track?: {bg?: string; fg?: string;}; - scrollbar?: {bg?: string; fg?: string;}; - } - - export type TBorder = { - /** - * Type of border (line or bg). bg by default. - */ - type?: "line" | "bg"; - /** - * Character to use if bg type, default is space. - */ - ch?: string; - /** - * Border foreground and background, must be numbers (-1 for default). - */ - bg?: number; - fg?: number; - /** - * Border attributes. - */ - bold?: string; - underline?: string; - } - - export type TCursor = { - /** - * Have blessed draw a custom cursor and hide the terminal cursor (experimental). - */ - artificial: boolean; - /** - * Shape of the cursor. Can be: block, underline, or line. - */ - shape: 'block'|'underline'|'line'; - /** - * Whether the cursor blinks. - */ - blink: boolean; - /** - * Color of the color. Accepts any valid color value (null is default). - */ - color: string; - } - - export type TAlign = "left" | "center" | "right"; - - export type ListbarCommand = { - key: string; - callback: () => void; - }; - - export type TImage = { - /** - * Pixel width. - */ - width: number; - /** - * Pixel height. - */ - height: number; - /** - * Image bitmap. - * */ - bmp: any; - /** - * Image cellmap (bitmap scaled down to cell size). - */ - cellmap: any; - }; - - export type Cursor = { - /** - * Have blessed draw a custom cursor and hide the terminal cursor (experimental). - */ - artificial: boolean; - /** - * Shape of the cursor. Can be: block, underline, or line. - */ - shape: boolean; - /** - * Whether the cursor blinks. - */ - blink: boolean; - /** - * Color of the color. Accepts any valid color value (null is default). - */ - color: string; - } - } - - export module Events { - - export interface IMouseEventArg { - x: number; - y: number; - action: Types.TMouseAction; - } - - export interface IKeyEventArg { - full: string; - name: string; - shift: boolean; - ctrl: boolean; - meta: boolean; - sequence: string; - } - } - - export interface NodeChildProcessExecOptions { - cwd?: string; - stdio?: any; - customFds?: any; - env?: any; - encoding?: string; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - } - - export interface IDestroyable { - destroy(): void; - } - - export interface IOptions { - } - - export interface IHasOptions { - options: T; - } - - export interface TputsOptions extends IOptions { - terminal?: string; - extended?: boolean; - debug?: boolean; - termcap?: string; - terminfoFile?: string; - terminfoPrefix?: string; - termcapFile?: string; - } - - export class Tput implements IHasOptions { - constructor(opts: TputsOptions); - - // ** properties ** // - - /** - * Original options object. - */ - options: TputsOptions; - - debug: boolean; - padding: boolean; - extended: boolean; - printf: boolean; - termcap: string; - terminfoPrefix: string; - terminfoFile: string; - termcapFile: string; - error: Error; - terminal: string; - - setup(): void; - term(is: any): boolean; - readTerminfo(term: string): string; - parseTerminfo(data: any, file: string): { - header: { - dataSize: number; - headerSize: number; - magicNumber: boolean; - namesSize: number; - boolCount: number; - numCount: number; - strCount: number; - strTableSize: number; - extended: { - dataSize: number; - headerSize: number; - boolCount: number; - numCount: number; - strCount: number; - strTableSize: number; - lastStrTableOffset: number; - } - } - name: string; - names: string[]; - desc: string; - bools: Object; - numbers: Object; - strings: Object; - }; - } - - export interface IDestroyable { - destroy(): void; - } - - export interface INodeOptions extends IOptions { - name?: string; - screen?: Screen; - parent?: Node; - children?: Node[]; - focusable?: boolean; - } - - export abstract class Node extends EventEmitter implements IHasOptions, IDestroyable { - constructor(options: INodeOptions); - - // ** properties ** // - - focusable: boolean; - - /** - * Original options object. - */ - options: INodeOptions; - - /** - * An object for any miscellanous user data. - */ - data: {[index: string]: any;}; - /** - * An object for any miscellanous user data. - */ - _: {[index: string]: any;}; - /** - * An object for any miscellanous user data. - */ - $: {[index: string]: any;}; - /** - * Type of the node (e.g. box). - */ - type: string; - /** - * Render index (document order index) of the last render call. - */ - index: number; - /** - * Parent screen. - */ - screen: Screen; - /** - * Parent node. - */ - parent: Node; - /** - * Array of node's children. - */ - children: Node[]; - - // ** methods ** // - - /** - * Prepend a node to this node's children. - */ - prepend(node: Node): void; - /** - * Append a node to this node's children. - */ - append(node: Node): void; - /** - * Remove child node from node. - */ - remove(node: Node): void; - /** - * Insert a node to this node's children at index i. - */ - insert(node: Node, index: number): void; - /** - * Insert a node to this node's children before the reference node. - */ - insertBefore(node: Node, refNode: Node): void; - /** - * Insert a node from node after the reference node. - */ - insertAfter(node: Node, refNode: Node): void; - /** - * Remove node from its parent. - */ - detach(): void; - /** - * Remove node from its parent. - */ - free(): void; - /** - * Remove node from its parent. - */ - forDescendants(iter: Function, s: any): void; - /** - * Remove node from its parent. - */ - forAncestors(iter: Function, s: any): void; - /** - * Remove node from its parent. - */ - collectDescendants(s: any): void; - /** - * Remove node from its parent. - */ - collectAncestors(s: any): void; - /** - * Remove node from its parent. - */ - emitDescendants(): void; - /** - * Remove node from its parent. - */ - emitAncestors(): void; - /** - * Remove node from its parent. - */ - hasDescendant(target: Node): void; - /** - * Remove node from its parent. - */ - hasAncestor(target: Node): boolean; - /** - * Remove node from its parent. - */ - destroy(): void; - /** - * Emit event for element, and recursively emit same event for all descendants. - */ - emitDescendants(type: string, ...args: any[]): void; - /** - * Get user property with a potential default value. - */ - get(name: string, def: T): T; - /** - * Set user property to value. - */ - set(name: string, value: T): void; - - // ** events ** // - - on(event: string, listener: Function): this; - /** - * Received when node is added to a parent. - */ - on(event: "adopt", callback: (arg: Node) => void): this; - /** - * Received when node is removed from it's current parent. - */ - on(event: "remove", callback: (arg: Node) => void): this; - /** - * Received when node gains a new parent. - */ - on(event: "reparent", callback: (arg: Node) => void): this; - /** - * Received when node is attached to the screen directly or somewhere in its ancestry. - */ - on(event: "attach", callback: (arg: Node) => void): this; - /** - * Received when node is detached from the screen directly or somewhere in its ancestry. - */ - on(event: "detach", callback: (arg: Node) => void): this; - } - - export class NodeWithEvents extends Node { - // ** methods ** // - - /** - * Bind a keypress listener for a specific key. - */ - key(name: string | string[], listener: Function): void; - /** - * Bind a keypress listener for a specific key once. - */ - onceKey(name: string, listener: Function): void; - /** - * Remove a keypress listener for a specific key. - */ - unkey(name: string, listener: Function): void; - removeKey(name: string, listener: Function): void; - - // ** events ** // - - on(event: string, listener: Function): this; - /** - * Received on screen resize. - */ - on(event: "resize", callback: () => void): this; - /** - * Received on mouse events. - */ - on(event: "mouse", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "mouseout", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "mouseover", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "mousedown", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "mouseup", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "mousewheel", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "wheeldown", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "wheelup", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "mousemove", callback: (arg: Events.IMouseEventArg) => void): this; - /** - * Received on key events. - */ - on(event: "keypress", callback: (ch: string, key: Events.IKeyEventArg) => void): this; - /** - * Global events received for all elements. - */ - on(event: "element click", callback: (arg: Screen) => void): this; - on(event: "element mouseover", callback: (arg: Screen) => void): this; - on(event: "element mouseout", callback: (arg: Screen) => void): this; - on(event: "element mouseup", callback: (arg: Screen) => void): this; - /** - * Received on key event for [name]. - */ - //on(event: "key", callback: (arg: BlessedScreen) => void): this; - /** - * Received when the terminal window focuses/blurs. Requires a terminal supporting the - * focus protocol and focus needs to be passed to program.enableMouse(). - */ - on(event: "focus", callback: (arg: Screen) => void): this; - /** - * Received when the terminal window focuses/blurs. Requires a terminal supporting the - * focus protocol and focus needs to be passed to program.enableMouse(). - */ - on(event: "blur", callback: (arg: Screen) => void): this; - /** - * Received before render. - */ - on(event: "prerender", callback: () => void): this; - /** - * Received on render. - */ - on(event: "render", callback: () => void): this; - /** - * Received when blessed notices something untoward (output is not a tty, terminfo not found, etc). - */ - on(event: "warning", callback: (text: string) => void): this; - /** - * Received when the screen is destroyed (only useful when using multiple screens). - */ - on(event: "destroy", callback: () => void): this; - /** - * Received when the element is moved. - */ - on(event: "move", callback: () => void): this; - /** - * Element was clicked (slightly smarter than mouseup). - */ - on(event: "click", callback: (arg: Screen) => void): this; - /** - * Received when element is shown. - */ - on(event: "show", callback: () => void): this; - /** - * Received when element becomes hidden. - */ - on(event: "hide", callback: () => void): this; - - on(event: "set content", callback: () => void): this; - on(event: "parsed content", callback: () => void): this; - } - - export interface IScreenOptions extends INodeOptions { - /** - * The blessed Program to be associated with. Will be automatically instantiated if none is provided. - */ - program?: BlessedProgram; - /** - * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with - * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, - * however, it is more optimal for terminal rendering. - */ - smartCSR?: boolean; - /** - * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, - * but may cause flickering depending on what is on each side of the element. - */ - fastCSR?: boolean; - /** - * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work - * with terminals that don't support it, but only on lines with the default background color. As it - * stands with the current implementation, it's uncertain how much terminal performance this adds at - * the cost of overhead within node. - */ - useBCE?: boolean; - /** - * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). - */ - resizeTimeout?: number; - /** - * The width of tabs within an element's content. - */ - tabSize?: number; - /** - * Automatically position child elements with border and padding in mind (NOTE: this is a recommended - * option. It may become default in the future). - */ - autoPadding?: boolean; - - cursor?: Types.TCursor; - - /** - * Create a log file. See log method. - */ - log?: (...msg: any[]) => void; - /** - * Dump all output and input to desired file. Can be used together with log option if set as a boolean. - */ - dump?: string; - /** - * Debug mode. Enables usage of the debug method. Also creates a debug console which will display when - * pressing F12. It will display all log and debug messages. - */ - debug?: (...msg: string[]) => void; - /** - * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful - * for creating a key that will always exit no matter whether the keys are locked. - */ - ignoreLocked?: boolean; - /** - * Automatically "dock" borders with other elements instead of overlapping, depending on position - * (experimental). For example: These border-overlapped elements: - */ - dockBorders?: boolean; - /** - * Normally, dockable borders will not dock if the colors or attributes are different. This option - * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. - */ - ignoreDockContrast?: boolean; - /** - * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode - * combining characters. This allows you to display text above the basic multilingual plane. This - * is behind an option because it may affect performance slightly negatively. Without this option - * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', - * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply - * removes them from an element's content if iTerm2 is detected). - */ - fullUnicode?: boolean; - /** - * Send focus events after mouse is enabled. - */ - sendFocus?: boolean; - /** - * Display warnings (such as the output not being a TTY, similar to ncurses). - */ - warnings?: boolean; - /** - * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. - * If value is true unicode is forced. If value is false non-unicode is forced (default: null). - */ - forceUnicode?: boolean; - /** - * Input and output streams. process.stdin/process.stdout by default, however, it could be a - * net.Socket if you want to make a program that runs over telnet or something of that nature. - * */ - input?: stream.Writable; - /** - * Input and output streams. process.stdin/process.stdout by default, however, it could be a - * net.Socket if you want to make a program that runs over telnet or something of that nature. - * */ - output?: stream.Readable; - /** - * The blessed Tput object (only available if you passed tput: true to the Program constructor.) - */ - tput?: Tput; - /** - * Top of the focus history stack. - */ - focused?: BlessedElement; - /** - * Width of the screen (same as program.cols). - */ - width?: Types.TPosition; - /** - * Height of the screen (same as program.rows). - */ - height?: Types.TPosition; - /** - * Same as screen.width. - */ - cols?: number; - /** - * Same as screen.height. - */ - rows?: number; - /** - * Relative top offset, always zero. - */ - top?: Types.TTopLeft; - /** - * Relative left offset, always zero. - */ - left?: Types.TTopLeft; - /** - * Relative right offset, always zero. - */ - right?: Types.TPosition; - /** - * Relative bottom offset, always zero. - */ - bottom?: Types.TPosition; - /** - * Absolute top offset, always zero. - */ - atop?: Types.TTopLeft; - /** - * Absolute left offset, always zero. - */ - aleft?: Types.TTopLeft; - /** - * Absolute right offset, always zero. - */ - aright?: Types.TPosition; - /** - * Absolute bottom offset, always zero. - */ - abottom?: Types.TPosition; - /** - * Whether the focused element grabs all keypresses. - */ - grabKeys?: any; - /** - * Prevent keypresses from being received by any element. - */ - lockKeys?: boolean; - /** - * The currently hovered element. Only set if mouse events are bound. - */ - hover?: any; - /** - * Set or get terminal name. Set calls screen.setTerminal() internally. - */ - terminal?: string; - /** - * Set or get window title. - */ - title?: string; - } - - export class Screen extends NodeWithEvents implements IHasOptions { - constructor(opts: IScreenOptions); - - // ** properties ** // - cleanSides: any; - - /** - * Original options object. - */ - options: IScreenOptions; - - /** - * The blessed Program to be associated with. Will be automatically instantiated if none is provided. - */ - program: BlessedProgram; - /** - * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with - * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, - * however, it is more optimal for terminal rendering. - */ - smartCSR: boolean; - /** - * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, - * but may cause flickering depending on what is on each side of the element. - */ - fastCSR: boolean; - /** - * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work - * with terminals that don't support it, but only on lines with the default background color. As it - * stands with the current implementation, it's uncertain how much terminal performance this adds at - * the cost of overhead within node. - */ - useBCE: boolean; - /** - * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). - */ - resizeTimeout: number; - /** - * The width of tabs within an element's content. - */ - tabSize: number; - /** - * Automatically position child elements with border and padding in mind (NOTE: this is a recommended - * option. It may become default in the future). - */ - autoPadding: boolean; - - cursor: Types.TCursor; - - /** - * Dump all output and input to desired file. Can be used together with log option if set as a boolean. - */ - dump: string; - /** - * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful - * for creating a key that will always exit no matter whether the keys are locked. - */ - ignoreLocked: boolean; - /** - * Automatically "dock" borders with other elements instead of overlapping, depending on position - * (experimental). For example: These border-overlapped elements: - */ - dockBorders: boolean; - /** - * Normally, dockable borders will not dock if the colors or attributes are different. This option - * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. - */ - ignoreDockContrast: boolean; - /** - * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode - * combining characters. This allows you to display text above the basic multilingual plane. This - * is behind an option because it may affect performance slightly negatively. Without this option - * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', - * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply - * removes them from an element's content if iTerm2 is detected). - */ - fullUnicode: boolean; - /** - * Send focus events after mouse is enabled. - */ - sendFocus: boolean; - /** - * Display warnings (such as the output not being a TTY, similar to ncurses). - */ - warnings: boolean; - /** - * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. - * If value is true unicode is forced. If value is false non-unicode is forced (default: null). - */ - forceUnicode: boolean; - /** - * Input and output streams. process.stdin/process.stdout by default, however, it could be a - * net.Socket if you want to make a program that runs over telnet or something of that nature. - * */ - input: stream.Writable; - /** - * Input and output streams. process.stdin/process.stdout by default, however, it could be a - * net.Socket if you want to make a program that runs over telnet or something of that nature. - * */ - output: stream.Readable; - /** - * The blessed Tput object (only available if you passed tput: true to the Program constructor.) - */ - tput: Tput; - /** - * Top of the focus history stack. - */ - focused: BlessedElement; - /** - * Width of the screen (same as program.cols). - */ - width: Types.TPosition; - /** - * Height of the screen (same as program.rows). - */ - height: Types.TPosition; - /** - * Same as screen.width. - */ - cols: number; - /** - * Same as screen.height. - */ - rows: number; - /** - * Relative top offset, always zero. - */ - top: Types.TTopLeft; - /** - * Relative left offset, always zero. - */ - left: Types.TTopLeft; - /** - * Relative right offset, always zero. - */ - right: Types.TPosition; - /** - * Relative bottom offset, always zero. - */ - bottom: Types.TPosition; - /** - * Absolute top offset, always zero. - */ - atop: Types.TTopLeft; - /** - * Absolute left offset, always zero. - */ - aleft: Types.TTopLeft; - /** - * Absolute right offset, always zero. - */ - aright: Types.TPosition; - /** - * Absolute bottom offset, always zero. - */ - abottom: Types.TPosition; - /** - * Whether the focused element grabs all keypresses. - */ - grabKeys: any; - /** - * Prevent keypresses from being received by any element. - */ - lockKeys: boolean; - /** - * The currently hovered element. Only set if mouse events are bound. - */ - hover: any; - /** - * Set or get terminal name. Set calls screen.setTerminal() internally. - */ - terminal: string; - /** - * Set or get window title. - */ - title: string; - - // ** methods ** // - - /** - * Write string to the log file if one was created. - */ - log(...msg: any[]): void; - /** - * Same as the log method, but only gets called if the debug option was set. - */ - debug(...msg: string[]): void; - /** - * Allocate a new pending screen buffer and a new output screen buffer. - */ - alloc(): void; - /** - * Reallocate the screen buffers and clear the screen. - */ - realloc(): void; - /** - * Draw the screen based on the contents of the screen buffer. - */ - draw(start: number, end: number): void; - /** - * Render all child elements, writing all data to the screen buffer and drawing the screen. - */ - render(): void; - /** - * Clear any region on the screen. - */ - clearRegion(x1: number, x2: number, y1: number, y2: number): void; - /** - * Fill any region with a character of a certain attribute. - */ - fillRegion(attr: string, ch: string, x1: number, x2: number, y1: number, y2: number): void; - /** - * Focus element by offset of focusable elements. - */ - focusOffset(offset: number): any; - /** - * Focus previous element in the index. - */ - focusPrevious(): void; - /** - * Focus next element in the index. - */ - focusNext(): void; - /** - * Push element on the focus stack (equivalent to screen.focused = el). - */ - focusPush(element: BlessedElement): void; - /** - * Pop element off the focus stack. - */ - focusPop(): BlessedElement; - /** - * Save the focused element. - */ - saveFocus(): BlessedElement; - /** - * Restore the saved focused element. - */ - restoreFocus(): BlessedElement; - /** - * "Rewind" focus to the last visible and attached element. - */ - rewindFocus(): BlessedElement; - /** - * Spawn a process in the foreground, return to blessed app after exit. - */ - spawn(file: string, args: string[], options: NodeChildProcessExecOptions): child_process.ChildProcess; - /** - * Spawn a process in the foreground, return to blessed app after exit. Executes callback on error or exit. - */ - exec(file: string, args: string[], options: NodeChildProcessExecOptions, callback: Function): child_process.ChildProcess; - /** - * Read data from text editor. - */ - readEditor(options: any, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - readEditor(callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - /** - * Set effects based on two events and attributes. - */ - setEffects(el: BlessedElement, fel: BlessedElement, over: any, out: any, effects: any, temp: any): void; - /** - * Insert a line into the screen (using csr: this bypasses the output buffer). - */ - insertLine(n: number, y: number, top: number, bottom: number): void; - /** - * Delete a line from the screen (using csr: this bypasses the output buffer). - */ - deleteLine(n: number, y: number, top: number, bottom: number): void; - /** - * Insert a line at the bottom of the screen. - */ - insertBottom(top: number, bottom: number): void; - /** - * Insert a line at the top of the screen. - */ - insertTop(top: number, bottom: number): void; - /** - * Delete a line at the bottom of the screen. - */ - deleteBottom(top: number, bottom: number): void; - /** - * Delete a line at the top of the screen. - */ - deleteTop(top: number, bottom: number): void; - /** - * Enable mouse events for the screen and optionally an element (automatically called when a form of - * on('mouse') is bound). - */ - enableMouse(el: BlessedElement): void; - enableMouse(): void; - /** - * Enable keypress events for the screen and optionally an element (automatically called when a form of - * on('keypress') is bound). - */ - enableKeys(el: BlessedElement): void; - enableKeys(): void; - /** - * Enable key and mouse events. Calls bot enableMouse and enableKeys. - */ - enableInput(el: BlessedElement): void; - enableInput(): void; - /** - * Attempt to copy text to clipboard using iTerm2's proprietary sequence. Returns true if successful. - */ - copyToClipboard(text: string): void; - /** - * Attempt to change cursor shape. Will not work in all terminals (see artificial cursors for a solution - * to this). Returns true if successful. - */ - cursorShape(shape: boolean, blink: boolean): any; - /** - * Attempt to change cursor color. Returns true if successful. - */ - cursorColor(color: string): void; - /** - * Attempt to reset cursor. Returns true if successful. - */ - cursorReset(): void; - /** - * Take an SGR screenshot of the screen within the region. Returns a string containing only - * characters and SGR codes. Can be displayed by simply echoing it in a terminal. - */ - screenshot(xi: number, xl: number, yi: number, yl: number): string; - screenshot(): void; - /** - * Destroy the screen object and remove it from the global list. Also remove all global events relevant - * to the screen object. If all screen objects are destroyed, the node process is essentially reset - * to its initial state. - */ - destroy(): void; - /** - * Reset the terminal to term. Reloads terminfo. - */ - setTerminal(term: string): void; - } - - export interface Padding { - left?: number; - right?: number; - top?: number; - bottom?: number; - } - - export class PositionCoords { - xi: number; - xl: number; - yi: number; - yl: number; - } - - export interface Position { - left: number | string; - right: number | string; - top: number | string; - bottom: number | string; - } - - export interface Border { - /** - * Type of border (line or bg). bg by default. - */ - type?: "line" | "bg"; - /** - * Character to use if bg type, default is space. - */ - ch?: string; - /** - * Border foreground and background, must be numbers (-1 for default). - */ - bg?: number; - fg?: number; - /** - * Border attributes. - */ - bold?: string; - underline?: string; - } - - export interface ElementOptions extends INodeOptions { - tags?: boolean; - - fg?: string; - bg?: string; - bold?: string; - underline?: string; - - style?: any; - /** - * Border object, see below. - */ - border?: Border | "line" | "bg"; - /** - * Element's text content. - */ - content?: string; - /** - * Element is clickable. - */ - clickable?: boolean; - /** - * Element is focusable and can receive key input. - */ - input?: boolean; - keyable?: boolean; - /** - * Element is focused. - */ - focused?: BlessedElement; - /** - * Whether the element is hidden. - */ - hidden?: boolean; - /** - * A simple text label for the element. - */ - label?: string; - /** - * A floating text label for the element which appears on mouseover. - */ - hoverText?: string; - /** - * Text alignment: left, center, or right. - */ - align?: "left" | "center" | "right"; - /** - * Vertical text alignment: top, middle, or bottom. - */ - valign?: "top" | "middle" | "bottom"; - /** - * Shrink/flex/grow to content and child elements. Width/height during render. - */ - shrink?: boolean; - /** - * Amount of padding on the inside of the element. Can be a number or an object containing - * the properties: left, right, top, and bottom. - */ - padding?: number | Padding; - - top?: Types.TTopLeft; - left?: Types.TTopLeft; - right?: Types.TPosition; - bottom?: Types.TPosition; - - /** - * Width/height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). - * Percentages can also have offsets (50%+1, 50%-1). - */ - width?: number | string; - /** - * Offsets of the element relative to its parent. Can be a number, percentage (0-100%), or - * keyword (center). right and bottom do not accept keywords. Percentages can also have - * offsets (50%+1, 50%-1). - */ - height?: number | string; - /** - * Can contain the above options. - */ - position?: Position; - /** - * Whether the element is scrollable or not. - */ - scrollable?: boolean; - /** - * Background character (default is whitespace ). - */ - ch?: string; - /** - * Allow the element to be dragged with the mouse. - */ - draggable?: boolean; - /** - * Draw a translucent offset shadow behind the element. - */ - shadow?: boolean; - } - - export interface Coords { - xl: number; - xi: number; - yl: number; - yi: number; - base: number; - _contentEnd: {x: number; y: number;}; - notop: Types.TTopLeft; - noleft: Types.TTopLeft; - noright: Types.TPosition; - nobot: Types.TPosition; - } - - export interface LabelOptions { - text: string; - side: Types.TAlign; - } - - // TODO: scrollable - Note: If the scrollable option is enabled, Element inherits all methods from ScrollableBox. - export abstract class BlessedElement extends NodeWithEvents implements IHasOptions { - constructor(opts: ElementOptions); - - // ** properties ** // - - /** - * Original options object. - */ - options: ElementOptions; - /** - * Name of the element. Useful for form submission. - */ - name: string; - /** - * Border object. - */ - border: Border; - - style: any; - position: Position; - content: string; - hidden: boolean; - visible: boolean; - detached: boolean; - /** - * Border foreground and background, must be numbers (-1 for default). - */ - bg: number; - fg: number; - /** - * Border attributes. - */ - bold: string; - underline: string; - /** - * Calculated width. - */ - width: number | string; - /** - * Calculated height. - */ - height: number | string; - /** - * Calculated relative top offset.*/ - top: Types.TTopLeft; - /** - * Calculated relative left offset. - */ - left: Types.TTopLeft; - /** - * Calculated relative right offset. - */ - right: Types.TPosition; - /** - * Calculated relative bottom offset. - */ - bottom: Types.TPosition; - /** - * Calculated absolute top offset. - */ - atop: Types.TTopLeft; - /** - * Calculated absolute left offset. - */ - aleft: Types.TTopLeft; - /** - * Calculated absolute right offset. - */ - aright: Types.TPosition; - /** - * Calculated absolute bottom offset. - */ - abottom: Types.TPosition; - - /** - * Whether the element is draggable. Set to true to allow dragging. - */ - draggable: boolean; - - itop: Types.TTopLeft; - ileft: Types.TTopLeft; - iheight: Types.TPosition; - iwidth: Types.TPosition; - - /** - * Calculated relative top offset. - */ - rtop: Types.TTopLeft; - /** - * Calculated relative left offset. - */ - rleft: Types.TTopLeft; - /** - * Calculated relative right offset. - */ - rright: Types.TPosition; - /** - * Calculated relative bottom offset. - */ - rbottom: Types.TPosition; - - lpos: PositionCoords; - - // ** methods ** // - - /** - * Write content and children to the screen buffer. - */ - render(): Coords; - /** - * Hide element.*/ - hide(): void; - /** - * Show element. - */ - show(): void; - /** - * Toggle hidden/shown. - */ - toggle(): void; - /** - * Focus element. - */ - focus(): void; - /** - * Same asel.on('screen', ...) except this will automatically keep track of which listeners - * are bound to the screen object. For use with removeScreenEvent(), free(), and destroy(). - */ - onScreenEvent(type: string, handler: Function): void; - /** - * Same asel.removeListener('screen', ...) except this will automatically keep track of which - * listeners are bound to the screen object. For use with onScreenEvent(), free(), and destroy(). - */ - removeScreenEvent(type: string, handler: Function): void; - /** - * Free up the element. Automatically unbind all events that may have been bound to the screen - * object. This prevents memory leaks. For use with onScreenEvent(), removeScreenEvent(), - * and destroy(). - */ - free(): void; - /** - * Same as the detach() method, except this will automatically call free() and unbind any screen - * events to prevent memory leaks. for use with onScreenEvent(), removeScreenEvent(), and free(). - */ - destroy(): void; - /** - * Set the z-index of the element (changes rendering order). - */ - setIndex(z: number): void; - /** - * Put the element in front of its siblings.*/ - setFront(): void; - /** - * Put the element in back of its siblings. - */ - setBack(): void; - /** - * text/options - Set the label text for the top-left corner. Example options: {text:'foo',side:'left'} - */ - setLabel(arg: string | LabelOptions): void; - /** - * Remove the label completely. - */ - removeLabel(): any; - /** - * text/options - Set a hover text box to follow the cursor. Similar to the "title" DOM attribute - * in the browser. Example options: {text:'foo'} - */ - setHover(arg: string | LabelOptions): void; - /** - * Remove the hover label completely. - */ - removeHover(): void; - /** - * Enable mouse events for the element (automatically called when a form of on('mouse') is bound). - */ - enableMouse(): void; - /** - * Enable keypress events for the element (automatically called when a form of on('keypress') is bound). - */ - enableKeys(): void; - /** - * Enable key and mouse events. Calls bot enableMouse and enableKeys. - */ - enableInput(): void; - /** - * Enable dragging of the element. - */ - enableDrag(): void; - /** - * Disable dragging of the element. - */ - disableDrag(): void; - /** - * Take an SGR screenshot of the screen within the region. Returns a string containing only - * characters and SGR codes. Can be displayed by simply echoing it in a terminal. - */ - screenshot(xi: number, xl: number, yi: number, yl: number): string; - screenshot(): void; - - /* - Content Methods - - Methods for dealing with text content, line by line. Useful for writing a text editor, - irc client, etc. - - Note: All of these methods deal with pre-aligned, pre-wrapped text. If you use deleteTop() - on a box with a wrapped line at the top, it may remove 3-4 "real" lines (rows) depending - on how long the original line was. - - The lines parameter can be a string or an array of strings. The line parameter must - be a string. - */ - - /** - * Set the content. Note: When text is input, it will be stripped of all non-SGR - * escape codes, tabs will be replaced with 8 spaces, and tags will be replaced - * with SGR codes (if enabled). - */ - setContent(text: string): void; - /** - * Return content, slightly different from el.content. Assume the above formatting. - */ - getContent(): string; - /** - * Similar to setContent, but ignore tags and remove escape codes. - */ - setText(text: string): void; - /** - * Similar to getContent, but return content with tags and escape codes removed. - */ - getText(): string; - /** - * Insert a line into the box's content. - */ - insertLine(i: number, lines: string | string[]): void; - /** - * Delete a line from the box's content. - */ - deleteLine(i: number): void; - /** - * Get a line from the box's content. - */ - getLine(i: number): string; - /** - * Get a line from the box's content from the visible top. - */ - getBaseLine(i: number): string; - /** - * Set a line in the box's content. - */ - setLine(i: number, line: string | string[]): void; - /** - * Set a line in the box's content from the visible top. - */ - setBaseLine(i: number, line: string | string[]): void; - /** - * Clear a line from the box's content. - */ - clearLine(i: number): void; - /** - * Clear a line from the box's content from the visible top. - */ - clearBaseLine(i: number): void; - /** - * Insert a line at the top of the box. - */ - insertTop(lines: string | string[]): void; - /** - * Insert a line at the bottom of the box. - */ - insertBottom(lines: string | string[]): void; - /** - * Delete a line at the top of the box. - */ - deleteTop(): void; - /** - * Delete a line at the bottom of the box. - */ - deleteBottom(): void; - /** - * Unshift a line onto the top of the content. - */ - unshiftLine(lines: string | string[]): void; - /** - * Shift a line off the top of the content. - */ - shiftLine(i: number): void; - /** - * Push a line onto the bottom of the content. - */ - pushLine(lines: string | string[]): void; - /** - * Pop a line off the bottom of the content. - */ - popLine(i: number): string; - /** - * An array containing the content lines. - */ - getLines(): string[]; - /** - * An array containing the lines as they are displayed on the screen. - */ - getScreenLines(): string[]; - /** - * Get a string's displayed width, taking into account double-width, surrogate pairs, - * combining characters, tags, and SGR escape codes. - */ - strWidth(text: string): string; - - // ** events ** // - } - - export interface ScrollableBoxOptions extends ElementOptions { - /** - * A limit to the childBase. Default is Infinity. - */ - baseLimit?: number; - /** - * A option which causes the ignoring of childOffset. This in turn causes the - * childBase to change every time the element is scrolled. - */ - alwaysScroll?: boolean; - /** - * Object enabling a scrollbar. - * Style of the scrollbar track if present (takes regular style options). - */ - scrollbar?: { style?: any; track?: any; ch?: string; } - } - - export interface ScrollableTextOptions extends ScrollableBoxOptions { - /** - * Whether to enable automatic mouse support for this element. - * Use pre-defined mouse events (right-click for editor). - */ - mouse?: boolean | (() => void); - /** - * Use pre-defined keys (i or enter for insert, e for editor, C-e for editor while inserting). - */ - keys?: string | string[] | boolean; - /** - * Use vi keys with the keys option. - */ - vi?: boolean; - } - - export interface BoxOptions extends ScrollableTextOptions { - bindings?: any; - } - - /** - * DEPRECATED - Use Box with the scrollable option instead. A box with scrollable content. - */ - export class ScrollableBoxElement extends BlessedElement { - /** - * The offset of the top of the scroll content. - */ - childBase: number; - /** - * The offset of the chosen item/line. - */ - childOffset: number; - - /** - * Scroll the content by a relative offset. - */ - scroll(offset: number, always?: boolean): void; - /** - * Scroll the content to an absolute index. - */ - scrollTo(index: number): void; - /** - * Same as scrollTo. - */ - setScroll(index: number): void; - /** - * Set the current scroll index in percentage (0-100). - */ - setScrollPerc(perc: number): void; - /** - * Get the current scroll index in lines. - */ - getScroll(): number; - /** - * Get the actual height of the scrolling area. - */ - getScrollHeight(): number; - /** - * Get the current scroll index in percentage. - */ - getScrollPerc(): number; - /** - * Reset the scroll index to its initial state. - */ - resetScroll(): void; - - on(event: string, listener: Function): this; - /** - * Received when the element is scrolled. - */ - on(event: "scroll", callback: () => void): this; - } - - /** - * DEPRECATED - Use Box with the scrollable and alwaysScroll options instead. - * A scrollable text box which can display and scroll text, as well as handle - * pre-existing newlines and escape codes. - */ - export class ScrollableTextElement extends ScrollableBoxElement { - } - - /** - * A box element which draws a simple box containing content or other elements. - */ - export class BoxElement extends ScrollableTextElement implements IHasOptions { - constructor(opts: BoxOptions); - - /** - * Original options object. - */ - options: BoxOptions; - } - - export interface TextOptions extends ElementOptions { - /** - * Fill the entire line with chosen bg until parent bg ends, even if there - * is not enough text to fill the entire width. - */ - fill?: boolean; - /** - * Text alignment: left, center, or right. - */ - align?: Types.TAlign; - } - - /** - * An element similar to Box, but geared towards rendering simple text elements. - */ - export class TextElement extends BlessedElement implements IHasOptions { - constructor(opts: TextOptions); - - /** - * Original options object. - */ - options: TextOptions; - } - - /** - * A simple line which can be line or bg styled. - */ - export interface LineOptions extends BoxOptions { - /** - * Can be vertical or horizontal. - */ - orientation?: "vertical" | "horizontal"; - /** - * Treated the same as a border object. (attributes can be contained in style). - */ + interface TStyle { type?: string; bg?: string; fg?: string; ch?: string; + bold?: boolean; + underline?: boolean; + blink?: boolean; + inverse?: boolean; + invisible?: boolean; + transparent?: boolean; + border?: "line" | "bg" | TBorder; + hover?: boolean; + focus?: boolean; + label?: string; + track?: { bg?: string; fg?: string }; + scrollbar?: { bg?: string; fg?: string }; } - /** - * A simple line which can be line or bg styled. - */ - export class LineElement extends BoxElement implements IHasOptions { - constructor(opts: LineOptions); + interface TBorder { + /** + * Type of border (line or bg). bg by default. + */ + type?: "line" | "bg"; /** - * Original options object. - */ - options: LineOptions; + * Character to use if bg type, default is space. + */ + ch?: string; + + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg?: number; + fg?: number; + + /** + * Border attributes. + */ + bold?: string; + underline?: string; } - export interface BigTextOptions extends BoxOptions { + interface TCursor { /** - * bdf->json font file to use (see ttystudio for instructions on compiling BDFs to JSON). - */ - font?: string; + * Have blessed draw a custom cursor and hide the terminal cursor (experimental). + */ + artificial: boolean; + /** - * bdf->json bold font file to use (see ttystudio for instructions on compiling BDFs to JSON). - */ - fontBold?: string; + * Shape of the cursor. Can be: block, underline, or line. + */ + shape: "block" | "underline" | "line"; + /** - * foreground character. (default: ' ') - */ - fch?: string; + * Whether the cursor blinks. + */ + blink: boolean; + + /** + * Color of the color. Accepts any valid color value (null is default). + */ + color: string; } - /** - * A box which can render content drawn as 8x14 cell characters using the terminus font. - */ - export class BigTextElement extends BoxElement implements IHasOptions { - constructor(opts: BigTextOptions); + type TAlign = "left" | "center" | "right"; - /** - * Original options object. - */ - options: BigTextOptions; + interface ListbarCommand { + key: string; + callback(): void; } - export interface ListElementStyle { - selected?: any; - item?: any; + interface TImage { + /** + * Pixel width. + */ + width: number; + + /** + * Pixel height. + */ + height: number; + + /** + * Image bitmap. + */ + bmp: any; + + /** + * Image cellmap (bitmap scaled down to cell size). + */ + cellmap: any; } - export interface ListOptions extends BoxOptions { + interface Cursor { /** - * Style for a selected item. Style for an unselected item. - */ - style?: TStyle; - /** - * An array of strings which become the list's items. - */ - items?: string[]; - /** - * A function that is called when vi mode is enabled and the key / is pressed. This function accepts a - * callback function which should be called with the search string. The search string is then used to - * jump to an item that is found in items. - */ - search?: () => void; - /** - * Whether the list is interactive and can have items selected (Default: true). - */ - interactive?: boolean; - /** - * Whether to automatically override tags and invert fg of item when selected (Default: true). - */ - invertSelected?: boolean; - } - - export class ListElement extends BoxElement implements IHasOptions> { - constructor(opts: ListOptions); - - /** - * Original options object. - */ - options: ListOptions; - - /** - * Add an item based on a string. - */ - add(text: string): void; - /** - * Add an item based on a string. - */ - addItem(text: string): void; - /** - * Removes an item from the list. Child can be an element, index, or string. - */ - removeItem(child: BlessedElement): BlessedElement; - /** - * Push an item onto the list. - * */ - pushItem(child: BlessedElement): number; - /** - * Pop an item off the list. - * */ - popItem(): BlessedElement; - /** - * Unshift an item onto the list. - */ - unshiftItem(child: BlessedElement): number; - /** - * Shift an item off the list. - * */ - shiftItem(): BlessedElement; - /** - * Inserts an item to the list. Child can be an element, index, or string. - */ - insertItem(i: number, child: BlessedElement): void; - /** - * Returns the item element. Child can be an element, index, or string. - */ - getItem(child: BlessedElement): BlessedElement; - /** - * Set item to content. - */ - setItem(child: BlessedElement, content: BlessedElement | string): void; - /** - * Remove and insert items to the list. - * */ - spliceItem(i: number, n: number, ...items: BlessedElement[]): void; - /** - * Clears all items from the list. - * */ - clearItems(): void; - /** - * Sets the list items to multiple strings. - */ - setItems(items: BlessedElement[]): void; - /** - * Returns the item index from the list. Child can be an element, index, or string. - */ - getItemIndex(child: BlessedElement): number; - /** - * Select an index of an item. - * */ - select(index: number): void; - /** - * Select item based on current offset. - * */ - move(offset: number): void; - /** - * Select item above selected. - * */ - up(amount: number): void; - /** - * Select item below selected. - */ - down(amount: number): void; - /** - * Show/focus list and pick an item. The callback is executed with the result. - */ - pick(callback: () => void): void; - /** - * Find an item based on its text content. - */ - fuzzyFind(arg: string | RegExp | (() => void)): void; - - // ** events ** // + * Have blessed draw a custom cursor and hide the terminal cursor (experimental). + */ + artificial: boolean; - on(event: string, listener: Function): this; - /** - * Received when an item is selected. - */ - on(event: "select", callback: (item: BoxElement, index: number) => void): this; - /** - * List was canceled (when esc is pressed with the keys option). - */ - on(event: "cancel", callback: () => void): this; - /** - * Either a select or a cancel event was received. - */ - on(event: "action", callback: () => void): this; - - on(event: "create item", callback: () => void): this; - on(event: "add item", callback: () => void): this; - on(event: "remove item", callback: () => void): this; - on(event: "insert item", callback: () => void): this; - on(event: "set items", callback: () => void): this; - on(event: "select item", callback: (item: BlessedElement, index: number) => void): this; - } - - export interface FileManagerOptions extends ListOptions { - /** - * Current working directory. - */ - cwd?: string; - } - - export class FileManagerElement extends ListElement implements IHasOptions { - constructor(opts: FileManagerOptions); - - /** - * Original options object. - */ - options: FileManagerOptions; /** - * Current working directory. - */ - cwd: string; + * Shape of the cursor. Can be: block, underline, or line. + */ + shape: boolean; /** - * Refresh the file list (perform a readdir on cwd and update the list items). - */ - refresh(cwd:string, callback: () => void): void; - refresh(callback: () => void): void; - refresh(): void; - /** - * Pick a single file and return the path in the callback. - */ - pick(cwd:string, callback: () => void): void; - pick(callback: () => void): void; - /** - * Reset back to original cwd. - */ - reset(cwd:string, callback: () => void): void; - reset(callback: () => void): void; - reset(): void; - - // ** events ** // - - on(event: string, listener: Function): this; - /** - * Received when an item is selected. - */ - on(event: "cd", callback: (file: string, cwd: string) => void): this; - /** - * Received when an item is selected. - */ - on(event: "file", callback: (file: string) => void): this; - - on(event: "error", callback: (err: any, file: string) => void): this; - on(event: "refresh", callback: () => void): this; - } - - export interface StyleListTable extends ListElementStyle { - /** - * Header style. - */ - header?: any; - /** - * Cell style. - */ - cell?: any; - } - - export interface ListTableOptions extends ListOptions { - /** - * Array of array of strings representing rows. - */ - rows?: string[]; - data?: string[][]; - /** - * Spaces to attempt to pad on the sides of each cell. 2 by default: one space on each side - * (only useful if the width is shrunken). - */ - pad?: number; - /** - * Do not draw inner cells. - */ - noCellBorders?: boolean; - - style?: StyleListTable; - } - - export class ListTableElement extends ListElement implements IHasOptions { - constructor(opts: ListTableOptions); - - /** - * Original options object. - */ - options: ListTableOptions; - - /** - * Set rows in table. Array of arrays of strings. - * @example: - * - * table.setData([ - [ 'Animals', 'Foods' ], - [ 'Elephant', 'Apple' ], - [ 'Bird', 'Orange' ] - ]); - */ - setRows(rows: string[][]): void; - /** - * Set rows in table. Array of arrays of strings. - * @example: - * - * table.setData([ - [ 'Animals', 'Foods' ], - [ 'Elephant', 'Apple' ], - [ 'Bird', 'Orange' ] - ]); - */ - setData(rows: string[][]): void; - } - - export interface ListbarOptions extends BoxOptions { - style?: ListElementStyle; - /** - * Set buttons using an object with keys as titles of buttons, containing of objects - * containing keys of keys and callback. - */ - commands: Types.ListbarCommand[]; - items: Types.ListbarCommand[]; - /** - * Automatically bind list buttons to keys 0-9. - */ - autoCommandKeys: boolean; - } - - export class ListbarElement extends BoxElement implements IHasOptions { - constructor(opts: ListbarOptions); - - /** - * Original options object. - */ - options: ListbarOptions; - - /** - * Set commands (see commands option above). - */ - setItems(commands: Types.ListbarCommand[]): void; - /** - * Append an item to the bar. - */ - add(item: Types.ListbarCommand, callback: () => void): void; - /** - * Append an item to the bar. - */ - addItem(item: Types.ListbarCommand, callback: () => void): void; - /** - * Append an item to the bar. - */ - appendItem(item: Types.ListbarCommand, callback: () => void): void; - /** - * Select an item on the bar. - */ - select(offset: number): void; - /** - * Remove item from the bar. - */ - removeItem(child: BlessedElement): void; - /** - * Move relatively across the bar. - */ - move(offset: number): void; - /** - * Move left relatively across the bar. - */ - moveLeft(offset: number): void; - /** - * Move right relatively across the bar. - */ - moveRight(offset: number): void; - /** - * Select button and execute its callback. - */ - selectTab(index: number): void; - - // ** events ** // - - on(event: string, listener: Function): this; - - on(event: "set items", callback: () => void): this; - on(event: "remove item", callback: () => void): this; - on(event: "select tab", callback: () => void): this; - } - - export interface FormOptions extends BoxOptions { - /** - * Allow default keys (tab, vi keys, enter). - */ - keys?: any; - /** - * Allow vi keys. - */ - vi?: boolean; - } - - export class FormElement extends BoxElement implements IHasOptions { - constructor(opts: FormOptions); - - /** - * Original options object. - */ - options: FormOptions; - /** - * Last submitted data. - */ - submission: TFormData; - - /** - * Focus next form element. - */ - focusNext(): void; - /** - * Focus previous form element. - */ - focusPrevious(): void; - /** - * Submit the form. - */ - submit(): void; - /** - * Discard the form. - */ - cancel(): void; - /** - * Clear the form. - */ - reset(): void; - - // ** events ** // - - on(event: string, listener: Function): this; - /** - * Form is submitted. Receives a data object. - */ - on(event: "submit", callback: (out: TFormData) => void): this; - /** - * Form is discarded. - */ - on(event: "cancel", callback: () => void): this; - /** - * Form is cleared. - */ - on(event: "reset", callback: () => void): this; - } - - export interface InputOptions extends BoxOptions { } - - export abstract class InputElement extends BoxElement { - constructor(opts: InputOptions); - } - - /** - * A box which allows multiline text input. - */ - export interface TextareaOptions extends InputOptions { - /** - * Call readInput() when the element is focused. Automatically unfocus. - */ - inputOnFocus?: boolean; - } - - export class TextareaElement extends InputElement implements IHasOptions { - constructor(opts: TextareaOptions); - - /** - * Original options object. - */ - options: TextareaOptions; - - /** - * The input text. read-only. - */ - value: string; - - /** - * Submit the textarea (emits submit). - */ - submit(): void; - /** - * Cancel the textarea (emits cancel). - */ - cancel(): void; - /** - * Grab key events and start reading text from the keyboard. Takes a callback which receives - * the final value. - */ - readInput(callback?: (err: any, value?: string) => void): void; - /** - * Grab key events and start reading text from the keyboard. Takes a callback which receives - * the final value. - */ - input(callback: (err: any, value?: string) => void): void; - /** - * Grab key events and start reading text from the keyboard. Takes a callback which receives - * the final value. - */ - setInput(callback: (err: any, value?: string) => void): void; - /** - * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which - * receives the final value. - */ - readEditor(callback: (err: any, value?: string) => void): void; - /** - * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which - * receives the final value. - */ - editor(callback: (err: any, value?: string) => void): void; - /** - * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which - * receives the final value. - */ - setEditor(callback: (err: any, value?: string) => void): void; - /** - * The same as this.value, for now. - */ - getValue(): string; - /** - * Clear input. - */ - clearValue(): void; - /** - * Set value. - */ - setValue(text: string): void; - - // ** events ** // - - on(event: string, listener: Function): this; - - on(event: "error", callback: (err: any) => void): this; - - /** - * Value is submitted (enter). - */ - on(event: "submit", callback: (value: any) => void): this; - /** - * Value is discared (escape). - */ - on(event: "cancel", callback: (value: any) => void): this; - /** - * Either submit or cancel. - */ - on(event: "action", callback: (value: any) => void): this; - } - - export interface TextboxOptions extends TextareaOptions { - /** - * Completely hide text. - */ - secret?: boolean; - /** - * Replace text with asterisks (*). - */ - censor?: boolean; - } - - export class TextboxElement extends TextareaElement implements IHasOptions { - constructor(opts: TextboxOptions); - - /** - * Original options object. - */ - options: TextboxOptions; - - /** - * Completely hide text. - */ - secret: boolean; - /** - * Replace text with asterisks (*). - */ - censor: boolean; - } - - export interface ButtonOptions extends BoxOptions { } - - export class ButtonElement extends InputElement implements IHasOptions { - constructor(opts: ButtonOptions); - - /** - * Original options object. - */ - options: ButtonOptions; - - /** - * Press button. Emits press. - */ - press(): void; - - on(event: string, listener: Function): this; - - on(event: "press", callback: () => void): this; - } - - export interface CheckboxOptions extends BoxOptions { - /** - * whether the element is checked or not. - * */ - checked?: boolean; - /** - * enable mouse support. - * */ - mouse?: boolean; - } - - /** - * A checkbox which can be used in a form element. - * */ - export class CheckboxElement extends InputElement implements IHasOptions { - constructor(options?: CheckboxOptions); - - /** - * Original options object. - */ - options: CheckboxOptions; - - /** - * the text next to the checkbox (do not use setcontent, use `check.text = ''`). - * */ - text: string; - /** - * whether the element is checked or not. - * */ - checked: boolean; - /** - * same as `checked`. - * */ - value: boolean; - - /** - * check the element. - * */ - check(): void; - /** - * uncheck the element. - * */ - uncheck(): void; - /** - * toggle checked state. - * */ - toggle(): void; - } - - export interface RadioSetOptions extends BoxOptions { } - - /** - * An element wrapping RadioButtons. RadioButtons within this element will be mutually exclusive - * with each other. - * */ - export abstract class RadioSetElement extends BoxElement { - constructor(opts: RadioSetOptions); - } - - export interface RadioButtonOptions extends BoxOptions { } - - /** - * A radio button which can be used in a form element. - */ - export abstract class RadioButtonElement extends CheckboxElement { - constructor(opts: RadioButtonOptions); - } - - export interface PromptOptions extends BoxOptions { } - - /** - * A prompt box containing a text input, okay, and cancel buttons (automatically hidden). - */ - export class PromptElement extends BoxElement implements IHasOptions { - constructor(opts: PromptOptions); - - options: PromptOptions; - - /** - * Show the prompt and wait for the result of the textbox. Set text and initial value. - */ - input(text: string, value: string, callback: (err: any, value: string) => void): void; - setInput(text: string, value: string, callback: (err: any, value: string) => void): void; - readInput(text: string, value: string, callback: (err: any, value: string) => void): void; - } - - export interface QuestionOptions extends BoxOptions { } - - /** - * A question box containing okay and cancel buttons (automatically hidden). - */ - export class QuestionElement extends BoxElement implements IHasOptions { - constructor(opts: QuestionOptions); - - options: QuestionOptions; - - /** - * Ask a question. callback will yield the result. - */ - ask(question: string, callback: (err: any, value: string) => void): void; - } - - export interface MessageOptions extends BoxOptions { } - - /** - * A box containing a message to be displayed (automatically hidden). - */ - export class MessageElement extends BoxElement implements IHasOptions { - constructor(opts: MessageOptions); - - options: MessageOptions; - - /** - * Display a message for a time (default is 3 seconds). Set time to 0 for a perpetual message that is dismissed on keypress. - */ - log(text: string, time: number, callback: (err: any) => void): void; - log(text: string, callback: (err: any) => void): void; - display(text: string, time: number, callback: (err: any) => void): void; - display(text: string, callback: (err: any) => void): void; - - /** - * Display an error in the same way. - */ - error(text: string, time: number, callback: () => void): void; - error(text: string, callback: () => void): void; - } - - export interface LoadingOptions extends BoxOptions { } - - /** - * A box with a spinning line to denote loading (automatically hidden). - */ - export class LoadingElement extends BoxElement implements IHasOptions { - constructor(opts: LoadingOptions); - - options: LoadingOptions; - - /** - * Display the loading box with a message. Will lock keys until stop is called. - */ - load(text: string): void; - /** - * Hide loading box. Unlock keys. - */ - stop(): void; - } - - export interface ProgressBarOptions extends BoxOptions { - /** - * can be `horizontal` or `vertical`. - * */ - orientation: string; - /** - * the character to fill the bar with (default is space). - * */ - pch: string; - /** - * the amount filled (0 - 100). - * */ - filled: number; - /** - * same as `filled`. - * */ - value: number; - /** - * enable key support. - * */ - keys: boolean; - /** - * enable mouse support. - * */ - mouse: boolean; - } - - /** - * A progress bar allowing various styles. This can also be used as a form input. - */ - export class ProgressBarElement extends InputElement implements IHasOptions { - constructor(options?: ProgressBarOptions); - - options: ProgressBarOptions; - - /** - * progress the bar by a fill amount. - * */ - progress(amount:number): void; - /** - * set progress to specific amount. - * */ - setProgress(amount:number): void; - /** - * reset the bar. - * */ - reset(): void; - - on(event: string, listener: Function): this; - /** - * Bar was reset. - */ - on(event: "reset", callback: () => void): this; - /** - * Bar has completely filled. - */ - on(event: "complete", callback: () => void): this; - } - - export interface LogOptions extends ScrollableTextOptions { - /** - * amount of scrollback allowed. default: Infinity. - * */ - scrollback?: number; - /** - * scroll to bottom on input even if the user has scrolled up. default: false. - * */ - scrollOnInput?: boolean; - } - - /** - * A log permanently scrolled to the bottom. - * */ - export class Log extends ScrollableTextElement implements IHasOptions { - constructor(options?: LogOptions); - - options: LogOptions; - - /** - * amount of scrollback allowed. default: Infinity. - * */ - scrollback: number; - /** - * scroll to bottom on input even if the user has scrolled up. default: false. - * */ - scrollOnInput: boolean; - - /** - * add a log line. - * */ - log(text:string): void; - /** - * add a log line. - * */ - add(text:string): void; - } - - export interface TableOptions extends BoxOptions { - /** - * array of array of strings representing rows (same as `data`). - * */ - rows?: string[][]; - /** - * array of array of strings representing rows (same as `rows`). - * */ - data?: string[][]; - /** - * spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). - * */ - pad?: number; - /** - * do not draw inner cells. - * */ - noCellBorders?: boolean; - /** - * fill cell borders with the adjacent background color. - * */ - fillCellBorders?: boolean; - } - - /** - * A stylized table of text elements. - * */ - export class TableElement extends BoxElement implements IHasOptions { - constructor(opts: TableOptions); - - options: TableOptions; - - /** - * set rows in table. array of arrays of strings. - * */ - setData(rows: string[][]): void; - /** - * set rows in table. array of arrays of strings. - * */ - setRows(rows: string[][]): void; - } - - export interface TerminalOptions extends BoxOptions { - /** - * handler for input data. - * */ - handler?: (userInput:Buffer) => void; - /** - * name of shell. $SHELL by default. - * */ - shell?:string; - /** - * args for shell. - * */ - args?:any; - /** - * can be line, underline, and block. - * */ - cursor?: 'line'|'underline'|'block'; - - terminal?: string; - - /** - * Object for process env. - */ - env?: any; - } - - export class TerminalElement extends BoxElement implements IHasOptions { - constructor(opts: TerminalOptions); - - options: TerminalOptions; - - /** - * reference to the headless term.js terminal. - * */ - term: any; - /** - * reference to the pty.js pseudo terminal. - * */ - pty: any; - - /** - * write data to the terminal. - * */ - write(data:string): void; - - /** - * nearly identical to `element.screenshot`, however, the specified region includes the terminal's _entire_ scrollback, rather than just what is visible on the screen. - * */ - screenshot(xi?:number, xl?:number, yi?:number, yl?:number): string; - } - - export interface ImageOptions extends BoxOptions { - /** - * path to image. - * */ - file: string; - /** - * path to w3mimgdisplay. if a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. - * */ - type: "ansi" | "overlay" | "w3m"; - } - - /** - * Display an image in the terminal (jpeg, png, gif) using w3mimgdisplay. Requires w3m to be installed. X11 required: works in xterm, urxvt, and possibly other terminals. - * */ - export class ImageElement extends BoxElement implements IHasOptions { - constructor(options?: ImageOptions); - - options: ImageOptions; - } - - export interface ANSIImageOptions extends BoxOptions { - /** - * URL or path to PNG/GIF file. Can also be a buffer. - * */ - file: string; - /** - * Scale cellmap down (0-1.0) from its original pixel width/height (Default: 1.0). - * */ - scale: number; - - /** - * This differs from other element's width or height in that only one of them is needed: blessed will maintain the aspect ratio of the image as it scales down to the proper number of cells. NOTE: PNG/GIF's are always automatically shrunken to size (based on scale) if a width or height is not given. - * */ - width: number | string; - height: number | string; - - /** - * Add various "density" ASCII characters over the rendering to give the image more detail, similar to libcaca/libcucul (the library mplayer uses to display videos in the terminal). - */ - ascii: string; - - /** - * Whether to animate if the image is an APNG/animating GIF. If false, only display the first frame or IDAT (Default: true). - */ - animate: boolean; - - /** - * Set the speed of animation. Slower: 0.0-1.0. Faster: 1-1000. It cannot go faster than 1 frame per millisecond, so 1000 is the fastest. (Default: 1.0) - */ - speed: number; - - /** - * mem or cpu. If optimizing for memory, animation frames will be rendered to bitmaps as the animation plays, using less memory. Optimizing for cpu will precompile all bitmaps beforehand, which may be faster, but might also OOM the process on large images. (Default: mem). - */ - optimization: "mem" | "cpu"; - } - - /** - * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. - * */ - export class ANSIImageElement extends BoxElement implements IHasOptions { - constructor(options?:ANSIImageOptions); - - options: ANSIImageOptions; - - /** - * Image object from the png reader. - */ - img: Types.TImage; - - /** - * set the image in the box to a new path. - * */ - setImage(img: string, callback: () => void): void; - /** - * clear the current image. - * */ - clearImage(callback: () => void): void; - /** - * Play animation if it has been paused or stopped. - */ - play(): void; - /** - * Pause animation. - */ - pause(): void; - /** - * Stop animation. - */ - stop(): void; - } - - export interface OverlayImageOptions extends BoxOptions { - /** - * Path to image. - */ - file: string; - /** - * Render the file as ANSI art instead of using w3m to overlay Internally uses the ANSIImage element. See the ANSIImage element for more information/options. (Default: true). - */ - ansi: boolean; - /** - * Path to w3mimgdisplay. If a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. - */ - w3m: string; - /** - * Whether to search /usr, /bin, and /lib for w3mimgdisplay (Default: true). - */ - search: string; - } - - /** - * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. - * */ - export class OverlayImageElement extends BoxElement implements IHasOptions { - constructor(options?: OverlayImageOptions); - - options: OverlayImageOptions; - - /** - * set the image in the box to a new path. - * */ - setImage(img: string, callback: () => void): void; - /** - * clear the current image. - * */ - clearImage(callback: () => void): void; - /** - * get the size of an image file in pixels. - * */ - imageSize(img:string, callback: () => void): void; - /** - * get the size of the terminal in pixels. - * */ - termSize(callback: () => void): void; - /** - * get the pixel to cell ratio for the terminal. - * */ - getPixelRatio(callback: () => void): void; - } - - export interface VideoOptions extends BoxOptions { - /** - * Video to play. - */ - file: string; - /** - * Start time in seconds. - */ - start: number; - } - - export class VideoElement extends BoxElement implements IHasOptions { - constructor(options?: VideoOptions); - - options: VideoOptions; - - /** - * The terminal element running mplayer or mpv. - */ - tty: any; - } - - export interface LayoutOptions extends ElementOptions { - /** - * A callback which is called right before the children are iterated over to be rendered. Should return an - * iterator callback which is called on each child element: iterator(el, i). - */ - renderer?: () => void; - - /** - * Using the default renderer, it provides two layouts: inline, and grid. inline is the default and will render - * akin to inline-block. grid will create an automatic grid based on element dimensions. The grid cells' - * width and height are always determined by the largest children in the layout. - */ - layout: "inline" | "inline-block" | "grid"; - } - - export class LayoutElement extends BlessedElement implements IHasOptions { - constructor(options?: LayoutOptions); - - options: LayoutOptions; - - /** - * A callback which is called right before the children are iterated over to be rendered. Should return an - * iterator callback which is called on each child element: iterator(el, i). - */ - renderer(coords: PositionCoords): void; - /** - * Check to see if a previous child element has been rendered and is visible on screen. This is only useful - * for checking child elements that have already been attempted to be rendered! see the example below. - */ - isRendered(el: BlessedElement): boolean; - /** - * Get the last rendered and visible child element based on an index. This is useful for basing the position - * of the current child element on the position of the last child element. - */ - getLast(i: number): Element; - /** - * Get the last rendered and visible child element coords based on an index. This is useful for basing the position - * of the current child element on the position of the last child element. See the example below. - */ - getLastCoords(i: number): PositionCoords; - } + * Whether the cursor blinks. + */ + blink: boolean; - export class Program { /** - Wrap the given text in terminal formatting codes corresponding to the given attribute - name. The `attr` string can be of the form `red fg` or `52 bg` where `52` is a 0-255 - integer color number. - */ - text (text:string, attr:string): string; + * Color of the color. Accepts any valid color value (null is default). + */ + color: string; } } - export module widget { - export class Element extends Widgets.BlessedElement { } - export class Node extends Widgets.Node { } - export class Screen extends Widgets.Screen { } + namespace Events { + interface IMouseEventArg { + x: number; + y: number; + action: Types.TMouseAction; + } - export class Box extends Widgets.BoxElement { } - export class ScrollableBox extends Widgets.ScrollableBoxElement { } - export class ScrollableText extends Widgets.ScrollableTextElement { } - export class Text extends Widgets.BoxElement { } - export class Line extends Widgets.LineElement { } - export class BigText extends Widgets.BigTextElement { } - export class List extends Widgets.ListElement { } - export class FileManager extends Widgets.FileManagerElement { } - export class ListTable extends Widgets.ListTableElement { } - export class ListBar extends Widgets.ListbarElement { } - export class Form extends Widgets.FormElement { } - export class Textarea extends Widgets.TextareaElement { } - export class Button extends Widgets.ButtonElement { } - export class Checkbox extends Widgets.CheckboxElement { } - export class RadioSet extends Widgets.RadioSetElement { } - export class RadioButton extends Widgets.RadioButtonElement { } - - export class Prompt extends Widgets.PromptElement { } - export class question extends Widgets.QuestionElement { } - export class Message extends Widgets.MessageElement { } - export class Loading extends Widgets.LoadingElement { } - - export class ProgressBar extends Widgets.ProgressBarElement { } - export class Terminal extends Widgets.TerminalElement { } + interface IKeyEventArg { + full: string; + name: string; + shift: boolean; + ctrl: boolean; + meta: boolean; + sequence: string; + } } - export function screen(options?: Widgets.IScreenOptions): Widgets.Screen; + interface NodeChildProcessExecOptions { + cwd?: string; + stdio?: any; + customFds?: any; + env?: any; + encoding?: string; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + } - export function box(options?: Widgets.BoxOptions): Widgets.BoxElement; - export function text(options?: Widgets.TextOptions): Widgets.TextElement; - export function line(options?: Widgets.LineOptions): Widgets.LineElement; - export function scrollablebox(options?: Widgets.BoxOptions): Widgets.BoxElement; - export function scrollabletext(options?: Widgets.BoxOptions): Widgets.BoxElement; - export function bigtext(options?: Widgets.BigTextOptions): Widgets.BigTextElement; - export function list(options?: Widgets.ListOptions): Widgets.ListElement; - export function filemanager(options?: Widgets.FileManagerOptions): Widgets.FileManagerElement; - export function listtable(options?: Widgets.ListTableOptions): Widgets.ListTableElement; - export function listbar(options?: Widgets.ListbarOptions): Widgets.ListbarElement; - export function form(options?: Widgets.FormOptions): Widgets.FormElement; - export function input(options?: Widgets.InputOptions): Widgets.InputElement; - export function textarea(options?: Widgets.TextareaOptions): Widgets.TextareaElement; - export function textbox(options?: Widgets.TextboxOptions): Widgets.TextboxElement; - export function button(options?: Widgets.ButtonOptions): Widgets.ButtonElement; - export function checkbox(options?: Widgets.CheckboxOptions): Widgets.CheckboxElement; - export function radioset(options?: Widgets.RadioSetOptions): Widgets.RadioSetElement; - export function radiobutton(options?: Widgets.RadioButtonOptions): Widgets.RadioButtonElement; + interface IDestroyable { + destroy(): void; + } - export function table(options?: Widgets.TableOptions): Widgets.TableElement; + interface IOptions {} - export function prompt(options?: Widgets.PromptOptions): Widgets.PromptElement; - export function question(options?: Widgets.QuestionOptions): Widgets.QuestionElement; - export function message(options?: Widgets.MessageOptions): Widgets.MessageElement; - export function loading(options?: Widgets.LoadingOptions): Widgets.LoadingElement; - export function log(options?: Widgets.LogOptions): Widgets.Log; + interface IHasOptions { + options: T; + } - export function progressbar(options?: Widgets.ProgressBarOptions): Widgets.ProgressBarElement; - export function terminal(options?: Widgets.TerminalOptions): Widgets.TerminalElement; + interface TputsOptions extends IOptions { + terminal?: string; + extended?: boolean; + debug?: boolean; + termcap?: string; + terminfoFile?: string; + terminfoPrefix?: string; + termcapFile?: string; + } - export function layout(options?: Widgets.LayoutOptions): Widgets.LayoutElement; + class Tput implements IHasOptions { + constructor(opts: TputsOptions); - export function escape(item: any): any; - export const colors: { - match: (hexColor: string) => string + /** + * Original options object. + */ + options: TputsOptions; + + debug: boolean; + padding: boolean; + extended: boolean; + printf: boolean; + termcap: string; + terminfoPrefix: string; + terminfoFile: string; + termcapFile: string; + error: Error; + terminal: string; + + setup(): void; + term(is: any): boolean; + readTerminfo(term: string): string; + parseTerminfo( + data: any, + file: string + ): { + header: { + dataSize: number; + headerSize: number; + magicNumber: boolean; + namesSize: number; + boolCount: number; + numCount: number; + strCount: number; + strTableSize: number; + extended: { + dataSize: number; + headerSize: number; + boolCount: number; + numCount: number; + strCount: number; + strTableSize: number; + lastStrTableOffset: number; + }; + }; + name: string; + names: string[]; + desc: string; + bools: any; + numbers: any; + strings: any; + }; + } + + interface IDestroyable { + destroy(): void; + } + + interface INodeOptions extends IOptions { + name?: string; + screen?: Screen; + parent?: Node; + children?: Node[]; + focusable?: boolean; + } + + type NodeEventType = + /** Received when node is added to a parent. */ + | "adopt" + /** Received when node is removed from it's current parent. */ + | "remove" + /** Received when node gains a new parent. */ + | "reparent" + /** Received when node is attached to the screen directly or somewhere in its ancestry. */ + | "attach" + /** Received when node is detached from the screen directly or somewhere in its ancestry. */ + | "detach"; + + abstract class Node extends EventEmitter implements IHasOptions, IDestroyable { + constructor(options: INodeOptions); + + focusable: boolean; + + /** + * Original options object. + */ + options: INodeOptions; + + /** + * An object for any miscellanous user data. + */ + data: { [index: string]: any }; + + /** + * An object for any miscellanous user data. + */ + _: { [index: string]: any }; + + /** + * An object for any miscellanous user data. + */ + $: { [index: string]: any }; + + /** + * Type of the node (e.g. box). + */ + type: string; + + /** + * Render index (document order index) of the last render call. + */ + index: number; + + /** + * Parent screen. + */ + screen: Screen; + + /** + * Parent node. + */ + parent: Node; + + /** + * Array of node's children. + */ + children: Node[]; + + /** + * Prepend a node to this node's children. + */ + prepend(node: Node): void; + + /** + * Append a node to this node's children. + */ + append(node: Node): void; + + /** + * Remove child node from node. + */ + remove(node: Node): void; + + /** + * Insert a node to this node's children at index i. + */ + insert(node: Node, index: number): void; + + /** + * Insert a node to this node's children before the reference node. + */ + insertBefore(node: Node, refNode: Node): void; + + /** + * Insert a node from node after the reference node. + */ + insertAfter(node: Node, refNode: Node): void; + + /** + * Remove node from its parent. + */ + detach(): void; + free(): void; + forDescendants(iter: (node: Node) => void, s: any): void; + forAncestors(iter: (node: Node) => void, s: any): void; + collectDescendants(s: any): void; + collectAncestors(s: any): void; + + /** + * Emit event for element, and recursively emit same event for all descendants. + */ + emitDescendants(type?: string, ...args: any[]): void; + emitAncestors(): void; + hasDescendant(target: Node): void; + hasAncestor(target: Node): boolean; + destroy(): void; + + /** + * Get user property with a potential default value. + */ + get(name: string, def: T): T; + + /** + * Set user property to value. + */ + set(name: string, value: any): void; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: NodeEventType, callback: (arg: Node) => void): this; + } + + type NodeScreenEventType = + /** + * Received when the terminal window focuses/blurs. Requires a terminal supporting the + * focus protocol and focus needs to be passed to program.enableMouse(). + */ + | "focus" + /** + * Received when the terminal window focuses/blurs. Requires a terminal supporting the + * focus protocol and focus needs to be passed to program.enableMouse(). + */ + | "blur" + /** + * Element was clicked (slightly smarter than mouseup). + */ + | "click" + | "element click" + | "element mouseover" + | "element mouseout" + | "element mouseup"; + + type NodeMouseEventType = + | "mouse" + | "mouseout" + | "mouseover" + | "mousedown" + | "mouseup" + | "mousewheel" + | "wheeldown" + | "wheelup" + | "mousemove"; + + type NodeGenericEventType = + /** Received on screen resize. */ + | "resize" + /** Received before render. */ + | "prerender" + /** Received on render. */ + | "render" + /** Received when the screen is destroyed (only useful when using multiple screens). */ + | "destroy" + /** Received when the element is moved. */ + | "move" + /** Received when element is shown. */ + | "show" + /** Received when element becomes hidden. */ + | "hide" + | "set content" + | "parsed content"; + + class NodeWithEvents extends Node { + /** + * Bind a keypress listener for a specific key. + */ + key(name: string | string[], listener: (ch: any, key: Events.IKeyEventArg) => void): void; + + /** + * Bind a keypress listener for a specific key once. + */ + onceKey(name: string, listener: (ch: any, key: Events.IKeyEventArg) => void): void; + + /** + * Remove a keypress listener for a specific key. + */ + unkey(name: string, listener: (ch: any, key: Events.IKeyEventArg) => void): void; + removeKey(name: string, listener: (ch: any, key: Events.IKeyEventArg) => void): void; + + on(event: string, listener: (ch: any, key: Events.IKeyEventArg) => void): this; + /** Received on mouse events. */ + on(event: NodeMouseEventType, callback: (arg: Events.IMouseEventArg) => void): this; + /** Received on key events. */ + on(event: "keypress", callback: (ch: string, key: Events.IKeyEventArg) => void): this; + on(event: NodeScreenEventType, callback: (arg: Screen) => void): this; + /** Received when blessed notices something untoward (output is not a tty, terminfo not found, etc). */ + on(event: "warning", callback: (text: string) => void): this; + on(event: NodeGenericEventType, callback: () => void): this; + } + + interface IScreenOptions extends INodeOptions { + /** + * The blessed Program to be associated with. Will be automatically instantiated if none is provided. + */ + program?: BlessedProgram; + + /** + * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with + * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, + * however, it is more optimal for terminal rendering. + */ + smartCSR?: boolean; + + /** + * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, + * but may cause flickering depending on what is on each side of the element. + */ + fastCSR?: boolean; + + /** + * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work + * with terminals that don't support it, but only on lines with the default background color. As it + * stands with the current implementation, it's uncertain how much terminal performance this adds at + * the cost of overhead within node. + */ + useBCE?: boolean; + + /** + * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). + */ + resizeTimeout?: number; + + /** + * The width of tabs within an element's content. + */ + tabSize?: number; + + /** + * Automatically position child elements with border and padding in mind (NOTE: this is a recommended + * option. It may become default in the future). + */ + autoPadding?: boolean; + + cursor?: Types.TCursor; + + /** + * Create a log file. See log method. + */ + log?(...msg: any[]): void; + + /** + * Dump all output and input to desired file. Can be used together with log option if set as a boolean. + */ + dump?: string; + + /** + * Debug mode. Enables usage of the debug method. Also creates a debug console which will display when + * pressing F12. It will display all log and debug messages. + */ + debug?(...msg: string[]): void; + + /** + * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful + * for creating a key that will always exit no matter whether the keys are locked. + */ + ignoreLocked?: boolean; + + /** + * Automatically "dock" borders with other elements instead of overlapping, depending on position + * (experimental). For example: These border-overlapped elements: + */ + dockBorders?: boolean; + + /** + * Normally, dockable borders will not dock if the colors or attributes are different. This option + * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. + */ + ignoreDockContrast?: boolean; + + /** + * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode + * combining characters. This allows you to display text above the basic multilingual plane. This + * is behind an option because it may affect performance slightly negatively. Without this option + * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', + * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply + * removes them from an element's content if iTerm2 is detected). + */ + fullUnicode?: boolean; + + /** + * Send focus events after mouse is enabled. + */ + sendFocus?: boolean; + + /** + * Display warnings (such as the output not being a TTY, similar to ncurses). + */ + warnings?: boolean; + + /** + * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. + * If value is true unicode is forced. If value is false non-unicode is forced (default: null). + */ + forceUnicode?: boolean; + + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + */ + input?: stream.Writable; + + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + */ + output?: stream.Readable; + + /** + * The blessed Tput object (only available if you passed tput: true to the Program constructor.) + */ + tput?: Tput; + + /** + * Top of the focus history stack. + */ + focused?: BlessedElement; + + /** + * Width of the screen (same as program.cols). + */ + width?: Types.TPosition; + + /** + * Height of the screen (same as program.rows). + */ + height?: Types.TPosition; + + /** + * Same as screen.width. + */ + cols?: number; + + /** + * Same as screen.height. + */ + rows?: number; + + /** + * Relative top offset, always zero. + */ + top?: Types.TTopLeft; + + /** + * Relative left offset, always zero. + */ + left?: Types.TTopLeft; + + /** + * Relative right offset, always zero. + */ + right?: Types.TPosition; + + /** + * Relative bottom offset, always zero. + */ + bottom?: Types.TPosition; + + /** + * Absolute top offset, always zero. + */ + atop?: Types.TTopLeft; + + /** + * Absolute left offset, always zero. + */ + aleft?: Types.TTopLeft; + + /** + * Absolute right offset, always zero. + */ + aright?: Types.TPosition; + + /** + * Absolute bottom offset, always zero. + */ + abottom?: Types.TPosition; + + /** + * Whether the focused element grabs all keypresses. + */ + grabKeys?: any; + + /** + * Prevent keypresses from being received by any element. + */ + lockKeys?: boolean; + + /** + * The currently hovered element. Only set if mouse events are bound. + */ + hover?: any; + + /** + * Set or get terminal name. Set calls screen.setTerminal() internally. + */ + terminal?: string; + + /** + * Set or get window title. + */ + title?: string; + } + + class Screen extends NodeWithEvents implements IHasOptions { + constructor(opts: IScreenOptions); + + cleanSides: any; + + /** + * Original options object. + */ + options: IScreenOptions; + + /** + * The blessed Program to be associated with. Will be automatically instantiated if none is provided. + */ + program: BlessedProgram; + + /** + * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with + * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, + * however, it is more optimal for terminal rendering. + */ + smartCSR: boolean; + + /** + * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, + * but may cause flickering depending on what is on each side of the element. + */ + fastCSR: boolean; + + /** + * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work + * with terminals that don't support it, but only on lines with the default background color. As it + * stands with the current implementation, it's uncertain how much terminal performance this adds at + * the cost of overhead within node. + */ + useBCE: boolean; + + /** + * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). + */ + resizeTimeout: number; + + /** + * The width of tabs within an element's content. + */ + tabSize: number; + + /** + * Automatically position child elements with border and padding in mind (NOTE: this is a recommended + * option. It may become default in the future). + */ + autoPadding: boolean; + + cursor: Types.TCursor; + + /** + * Dump all output and input to desired file. Can be used together with log option if set as a boolean. + */ + dump: string; + + /** + * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful + * for creating a key that will always exit no matter whether the keys are locked. + */ + ignoreLocked: boolean; + + /** + * Automatically "dock" borders with other elements instead of overlapping, depending on position + * (experimental). For example: These border-overlapped elements: + */ + dockBorders: boolean; + + /** + * Normally, dockable borders will not dock if the colors or attributes are different. This option + * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. + */ + ignoreDockContrast: boolean; + + /** + * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode + * combining characters. This allows you to display text above the basic multilingual plane. This + * is behind an option because it may affect performance slightly negatively. Without this option + * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', + * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply + * removes them from an element's content if iTerm2 is detected). + */ + fullUnicode: boolean; + + /** + * Send focus events after mouse is enabled. + */ + sendFocus: boolean; + + /** + * Display warnings (such as the output not being a TTY, similar to ncurses). + */ + warnings: boolean; + + /** + * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. + * If value is true unicode is forced. If value is false non-unicode is forced (default: null). + */ + forceUnicode: boolean; + + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + */ + input: stream.Writable; + + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + */ + output: stream.Readable; + + /** + * The blessed Tput object (only available if you passed tput: true to the Program constructor.) + */ + tput: Tput; + + /** + * Top of the focus history stack. + */ + focused: BlessedElement; + + /** + * Width of the screen (same as program.cols). + */ + width: Types.TPosition; + + /** + * Height of the screen (same as program.rows). + */ + height: Types.TPosition; + + /** + * Same as screen.width. + */ + cols: number; + + /** + * Same as screen.height. + */ + rows: number; + + /** + * Relative top offset, always zero. + */ + top: Types.TTopLeft; + + /** + * Relative left offset, always zero. + */ + left: Types.TTopLeft; + + /** + * Relative right offset, always zero. + */ + right: Types.TPosition; + + /** + * Relative bottom offset, always zero. + */ + bottom: Types.TPosition; + + /** + * Absolute top offset, always zero. + */ + atop: Types.TTopLeft; + + /** + * Absolute left offset, always zero. + */ + aleft: Types.TTopLeft; + + /** + * Absolute right offset, always zero. + */ + aright: Types.TPosition; + + /** + * Absolute bottom offset, always zero. + */ + abottom: Types.TPosition; + + /** + * Whether the focused element grabs all keypresses. + */ + grabKeys: any; + + /** + * Prevent keypresses from being received by any element. + */ + lockKeys: boolean; + + /** + * The currently hovered element. Only set if mouse events are bound. + */ + hover: any; + + /** + * Set or get terminal name. Set calls screen.setTerminal() internally. + */ + terminal: string; + + /** + * Set or get window title. + */ + title: string; + + /** + * Write string to the log file if one was created. + */ + log(...msg: any[]): void; + + /** + * Same as the log method, but only gets called if the debug option was set. + */ + debug(...msg: string[]): void; + + /** + * Allocate a new pending screen buffer and a new output screen buffer. + */ + alloc(): void; + + /** + * Reallocate the screen buffers and clear the screen. + */ + realloc(): void; + + /** + * Draw the screen based on the contents of the screen buffer. + */ + draw(start: number, end: number): void; + + /** + * Render all child elements, writing all data to the screen buffer and drawing the screen. + */ + render(): void; + + /** + * Clear any region on the screen. + */ + clearRegion(x1: number, x2: number, y1: number, y2: number): void; + + /** + * Fill any region with a character of a certain attribute. + */ + fillRegion(attr: string, ch: string, x1: number, x2: number, y1: number, y2: number): void; + + /** + * Focus element by offset of focusable elements. + */ + focusOffset(offset: number): any; + + /** + * Focus previous element in the index. + */ + focusPrevious(): void; + + /** + * Focus next element in the index. + */ + focusNext(): void; + + /** + * Push element on the focus stack (equivalent to screen.focused = el). + */ + focusPush(element: BlessedElement): void; + + /** + * Pop element off the focus stack. + */ + focusPop(): BlessedElement; + + /** + * Save the focused element. + */ + saveFocus(): BlessedElement; + + /** + * Restore the saved focused element. + */ + restoreFocus(): BlessedElement; + + /** + * "Rewind" focus to the last visible and attached element. + */ + rewindFocus(): BlessedElement; + + /** + * Spawn a process in the foreground, return to blessed app after exit. + */ + spawn(file: string, args: string[], options: NodeChildProcessExecOptions): child_process.ChildProcess; + + /** + * Spawn a process in the foreground, return to blessed app after exit. Executes callback on error or exit. + */ + exec( + file: string, + args: string[], + options: NodeChildProcessExecOptions, + callback: (...args: any[]) => void + ): child_process.ChildProcess; + + /** + * Read data from text editor. + */ + readEditor(options: any, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + readEditor(callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + + /** + * Set effects based on two events and attributes. + */ + setEffects(el: BlessedElement, fel: BlessedElement, over: any, out: any, effects: any, temp: any): void; + + /** + * Insert a line into the screen (using csr: this bypasses the output buffer). + */ + insertLine(n: number, y: number, top: number, bottom: number): void; + + /** + * Delete a line from the screen (using csr: this bypasses the output buffer). + */ + deleteLine(n: number, y: number, top: number, bottom: number): void; + + /** + * Insert a line at the bottom of the screen. + */ + insertBottom(top: number, bottom: number): void; + + /** + * Insert a line at the top of the screen. + */ + insertTop(top: number, bottom: number): void; + + /** + * Delete a line at the bottom of the screen. + */ + deleteBottom(top: number, bottom: number): void; + + /** + * Delete a line at the top of the screen. + */ + deleteTop(top: number, bottom: number): void; + + /** + * Enable mouse events for the screen and optionally an element (automatically called when a form of + * on('mouse') is bound). + */ + enableMouse(el?: BlessedElement): void; + + /** + * Enable keypress events for the screen and optionally an element (automatically called when a form of + * on('keypress') is bound). + */ + enableKeys(el?: BlessedElement): void; + + /** + * Enable key and mouse events. Calls bot enableMouse and enableKeys. + */ + enableInput(el?: BlessedElement): void; + + /** + * Attempt to copy text to clipboard using iTerm2's proprietary sequence. Returns true if successful. + */ + copyToClipboard(text: string): void; + + /** + * Attempt to change cursor shape. Will not work in all terminals (see artificial cursors for a solution + * to this). Returns true if successful. + */ + cursorShape(shape: boolean, blink: boolean): any; + + /** + * Attempt to change cursor color. Returns true if successful. + */ + cursorColor(color: string): void; + + /** + * Attempt to reset cursor. Returns true if successful. + */ + cursorReset(): void; + + /** + * Take an SGR screenshot of the screen within the region. Returns a string containing only + * characters and SGR codes. Can be displayed by simply echoing it in a terminal. + */ + screenshot(xi: number, xl: number, yi: number, yl: number): string; + screenshot(): void; + + /** + * Destroy the screen object and remove it from the global list. Also remove all global events relevant + * to the screen object. If all screen objects are destroyed, the node process is essentially reset + * to its initial state. + */ + destroy(): void; + + /** + * Reset the terminal to term. Reloads terminfo. + */ + setTerminal(term: string): void; + } + + interface Padding { + left?: number; + right?: number; + top?: number; + bottom?: number; + } + + class PositionCoords { + xi: number; + xl: number; + yi: number; + yl: number; + } + + interface Position { + left: number | string; + right: number | string; + top: number | string; + bottom: number | string; + } + + interface Border { + /** + * Type of border (line or bg). bg by default. + */ + type?: "line" | "bg"; + + /** + * Character to use if bg type, default is space. + */ + ch?: string; + + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg?: number; + fg?: number; + + /** + * Border attributes. + */ + bold?: string; + underline?: string; + } + + interface ElementOptions extends INodeOptions { + tags?: boolean; + + fg?: string; + bg?: string; + bold?: string; + underline?: string; + + style?: any; + + /** + * Border object, see below. + */ + border?: Border | "line" | "bg"; + + /** + * Element's text content. + */ + content?: string; + + /** + * Element is clickable. + */ + clickable?: boolean; + + /** + * Element is focusable and can receive key input. + */ + input?: boolean; + keyable?: boolean; + + /** + * Element is focused. + */ + focused?: BlessedElement; + + /** + * Whether the element is hidden. + */ + hidden?: boolean; + + /** + * A simple text label for the element. + */ + label?: string; + + /** + * A floating text label for the element which appears on mouseover. + */ + hoverText?: string; + + /** + * Text alignment: left, center, or right. + */ + align?: "left" | "center" | "right"; + + /** + * Vertical text alignment: top, middle, or bottom. + */ + valign?: "top" | "middle" | "bottom"; + + /** + * Shrink/flex/grow to content and child elements. Width/height during render. + */ + shrink?: boolean; + + /** + * Amount of padding on the inside of the element. Can be a number or an object containing + * the properties: left, right, top, and bottom. + */ + padding?: number | Padding; + + top?: Types.TTopLeft; + left?: Types.TTopLeft; + right?: Types.TPosition; + bottom?: Types.TPosition; + + /** + * Width/height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). + * Percentages can also have offsets (50%+1, 50%-1). + */ + width?: number | string; + + /** + * Offsets of the element relative to its parent. Can be a number, percentage (0-100%), or + * keyword (center). right and bottom do not accept keywords. Percentages can also have + * offsets (50%+1, 50%-1). + */ + height?: number | string; + + /** + * Can contain the above options. + */ + position?: Position; + + /** + * Whether the element is scrollable or not. + */ + scrollable?: boolean; + + /** + * Background character (default is whitespace ). + */ + ch?: string; + + /** + * Allow the element to be dragged with the mouse. + */ + draggable?: boolean; + + /** + * Draw a translucent offset shadow behind the element. + */ + shadow?: boolean; + } + + interface Coords { + xl: number; + xi: number; + yl: number; + yi: number; + base: number; + _contentEnd: { x: number; y: number }; + notop: Types.TTopLeft; + noleft: Types.TTopLeft; + noright: Types.TPosition; + nobot: Types.TPosition; + } + + interface LabelOptions { + text: string; + side: Types.TAlign; + } + + // TODO: scrollable - Note: If the scrollable option is enabled, Element inherits all methods from ScrollableBox. + abstract class BlessedElement extends NodeWithEvents implements IHasOptions { + constructor(opts: ElementOptions); + + /** + * Original options object. + */ + options: ElementOptions; + + /** + * Name of the element. Useful for form submission. + */ + name: string; + + /** + * Border object. + */ + border: Border; + + style: any; + position: Position; + content: string; + hidden: boolean; + visible: boolean; + detached: boolean; + + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg: number; + fg: number; + + /** + * Border attributes. + */ + bold: string; + underline: string; + + /** + * Calculated width. + */ + width: number | string; + + /** + * Calculated height. + */ + height: number | string; + + /** + * Calculated relative top offset. + */ + top: Types.TTopLeft; + + /** + * Calculated relative left offset. + */ + left: Types.TTopLeft; + + /** + * Calculated relative right offset. + */ + right: Types.TPosition; + + /** + * Calculated relative bottom offset. + */ + bottom: Types.TPosition; + + /** + * Calculated absolute top offset. + */ + atop: Types.TTopLeft; + + /** + * Calculated absolute left offset. + */ + aleft: Types.TTopLeft; + + /** + * Calculated absolute right offset. + */ + aright: Types.TPosition; + + /** + * Calculated absolute bottom offset. + */ + abottom: Types.TPosition; + + /** + * Whether the element is draggable. Set to true to allow dragging. + */ + draggable: boolean; + + itop: Types.TTopLeft; + ileft: Types.TTopLeft; + iheight: Types.TPosition; + iwidth: Types.TPosition; + + /** + * Calculated relative top offset. + */ + rtop: Types.TTopLeft; + + /** + * Calculated relative left offset. + */ + rleft: Types.TTopLeft; + + /** + * Calculated relative right offset. + */ + rright: Types.TPosition; + + /** + * Calculated relative bottom offset. + */ + rbottom: Types.TPosition; + + lpos: PositionCoords; + + /** + * Write content and children to the screen buffer. + */ + render(): Coords; + + /** + * Hide element. + */ + hide(): void; + + /** + * Show element. + */ + show(): void; + + /** + * Toggle hidden/shown. + */ + toggle(): void; + + /** + * Focus element. + */ + focus(): void; + + /** + * Same asel.on('screen', ...) except this will automatically keep track of which listeners + * are bound to the screen object. For use with removeScreenEvent(), free(), and destroy(). + */ + onScreenEvent(type: string, handler: (...args: any[]) => void): void; + + /** + * Same asel.removeListener('screen', ...) except this will automatically keep track of which + * listeners are bound to the screen object. For use with onScreenEvent(), free(), and destroy(). + */ + removeScreenEvent(type: string, handler: (...args: any[]) => void): void; + + /** + * Free up the element. Automatically unbind all events that may have been bound to the screen + * object. This prevents memory leaks. For use with onScreenEvent(), removeScreenEvent(), + * and destroy(). + */ + free(): void; + + /** + * Same as the detach() method, except this will automatically call free() and unbind any screen + * events to prevent memory leaks. for use with onScreenEvent(), removeScreenEvent(), and free(). + */ + destroy(): void; + + /** + * Set the z-index of the element (changes rendering order). + */ + setIndex(z: number): void; + + /** + * Put the element in front of its siblings. + */ + setFront(): void; + + /** + * Put the element in back of its siblings. + */ + setBack(): void; + + /** + * text/options - Set the label text for the top-left corner. Example options: {text:'foo',side:'left'} + */ + setLabel(arg: string | LabelOptions): void; + + /** + * Remove the label completely. + */ + removeLabel(): any; + + /** + * text/options - Set a hover text box to follow the cursor. Similar to the "title" DOM attribute + * in the browser. Example options: {text:'foo'} + */ + setHover(arg: string | LabelOptions): void; + + /** + * Remove the hover label completely. + */ + removeHover(): void; + + /** + * Enable mouse events for the element (automatically called when a form of on('mouse') is bound). + */ + enableMouse(): void; + + /** + * Enable keypress events for the element (automatically called when a form of on('keypress') is bound). + */ + enableKeys(): void; + + /** + * Enable key and mouse events. Calls bot enableMouse and enableKeys. + */ + enableInput(): void; + + /** + * Enable dragging of the element. + */ + enableDrag(): void; + + /** + * Disable dragging of the element. + */ + disableDrag(): void; + + /** + * Take an SGR screenshot of the screen within the region. Returns a string containing only + * characters and SGR codes. Can be displayed by simply echoing it in a terminal. + */ + screenshot(xi: number, xl: number, yi: number, yl: number): string; + screenshot(): void; + + /* + Content Methods + + Methods for dealing with text content, line by line. Useful for writing a text editor, + irc client, etc. + + Note: All of these methods deal with pre-aligned, pre-wrapped text. If you use deleteTop() + on a box with a wrapped line at the top, it may remove 3-4 "real" lines (rows) depending + on how long the original line was. + + The lines parameter can be a string or an array of strings. The line parameter must + be a string. + */ + + /** + * Set the content. Note: When text is input, it will be stripped of all non-SGR + * escape codes, tabs will be replaced with 8 spaces, and tags will be replaced + * with SGR codes (if enabled). + */ + setContent(text: string): void; + + /** + * Return content, slightly different from el.content. Assume the above formatting. + */ + getContent(): string; + + /** + * Similar to setContent, but ignore tags and remove escape codes. + */ + setText(text: string): void; + + /** + * Similar to getContent, but return content with tags and escape codes removed. + */ + getText(): string; + + /** + * Insert a line into the box's content. + */ + insertLine(i: number, lines: string | string[]): void; + + /** + * Delete a line from the box's content. + */ + deleteLine(i: number): void; + + /** + * Get a line from the box's content. + */ + getLine(i: number): string; + + /** + * Get a line from the box's content from the visible top. + */ + getBaseLine(i: number): string; + + /** + * Set a line in the box's content. + */ + setLine(i: number, line: string | string[]): void; + + /** + * Set a line in the box's content from the visible top. + */ + setBaseLine(i: number, line: string | string[]): void; + + /** + * Clear a line from the box's content. + */ + clearLine(i: number): void; + + /** + * Clear a line from the box's content from the visible top. + */ + clearBaseLine(i: number): void; + + /** + * Insert a line at the top of the box. + */ + insertTop(lines: string | string[]): void; + + /** + * Insert a line at the bottom of the box. + */ + insertBottom(lines: string | string[]): void; + + /** + * Delete a line at the top of the box. + */ + deleteTop(): void; + + /** + * Delete a line at the bottom of the box. + */ + deleteBottom(): void; + + /** + * Unshift a line onto the top of the content. + */ + unshiftLine(lines: string | string[]): void; + + /** + * Shift a line off the top of the content. + */ + shiftLine(i: number): void; + + /** + * Push a line onto the bottom of the content. + */ + pushLine(lines: string | string[]): void; + + /** + * Pop a line off the bottom of the content. + */ + popLine(i: number): string; + + /** + * An array containing the content lines. + */ + getLines(): string[]; + + /** + * An array containing the lines as they are displayed on the screen. + */ + getScreenLines(): string[]; + + /** + * Get a string's displayed width, taking into account double-width, surrogate pairs, + * combining characters, tags, and SGR escape codes. + */ + strWidth(text: string): string; + } + + interface ScrollableBoxOptions extends ElementOptions { + /** + * A limit to the childBase. Default is Infinity. + */ + baseLimit?: number; + + /** + * A option which causes the ignoring of childOffset. This in turn causes the + * childBase to change every time the element is scrolled. + */ + alwaysScroll?: boolean; + + /** + * Object enabling a scrollbar. + * Style of the scrollbar track if present (takes regular style options). + */ + scrollbar?: { style?: any; track?: any; ch?: string }; + } + + interface ScrollableTextOptions extends ScrollableBoxOptions { + /** + * Whether to enable automatic mouse support for this element. + * Use pre-defined mouse events (right-click for editor). + */ + mouse?: boolean | (() => void); + + /** + * Use pre-defined keys (i or enter for insert, e for editor, C-e for editor while inserting). + */ + keys?: string | string[] | boolean; + + /** + * Use vi keys with the keys option. + */ + vi?: boolean; + } + + interface BoxOptions extends ScrollableTextOptions { + bindings?: any; + } + + /** + * DEPRECATED - Use Box with the scrollable option instead. A box with scrollable content. + */ + class ScrollableBoxElement extends BlessedElement { + /** + * The offset of the top of the scroll content. + */ + childBase: number; + + /** + * The offset of the chosen item/line. + */ + childOffset: number; + + /** + * Scroll the content by a relative offset. + */ + scroll(offset: number, always?: boolean): void; + + /** + * Scroll the content to an absolute index. + */ + scrollTo(index: number): void; + + /** + * Same as scrollTo. + */ + setScroll(index: number): void; + + /** + * Set the current scroll index in percentage (0-100). + */ + setScrollPerc(perc: number): void; + + /** + * Get the current scroll index in lines. + */ + getScroll(): number; + + /** + * Get the actual height of the scrolling area. + */ + getScrollHeight(): number; + + /** + * Get the current scroll index in percentage. + */ + getScrollPerc(): number; + + /** + * Reset the scroll index to its initial state. + */ + resetScroll(): void; + + on(event: string, listener: (...args: any[]) => void): this; + + /** + * Received when the element is scrolled. + */ + on(event: "scroll", callback: () => void): this; + } + + /** + * DEPRECATED - Use Box with the scrollable and alwaysScroll options instead. + * A scrollable text box which can display and scroll text, as well as handle + * pre-existing newlines and escape codes. + */ + class ScrollableTextElement extends ScrollableBoxElement {} + + /** + * A box element which draws a simple box containing content or other elements. + */ + class BoxElement extends ScrollableTextElement implements IHasOptions { + constructor(opts: BoxOptions); + + /** + * Original options object. + */ + options: BoxOptions; + } + + interface TextOptions extends ElementOptions { + /** + * Fill the entire line with chosen bg until parent bg ends, even if there + * is not enough text to fill the entire width. + */ + fill?: boolean; + + /** + * Text alignment: left, center, or right. + */ + align?: Types.TAlign; + } + + /** + * An element similar to Box, but geared towards rendering simple text elements. + */ + class TextElement extends BlessedElement implements IHasOptions { + constructor(opts: TextOptions); + + /** + * Original options object. + */ + options: TextOptions; + } + + /** + * A simple line which can be line or bg styled. + */ + interface LineOptions extends BoxOptions { + /** + * Can be vertical or horizontal. + */ + orientation?: "vertical" | "horizontal"; + + /** + * Treated the same as a border object. (attributes can be contained in style). + */ + type?: string; + bg?: string; + fg?: string; + ch?: string; + } + + /** + * A simple line which can be line or bg styled. + */ + class LineElement extends BoxElement implements IHasOptions { + constructor(opts: LineOptions); + + /** + * Original options object. + */ + options: LineOptions; + } + + interface BigTextOptions extends BoxOptions { + /** + * bdf->json font file to use (see ttystudio for instructions on compiling BDFs to JSON). + */ + font?: string; + + /** + * bdf->json bold font file to use (see ttystudio for instructions on compiling BDFs to JSON). + */ + fontBold?: string; + + /** + * foreground character. (default: ' ') + */ + fch?: string; + } + + /** + * A box which can render content drawn as 8x14 cell characters using the terminus font. + */ + class BigTextElement extends BoxElement implements IHasOptions { + constructor(opts: BigTextOptions); + + /** + * Original options object. + */ + options: BigTextOptions; + } + + interface ListElementStyle { + selected?: any; + item?: any; + } + + interface ListOptions extends BoxOptions { + /** + * Style for a selected item. Style for an unselected item. + */ + style?: TStyle; + + /** + * An array of strings which become the list's items. + */ + items?: string[]; + + /** + * A function that is called when vi mode is enabled and the key / is pressed. This function accepts a + * callback function which should be called with the search string. The search string is then used to + * jump to an item that is found in items. + */ + search?(err: any, value?: string): void; + + /** + * Whether the list is interactive and can have items selected (Default: true). + */ + interactive?: boolean; + + /** + * Whether to automatically override tags and invert fg of item when selected (Default: true). + */ + invertSelected?: boolean; + } + + type ListElementEventType = + /** List was canceled (when esc is pressed with the keys option). */ + | "cancel" + /** Either a select or a cancel event was received. */ + | "action" + | "create item" + | "add item" + | "remove item" + | "insert item" + | "set items"; + + class ListElement extends BoxElement implements IHasOptions> { + constructor(opts: ListOptions); + + /** + * Original options object. + */ + options: ListOptions; + + /** + * Add an item based on a string. + */ + add(text: string): void; + + /** + * Add an item based on a string. + */ + addItem(text: string): void; + + /** + * Removes an item from the list. Child can be an element, index, or string. + */ + removeItem(child: BlessedElement): BlessedElement; + + /** + * Push an item onto the list. + */ + pushItem(child: BlessedElement): number; + + /** + * Pop an item off the list. + */ + popItem(): BlessedElement; + + /** + * Unshift an item onto the list. + */ + unshiftItem(child: BlessedElement): number; + + /** + * Shift an item off the list. + */ + shiftItem(): BlessedElement; + + /** + * Inserts an item to the list. Child can be an element, index, or string. + */ + insertItem(i: number, child: BlessedElement): void; + + /** + * Returns the item element. Child can be an element, index, or string. + */ + getItem(child: BlessedElement): BlessedElement; + + /** + * Set item to content. + */ + setItem(child: BlessedElement, content: BlessedElement | string): void; + + /** + * Remove and insert items to the list. + */ + spliceItem(i: number, n: number, ...items: BlessedElement[]): void; + + /** + * Clears all items from the list. + */ + clearItems(): void; + + /** + * Sets the list items to multiple strings. + */ + setItems(items: BlessedElement[]): void; + + /** + * Returns the item index from the list. Child can be an element, index, or string. + */ + getItemIndex(child: BlessedElement): number; + + /** + * Select an index of an item. + */ + select(index: number): void; + + /** + * Select item based on current offset. + */ + move(offset: number): void; + + /** + * Select item above selected. + */ + up(amount: number): void; + + /** + * Select item below selected. + */ + down(amount: number): void; + + /** + * Show/focus list and pick an item. The callback is executed with the result. + */ + pick(callback: () => void): void; + + /** + * Find an item based on its text content. + */ + fuzzyFind(arg: string | RegExp | (() => void)): void; + + on(event: string, listener: (...args: any[]) => void): this; + /** Received when an item is selected. */ + on(event: "select", callback: (item: BoxElement, index: number) => void): this; + on(event: ListElementEventType, callback: () => void): this; + on(event: "select item", callback: (item: BlessedElement, index: number) => void): this; + } + + interface FileManagerOptions extends ListOptions { + /** + * Current working directory. + */ + cwd?: string; + } + + class FileManagerElement extends ListElement implements IHasOptions { + constructor(opts: FileManagerOptions); + + /** + * Original options object. + */ + options: FileManagerOptions; + + /** + * Current working directory. + */ + cwd: string; + + /** + * Refresh the file list (perform a readdir on cwd and update the list items). + */ + refresh(cwd: string, callback: () => void): void; + refresh(callback?: () => void): void; + + /** + * Pick a single file and return the path in the callback. + */ + pick(cwd: string, callback: () => void): void; + pick(callback: () => void): void; + + /** + * Reset back to original cwd. + */ + reset(cwd: string, callback: () => void): void; + reset(callback?: () => void): void; + + on(event: string, listener: (...args: any[]) => void): this; + /** Received when an item is selected. */ + on(event: "cd", callback: (file: string, cwd: string) => void): this; + /** Received when an item is selected. */ + on(event: "file", callback: (file: string) => void): this; + on(event: "error", callback: (err: any, file: string) => void): this; + on(event: "refresh", callback: () => void): this; + } + + interface StyleListTable extends ListElementStyle { + /** + * Header style. + */ + header?: any; + + /** + * Cell style. + */ + cell?: any; + } + + interface ListTableOptions extends ListOptions { + /** + * Array of array of strings representing rows. + */ + rows?: string[]; + data?: string[][]; + + /** + * Spaces to attempt to pad on the sides of each cell. 2 by default: one space on each side + * (only useful if the width is shrunken). + */ + pad?: number; + + /** + * Do not draw inner cells. + */ + noCellBorders?: boolean; + + style?: StyleListTable; + } + + class ListTableElement extends ListElement implements IHasOptions { + constructor(opts: ListTableOptions); + + /** + * Original options object. + */ + options: ListTableOptions; + + /** + * Set rows in table. Array of arrays of strings. + * @example: + * + * table.setData([ + * [ 'Animals', 'Foods' ], + * [ 'Elephant', 'Apple' ], + * [ 'Bird', 'Orange' ] + * ]); + */ + setRows(rows: string[][]): void; + + /** + * Set rows in table. Array of arrays of strings. + * @example: + * + * table.setData([ + * [ 'Animals', 'Foods' ], + * [ 'Elephant', 'Apple' ], + * [ 'Bird', 'Orange' ] + * ]); + */ + setData(rows: string[][]): void; + } + + interface ListbarOptions extends BoxOptions { + style?: ListElementStyle; + + /** + * Set buttons using an object with keys as titles of buttons, containing of objects + * containing keys of keys and callback. + */ + commands: Types.ListbarCommand[]; + items: Types.ListbarCommand[]; + + /** + * Automatically bind list buttons to keys 0-9. + */ + autoCommandKeys: boolean; + } + + class ListbarElement extends BoxElement implements IHasOptions { + constructor(opts: ListbarOptions); + + /** + * Original options object. + */ + options: ListbarOptions; + + /** + * Set commands (see commands option above). + */ + setItems(commands: Types.ListbarCommand[]): void; + + /** + * Append an item to the bar. + */ + add(item: Types.ListbarCommand, callback: () => void): void; + + /** + * Append an item to the bar. + */ + addItem(item: Types.ListbarCommand, callback: () => void): void; + + /** + * Append an item to the bar. + */ + appendItem(item: Types.ListbarCommand, callback: () => void): void; + + /** + * Select an item on the bar. + */ + select(offset: number): void; + + /** + * Remove item from the bar. + */ + removeItem(child: BlessedElement): void; + + /** + * Move relatively across the bar. + */ + move(offset: number): void; + + /** + * Move left relatively across the bar. + */ + moveLeft(offset: number): void; + + /** + * Move right relatively across the bar. + */ + moveRight(offset: number): void; + + /** + * Select button and execute its callback. + */ + selectTab(index: number): void; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "set items" | "remove item" | "select tab", callback: () => void): this; + } + + interface FormOptions extends BoxOptions { + /** + * Allow default keys (tab, vi keys, enter). + */ + keys?: any; + + /** + * Allow vi keys. + */ + vi?: boolean; + } + + class FormElement extends BoxElement implements IHasOptions { + constructor(opts: FormOptions); + + /** + * Original options object. + */ + options: FormOptions; + + /** + * Last submitted data. + */ + submission: TFormData; + + /** + * Focus next form element. + */ + focusNext(): void; + + /** + * Focus previous form element. + */ + focusPrevious(): void; + + /** + * Submit the form. + */ + submit(): void; + + /** + * Discard the form. + */ + cancel(): void; + + /** + * Clear the form. + */ + reset(): void; + + on(event: string, listener: (...args: any[]) => void): this; + /** Form is submitted. Receives a data object. */ + on(event: "submit", callback: (out: TFormData) => void): this; + on(event: "cancel" | "reset", callback: () => void): this; + } + + interface InputOptions extends BoxOptions {} + + abstract class InputElement extends BoxElement { + constructor(opts: InputOptions); + } + + /** + * A box which allows multiline text input. + */ + interface TextareaOptions extends InputOptions { + /** + * Call readInput() when the element is focused. Automatically unfocus. + */ + inputOnFocus?: boolean; + } + + type TextareaElementEventType = + /** Value is an error. */ + | "error" + /** Value is submitted (enter). */ + | "submit" + /** Value is discared (escape). */ + | "cancel" + /** Either submit or cancel. */ + | "action"; + + class TextareaElement extends InputElement implements IHasOptions { + constructor(opts: TextareaOptions); + + /** + * Original options object. + */ + options: TextareaOptions; + + /** + * The input text. read-only. + */ + value: string; + + /** + * Submit the textarea (emits submit). + */ + submit(): void; + + /** + * Cancel the textarea (emits cancel). + */ + cancel(): void; + + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + readInput(callback?: (err: any, value?: string) => void): void; + + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + input(callback: (err: any, value?: string) => void): void; + + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + setInput(callback: (err: any, value?: string) => void): void; + + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + readEditor(callback: (err: any, value?: string) => void): void; + + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + editor(callback: (err: any, value?: string) => void): void; + + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + setEditor(callback: (err: any, value?: string) => void): void; + + /** + * The same as this.value, for now. + */ + getValue(): string; + + /** + * Clear input. + */ + clearValue(): void; + + /** + * Set value. + */ + setValue(text: string): void; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: TextareaElementEventType, callback: (err: any) => void): this; + } + + interface TextboxOptions extends TextareaOptions { + /** + * Completely hide text. + */ + secret?: boolean; + + /** + * Replace text with asterisks (*). + */ + censor?: boolean; + } + + class TextboxElement extends TextareaElement implements IHasOptions { + constructor(opts: TextboxOptions); + + /** + * Original options object. + */ + options: TextboxOptions; + + /** + * Completely hide text. + */ + secret: boolean; + + /** + * Replace text with asterisks (*). + */ + censor: boolean; + } + + interface ButtonOptions extends BoxOptions {} + + class ButtonElement extends InputElement implements IHasOptions { + constructor(opts: ButtonOptions); + + /** + * Original options object. + */ + options: ButtonOptions; + + /** + * Press button. Emits press. + */ + press(): void; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "press", callback: () => void): this; + } + + interface CheckboxOptions extends BoxOptions { + /** + * whether the element is checked or not. + */ + checked?: boolean; + + /** + * enable mouse support. + */ + mouse?: boolean; + } + + /** + * A checkbox which can be used in a form element. + */ + class CheckboxElement extends InputElement implements IHasOptions { + constructor(options?: CheckboxOptions); + + /** + * Original options object. + */ + options: CheckboxOptions; + + /** + * the text next to the checkbox (do not use setcontent, use `check.text = ''`). + */ + text: string; + + /** + * whether the element is checked or not. + */ + checked: boolean; + + /** + * same as `checked`. + */ + value: boolean; + + /** + * check the element. + */ + check(): void; + + /** + * uncheck the element. + */ + uncheck(): void; + + /** + * toggle checked state. + */ + toggle(): void; + } + + interface RadioSetOptions extends BoxOptions {} + + /** + * An element wrapping RadioButtons. RadioButtons within this element will be mutually exclusive + * with each other. + */ + abstract class RadioSetElement extends BoxElement { + constructor(opts: RadioSetOptions); + } + + interface RadioButtonOptions extends BoxOptions {} + + /** + * A radio button which can be used in a form element. + */ + abstract class RadioButtonElement extends CheckboxElement { + constructor(opts: RadioButtonOptions); + } + + interface PromptOptions extends BoxOptions {} + + /** + * A prompt box containing a text input, okay, and cancel buttons (automatically hidden). + */ + class PromptElement extends BoxElement implements IHasOptions { + constructor(opts: PromptOptions); + + options: PromptOptions; + + /** + * Show the prompt and wait for the result of the textbox. Set text and initial value. + */ + input(text: string, value: string, callback: (err: any, value: string) => void): void; + setInput(text: string, value: string, callback: (err: any, value: string) => void): void; + readInput(text: string, value: string, callback: (err: any, value: string) => void): void; + } + + interface QuestionOptions extends BoxOptions {} + + /** + * A question box containing okay and cancel buttons (automatically hidden). + */ + class QuestionElement extends BoxElement implements IHasOptions { + constructor(opts: QuestionOptions); + + options: QuestionOptions; + + /** + * Ask a question. callback will yield the result. + */ + ask(question: string, callback: (err: any, value: string) => void): void; + } + + interface MessageOptions extends BoxOptions {} + + /** + * A box containing a message to be displayed (automatically hidden). + */ + class MessageElement extends BoxElement implements IHasOptions { + constructor(opts: MessageOptions); + + options: MessageOptions; + + /** + * Display a message for a time (default is 3 seconds). Set time to 0 for a + * perpetual message that is dismissed on keypress. + */ + log(text: string, time: number, callback: (err: any) => void): void; + log(text: string, callback: (err: any) => void): void; + display(text: string, time: number, callback: (err: any) => void): void; + display(text: string, callback: (err: any) => void): void; + + /** + * Display an error in the same way. + */ + error(text: string, time: number, callback: () => void): void; + error(text: string, callback: () => void): void; + } + + interface LoadingOptions extends BoxOptions {} + + /** + * A box with a spinning line to denote loading (automatically hidden). + */ + class LoadingElement extends BoxElement implements IHasOptions { + constructor(opts: LoadingOptions); + + options: LoadingOptions; + + /** + * Display the loading box with a message. Will lock keys until stop is called. + */ + load(text: string): void; + + /** + * Hide loading box. Unlock keys. + */ + stop(): void; + } + + interface ProgressBarOptions extends BoxOptions { + /** + * can be `horizontal` or `vertical`. + */ + orientation: string; + + /** + * the character to fill the bar with (default is space). + */ + pch: string; + + /** + * the amount filled (0 - 100). + */ + filled: number; + + /** + * same as `filled`. + */ + value: number; + + /** + * enable key support. + */ + keys: boolean; + + /** + * enable mouse support. + */ + mouse: boolean; + } + + /** + * A progress bar allowing various styles. This can also be used as a form input. + */ + class ProgressBarElement extends InputElement implements IHasOptions { + constructor(options?: ProgressBarOptions); + + options: ProgressBarOptions; + + /** + * progress the bar by a fill amount. + */ + progress(amount: number): void; + + /** + * set progress to specific amount. + */ + setProgress(amount: number): void; + + /** + * reset the bar. + */ + reset(): void; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "reset" | "complete", callback: () => void): this; + } + + interface LogOptions extends ScrollableTextOptions { + /** + * amount of scrollback allowed. default: Infinity. + */ + scrollback?: number; + + /** + * scroll to bottom on input even if the user has scrolled up. default: false. + */ + scrollOnInput?: boolean; + } + + /** + * A log permanently scrolled to the bottom. + */ + class Log extends ScrollableTextElement implements IHasOptions { + constructor(options?: LogOptions); + + options: LogOptions; + + /** + * amount of scrollback allowed. default: Infinity. + */ + scrollback: number; + + /** + * scroll to bottom on input even if the user has scrolled up. default: false. + */ + scrollOnInput: boolean; + + /** + * add a log line. + */ + log(text: string): void; + + /** + * add a log line. + */ + add(text: string): void; + } + + interface TableOptions extends BoxOptions { + /** + * array of array of strings representing rows (same as `data`). + */ + rows?: string[][]; + + /** + * array of array of strings representing rows (same as `rows`). + */ + data?: string[][]; + + /** + * spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). + */ + pad?: number; + + /** + * do not draw inner cells. + */ + noCellBorders?: boolean; + + /** + * fill cell borders with the adjacent background color. + */ + fillCellBorders?: boolean; + } + + /** + * A stylized table of text elements. + */ + class TableElement extends BoxElement implements IHasOptions { + constructor(opts: TableOptions); + + options: TableOptions; + + /** + * set rows in table. array of arrays of strings. + */ + setData(rows: string[][]): void; + + /** + * set rows in table. array of arrays of strings. + */ + setRows(rows: string[][]): void; + } + + interface TerminalOptions extends BoxOptions { + /** + * handler for input data. + */ + handler?(userInput: Buffer): void; + + /** + * name of shell. $SHELL by default. + */ + shell?: string; + + /** + * args for shell. + */ + args?: any; + + /** + * can be line, underline, and block. + */ + cursor?: "line" | "underline" | "block"; + + terminal?: string; + + /** + * Object for process env. + */ + env?: any; + } + + class TerminalElement extends BoxElement implements IHasOptions { + constructor(opts: TerminalOptions); + + options: TerminalOptions; + + /** + * reference to the headless term.js terminal. + */ + term: any; + + /** + * reference to the pty.js pseudo terminal. + */ + pty: any; + + /** + * write data to the terminal. + */ + write(data: string): void; + + /** + * nearly identical to `element.screenshot`, however, the specified region includes the terminal's + * _entire_ scrollback, rather than just what is visible on the screen. + */ + screenshot(xi?: number, xl?: number, yi?: number, yl?: number): string; + } + + interface ImageOptions extends BoxOptions { + /** + * path to image. + */ + file: string; + + /** + * path to w3mimgdisplay. if a proper w3mimgdisplay path is not given, blessed will search the + * entire disk for the binary. + */ + type: "ansi" | "overlay" | "w3m"; + } + + /** + * Display an image in the terminal (jpeg, png, gif) using w3mimgdisplay. Requires w3m to be installed. + * X11 required: works in xterm, urxvt, and possibly other terminals. + */ + class ImageElement extends BoxElement implements IHasOptions { + constructor(options?: ImageOptions); + + options: ImageOptions; + } + + interface ANSIImageOptions extends BoxOptions { + /** + * URL or path to PNG/GIF file. Can also be a buffer. + */ + file: string; + + /** + * Scale cellmap down (0-1.0) from its original pixel width/height (Default: 1.0). + */ + scale: number; + + /** + * This differs from other element's width or height in that only one + * of them is needed: blessed will maintain the aspect ratio of the image + * as it scales down to the proper number of cells. NOTE: PNG/GIF's are + * always automatically shrunken to size (based on scale) if a width or + * height is not given. + */ + width: number | string; + height: number | string; + + /** + * Add various "density" ASCII characters over the rendering to give the + * image more detail, similar to libcaca/libcucul (the library mplayer uses + * to display videos in the terminal). + */ + ascii: string; + + /** + * Whether to animate if the image is an APNG/animating GIF. If false, only + * display the first frame or IDAT (Default: true). + */ + animate: boolean; + + /** + * Set the speed of animation. Slower: 0.0-1.0. Faster: 1-1000. It cannot go + * faster than 1 frame per millisecond, so 1000 is the fastest. (Default: 1.0) + */ + speed: number; + + /** + * mem or cpu. If optimizing for memory, animation frames will be rendered to + * bitmaps as the animation plays, using less memory. Optimizing for cpu will + * precompile all bitmaps beforehand, which may be faster, but might also OOM + * the process on large images. (Default: mem). + */ + optimization: "mem" | "cpu"; + } + + /** + * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. + */ + class ANSIImageElement extends BoxElement implements IHasOptions { + constructor(options?: ANSIImageOptions); + + options: ANSIImageOptions; + + /** + * Image object from the png reader. + */ + img: Types.TImage; + + /** + * set the image in the box to a new path. + */ + setImage(img: string, callback: () => void): void; + + /** + * clear the current image. + */ + clearImage(callback: () => void): void; + + /** + * Play animation if it has been paused or stopped. + */ + play(): void; + + /** + * Pause animation. + */ + pause(): void; + + /** + * Stop animation. + */ + stop(): void; + } + + interface OverlayImageOptions extends BoxOptions { + /** + * Path to image. + */ + file: string; + + /** + * Render the file as ANSI art instead of using w3m to overlay Internally uses the + * ANSIImage element. See the ANSIImage element for more information/options. (Default: true). + */ + ansi: boolean; + + /** + * Path to w3mimgdisplay. If a proper w3mimgdisplay path is not given, blessed will + * search the entire disk for the binary. + */ + w3m: string; + + /** + * Whether to search /usr, /bin, and /lib for w3mimgdisplay (Default: true). + */ + search: string; + } + + /** + * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. + */ + class OverlayImageElement extends BoxElement implements IHasOptions { + constructor(options?: OverlayImageOptions); + + options: OverlayImageOptions; + + /** + * set the image in the box to a new path. + */ + setImage(img: string, callback: () => void): void; + + /** + * clear the current image. + */ + clearImage(callback: () => void): void; + + /** + * get the size of an image file in pixels. + */ + imageSize(img: string, callback: () => void): void; + + /** + * get the size of the terminal in pixels. + */ + termSize(callback: () => void): void; + + /** + * get the pixel to cell ratio for the terminal. + */ + getPixelRatio(callback: () => void): void; + } + + interface VideoOptions extends BoxOptions { + /** + * Video to play. + */ + file: string; + + /** + * Start time in seconds. + */ + start: number; + } + + class VideoElement extends BoxElement implements IHasOptions { + constructor(options?: VideoOptions); + + options: VideoOptions; + + /** + * The terminal element running mplayer or mpv. + */ + tty: any; + } + + interface LayoutOptions extends ElementOptions { + /** + * A callback which is called right before the children are iterated over to be rendered. Should return an + * iterator callback which is called on each child element: iterator(el, i). + */ + renderer?(): void; + + /** + * Using the default renderer, it provides two layouts: inline, and grid. inline is the default and will render + * akin to inline-block. grid will create an automatic grid based on element dimensions. The grid cells' + * width and height are always determined by the largest children in the layout. + */ + layout: "inline" | "inline-block" | "grid"; + } + + class LayoutElement extends BlessedElement implements IHasOptions { + constructor(options?: LayoutOptions); + + options: LayoutOptions; + + /** + * A callback which is called right before the children are iterated over to be rendered. Should return an + * iterator callback which is called on each child element: iterator(el, i). + */ + renderer(coords: PositionCoords): void; + + /** + * Check to see if a previous child element has been rendered and is visible on screen. This is only useful + * for checking child elements that have already been attempted to be rendered! see the example below. + */ + isRendered(el: BlessedElement): boolean; + + /** + * Get the last rendered and visible child element based on an index. This is useful for basing the position + * of the current child element on the position of the last child element. + */ + getLast(i: number): BlessedElement; + + /** + * Get the last rendered and visible child element coords based on an index. This is useful for basing the position + * of the current child element on the position of the last child element. See the example below. + */ + getLastCoords(i: number): PositionCoords; + } + + class Program { + /** + * Wrap the given text in terminal formatting codes corresponding to the given attribute + * name. The `attr` string can be of the form `red fg` or `52 bg` where `52` is a 0-255 + * integer color number. + */ + text(text: string, attr: string): string; } } -export = Blessed; +export namespace widget { + class Terminal extends Widgets.TerminalElement {} +} + +export function screen(options?: Widgets.IScreenOptions): Widgets.Screen; +export function box(options?: Widgets.BoxOptions): Widgets.BoxElement; +export function text(options?: Widgets.TextOptions): Widgets.TextElement; +export function line(options?: Widgets.LineOptions): Widgets.LineElement; +export function scrollablebox(options?: Widgets.BoxOptions): Widgets.BoxElement; +export function scrollabletext(options?: Widgets.BoxOptions): Widgets.BoxElement; +export function bigtext(options?: Widgets.BigTextOptions): Widgets.BigTextElement; +export function list(options?: Widgets.ListOptions): Widgets.ListElement; +export function filemanager(options?: Widgets.FileManagerOptions): Widgets.FileManagerElement; +export function listtable(options?: Widgets.ListTableOptions): Widgets.ListTableElement; +export function listbar(options?: Widgets.ListbarOptions): Widgets.ListbarElement; +export function form(options?: Widgets.FormOptions): Widgets.FormElement; +export function input(options?: Widgets.InputOptions): Widgets.InputElement; +export function textarea(options?: Widgets.TextareaOptions): Widgets.TextareaElement; +export function textbox(options?: Widgets.TextboxOptions): Widgets.TextboxElement; +export function button(options?: Widgets.ButtonOptions): Widgets.ButtonElement; +export function checkbox(options?: Widgets.CheckboxOptions): Widgets.CheckboxElement; +export function radioset(options?: Widgets.RadioSetOptions): Widgets.RadioSetElement; +export function radiobutton(options?: Widgets.RadioButtonOptions): Widgets.RadioButtonElement; +export function table(options?: Widgets.TableOptions): Widgets.TableElement; +export function prompt(options?: Widgets.PromptOptions): Widgets.PromptElement; +export function question(options?: Widgets.QuestionOptions): Widgets.QuestionElement; +export function message(options?: Widgets.MessageOptions): Widgets.MessageElement; +export function loading(options?: Widgets.LoadingOptions): Widgets.LoadingElement; +export function log(options?: Widgets.LogOptions): Widgets.Log; +export function progressbar(options?: Widgets.ProgressBarOptions): Widgets.ProgressBarElement; +export function terminal(options?: Widgets.TerminalOptions): Widgets.TerminalElement; +export function layout(options?: Widgets.LayoutOptions): Widgets.LayoutElement; +export function escape(item: any): any; + +export const colors: { + match(hexColor: string): string; +}; diff --git a/types/bluebird-retry/bluebird-retry-tests.ts b/types/bluebird-retry/bluebird-retry-tests.ts index eb3260a007..e9beaf5562 100644 --- a/types/bluebird-retry/bluebird-retry-tests.ts +++ b/types/bluebird-retry/bluebird-retry-tests.ts @@ -1,13 +1,13 @@ import Promise = require('bluebird'); import retry = require('bluebird-retry'); -function promiseSuccess(text:string) { +function promiseSuccess(text: string) { return Promise.resolve(text); -}; +} -var count = 0; +let count = 0; function myfunc() { - console.log('myfunc called ' + (++count) + ' times'); + console.log(`myfunc called ${++count} times`); if (count < 3) { throw new Error('i fail the first two times'); } else { @@ -16,18 +16,17 @@ function myfunc() { } retry(myfunc) - .done(function(result) { console.log(result); } ); + .done(result => { console.log(result); }); - -//Options example +// Options example function logFail() { console.log(new Date().toISOString()); throw new Error('bail'); } -var options:retry.Options = { +const options: retry.Options = { max_tries: 4, interval: 500 }; -retry(logFail, options); \ No newline at end of file +retry(logFail, options); diff --git a/types/bluebird-retry/index.d.ts b/types/bluebird-retry/index.d.ts index 97d756524b..358c75936d 100644 --- a/types/bluebird-retry/index.d.ts +++ b/types/bluebird-retry/index.d.ts @@ -1,17 +1,15 @@ -// Type definitions for bluebird-retry +// Type definitions for bluebird-retry 0.11 // Project: https://github.com/jut-io/bluebird-retry // Definitions by: Pascal Vomhoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -/// - import Promise = require('bluebird'); declare function retry(func: (param: T) => void, options?: retry.Options): Promise; declare namespace retry { - export interface Options { + interface Options { interval?: number; backoff?: number; max_interval?: number; @@ -22,7 +20,6 @@ declare namespace retry { context?: any; args?: any; } - } export = retry; diff --git a/types/bluebird-retry/tslint.json b/types/bluebird-retry/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/bluebird-retry/tslint.json +++ b/types/bluebird-retry/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/bootstrap-fileinput/index.d.ts b/types/bootstrap-fileinput/index.d.ts index 8a7df2dbbc..61a53b12bb 100644 --- a/types/bootstrap-fileinput/index.d.ts +++ b/types/bootstrap-fileinput/index.d.ts @@ -6,10 +6,14 @@ /// -interface JQuery { - fileinput: (options?: BootstrapFileInput.FileInputOptions) => JQuery; -} +export = BootstrapFileInput; +export as namespace BootstrapFileInput; +declare global { + interface JQuery { + fileinput: (options?: BootstrapFileInput.FileInputOptions) => JQuery; + } +} declare module BootstrapFileInput { interface FileInputOptions { @@ -19,6 +23,11 @@ declare module BootstrapFileInput { The locale JS file for the language code must be defined as mentioned in the translations section: http://plugins.krajee.com/file-input#translations */ language?: string; + + /** + * Theming + */ + theme?: string; /** Whether to display the file caption. Defaults to true. diff --git a/types/box2d/index.d.ts b/types/box2d/index.d.ts index 77a132592e..d17eb2c8f6 100644 --- a/types/box2d/index.d.ts +++ b/types/box2d/index.d.ts @@ -5147,7 +5147,7 @@ declare namespace Box2D.Dynamics.Joints { /** * The pulley joint is connected to two bodies and two fixed ground points. The pulley supports a ratio such that: length1 + ratio length2 <= constant Yes, the force transmitted is scaled by the ratio. The pulley also enforces a maximum length limit on both sides. This is useful to prevent one side of the pulley hitting the top. **/ - export class b2PullyJoint extends b2Joint { + export class b2PulleyJoint extends b2Joint { /** * Get the anchor point on bodyA in world coordinates. @@ -5207,7 +5207,7 @@ declare namespace Box2D.Dynamics.Joints { /** * Pulley joint definition. This requires two ground anchors, two dynamic body anchor points, max lengths for each side, and a pulley ratio. **/ - export class b2PullyJointDef extends b2JointDef { + export class b2PulleyJointDef extends b2JointDef { /** * The first ground anchor in world coordinates. This point never moves. diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index abfd4ddd98..1e9e3b55bc 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -1,11 +1,14 @@ -// Type definitions for bull 3.0 +// Type definitions for bull 3.3 // Project: https://github.com/OptimalBits/bull // Definitions by: Bruno Grieder // Cameron Crothers // Marshall Cottrell +// Weeco // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as Redis from "ioredis"; +import * as Promise from "bluebird"; /** * This is the Queue constructor. @@ -13,407 +16,591 @@ import * as Redis from "ioredis"; * Everytime the same queue is instantiated it tries to process all the old jobs that may exist from a previous unfinished session. */ declare const Bull: { - // tslint:disable:unified-signatures - (queueName: string, opts?: Bull.QueueOptions): Bull.Queue; - (queueName: string, url?: string): Bull.Queue; - new (queueName: string, opts?: Bull.QueueOptions): Bull.Queue; - new (queueName: string, url?: string): Bull.Queue; - // tslint:enable:unified-signatures + // tslint:disable:unified-signatures + (queueName: string, opts?: Bull.QueueOptions): Bull.Queue; + (queueName: string, url?: string): Bull.Queue; + new (queueName: string, opts?: Bull.QueueOptions): Bull.Queue; + new (queueName: string, url?: string): Bull.Queue; + // tslint:enable:unified-signatures }; declare namespace Bull { - interface QueueOptions { - /** - * Options passed directly to the `ioredis` constructor - */ - redis?: Redis.RedisOptions; - - /** - * When specified, the `Queue` will use this function to create new `ioredis` client connections. - * This is useful if you want to re-use connections. - */ - createClient?(type: 'client' | 'subscriber', redisOpts?: Redis.RedisOptions): Redis.Redis; - - /** - * Prefix to use for all redis keys - */ - prefix?: string; - - settings?: AdvancedSettings; - } - - interface AdvancedSettings { - /** - * Key expiration time for job locks - */ - lockDuration?: number; - - /** - * How often check for stalled jobs (use 0 for never checking) - */ - stalledInterval?: number; - - /** - * Max amount of times a stalled job will be re-processed - */ - maxStalledCount?: number; - - /** - * Poll interval for delayed jobs and added jobs - */ - guardInterval?: number; - - /** - * Delay before processing next job in case of internal error - */ - retryProcessDelay?: number; - } - - type DoneCallback = (error?: Error | null, value?: any) => void; - - type JobId = number | string; - - interface Job { - id: JobId; - - /** - * The custom data passed when the job was created - */ - data: any; - - /** - * Report progress on a job - */ - progress(value: any): Promise; - - /** - * Removes a job from the queue and from any lists it may be included in. - * @returns A promise that resolves when the job is removed. - */ - remove(): Promise; - - /** - * Re-run a job that has failed. - * @returns A promise that resolves when the job is scheduled for retry. - */ - retry(): Promise; - - /** - * Returns a promise the resolves when the job has been finished. - * TODO: Add a watchdog to check if the job has finished periodically. - * since pubsub does not give any guarantees. - */ - finished(): Promise; - - /** - * Promotes a job that is currently "delayed" to the "waiting" state and executed as soon as possible. - */ - promote(): Promise; - } - - type JobStatus = 'completed' | 'waiting' | 'active' | 'delayed' | 'failed'; - - interface BackoffOptions { - /** - * Backoff type, which can be either `fixed` or `exponential` - */ - type: 'fixed' | 'exponential'; - - /** - * Backoff delay, in milliseconds - */ - delay: number; - } - - interface RepeatOptions { - /** - * Cron pattern specifying when the job should execute - */ - cron: string; - - /** - * Timezone - */ - tz?: string; - - /** - * End date when the repeat job should stop repeating - */ - endDate?: Date | string | number; - } - - interface JobOptions { - /** - * Optional priority value. ranges from 1 (highest priority) to MAX_INT (lowest priority). - * Note that using priorities has a slight impact on performance, so do not use it if not required - */ - priority?: number; - - /** - * An amount of miliseconds to wait until this job can be processed. - * Note that for accurate delays, both server and clients should have their clocks synchronized. [optional] - */ - delay?: number; - - /** - * The total number of attempts to try the job until it completes - */ - attempts?: number; - - /** - * Repeat job according to a cron specification - */ - repeat?: RepeatOptions; - - /** - * Backoff setting for automatic retries if the job fails - */ - backoff?: number | BackoffOptions; - - /** - * A boolean which, if true, adds the job to the right - * of the queue instead of the left (default false) - */ - lifo?: boolean; - - /** - * The number of milliseconds after which the job should be fail with a timeout error - */ - timeout?: number; - - /** - * Override the job ID - by default, the job ID is a unique - * integer, but you can use this setting to override it. - * If you use this option, it is up to you to ensure the - * jobId is unique. If you attempt to add a job with an id that - * already exists, it will not be added. - */ - jobId?: JobId; - - /** - * A boolean which, if true, removes the job when it successfully completes. - * Default behavior is to keep the job in the completed set. - */ - removeOnComplete?: boolean; - - /** - * A boolean which, if true, removes the job when it fails after all attempts - * Default behavior is to keep the job in the completed set. - */ - removeOnFail?: boolean; - } - - interface JobCounts { - wait: number; - active: number; - completed: number; - failed: number; - delayed: number; - } - - interface Queue { - /** - * Returns a promise that resolves when Redis is connected and the queue is ready to accept jobs. - * This replaces the `ready` event emitted on Queue in previous verisons. - */ - isReady(): Promise; - - /** - * Defines a processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * - * The done callback can be called with an Error instance, to signal that the job did not complete successfully, - * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. - * Errors will be passed as a second argument to the "failed" event; - * results, as a second argument to the "completed" event. - * - * concurrency: Bull will then call you handler in parallel respecting this max number. - */ - process(concurrency: number, callback: (job: Job, done: DoneCallback) => void): void; - - /** - * Defines a processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * - * The done callback can be called with an Error instance, to signal that the job did not complete successfully, - * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. - * Errors will be passed as a second argument to the "failed" event; - * results, as a second argument to the "completed" event. - */ - process(callback: (job: Job, done: DoneCallback) => void): void; - - /** - * Defines a processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * - * A promise must be returned to signal job completion. - * If the promise is rejected, the error will be passed as a second argument to the "failed" event. - * If it is resolved, its value will be the "completed" event's second argument. - * - * concurrency: Bull will then call you handler in parallel respecting this max number. - */ - process(concurrency: number, callback: (job: Job) => void): Promise; - - /** - * Defines a processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * - * A promise must be returned to signal job completion. - * If the promise is rejected, the error will be passed as a second argument to the "failed" event. - * If it is resolved, its value will be the "completed" event's second argument. - */ - process(callback: (job: Job) => void): Promise; - - /** - * Creates a new job and adds it to the queue. - * If the queue is empty the job will be executed directly, - * otherwise it will be placed in the queue and executed as soon as possible. - */ - add(data: any, opts?: JobOptions): Promise; - - /** - * Returns a promise that resolves when the queue is paused. - * The pause is global, meaning that all workers in all queue instances for a given queue will be paused. - * A paused queue will not process new jobs until resumed, - * but current jobs being processed will continue until they are finalized. - * - * Pausing a queue that is already paused does nothing. - */ - pause(): Promise; - - /** - * Returns a promise that resolves when the queue is resumed after being paused. - * The resume is global, meaning that all workers in all queue instances for a given queue will be resumed. - * - * Resuming a queue that is not paused does nothing. - */ - resume(): Promise; - - /** - * Returns a promise that returns the number of jobs in the queue, waiting or paused. - * Since there may be other processes adding or processing jobs, this value may be true only for a very small amount of time. - */ - count(): Promise; - - /** - * Empties a queue deleting all the input lists and associated jobs. - */ - empty(): Promise; - - /** - * Closes the underlying redis client. Use this to perform a graceful shutdown. - * - * `close` can be called from anywhere, with one caveat: - * if called from within a job handler the queue won't close until after the job has been processed - */ - close(): Promise; - - /** - * Returns a promise that will return the job instance associated with the jobId parameter. - * If the specified job cannot be located, the promise callback parameter will be set to null. - */ - getJob(jobId: JobId): Promise; - - /** - * Returns a promise that resolves with the job counts for the given queue - */ - getJobCounts(): Promise; - - /** - * Tells the queue remove all jobs created outside of a grace period in milliseconds. - * You can clean the jobs with the following states: completed, waiting, active, delayed, and failed. - */ - clean(grace: number, status?: JobStatus, limit?: number): Promise; - - // tslint:disable:unified-signatures - - /** - * Listens to queue events - */ - on(event: string, callback: (...args: any[]) => void): this; - - /** - * An error occured - */ - on(event: 'error', callback: ErrorEventCallback): this; - - /** - * A job has started. You can use `jobPromise.cancel()` to abort it - */ - on(event: 'active', callback: ActiveEventCallback): this; - - /** - * A job has been marked as stalled. - * This is useful for debugging job workers that crash or pause the event loop. - */ - on(event: 'stalled', callback: StalledEventCallback): this; - - /** - * A job's progress was updated - */ - on(event: 'progress', callback: ProgressEventCallback): this; - - /** - * A job successfully completed with a `result` - */ - on(event: 'completed', callback: CompletedEventCallback): this; - - /** - * A job failed with `err` as the reason - */ - on(event: 'failed', callback: FailedEventCallback): this; - - /** - * The queue has been paused - */ - on(event: 'paused', callback: EventCallback): this; - - /** - * The queue has been resumed - */ - on(event: 'resumed', callback: EventCallback): this; - - /** - * Old jobs have been cleaned from the queue. - * `jobs` is an array of jobs that were removed, and `type` is the type of those jobs. - * - * @see Queue#clean() for details - */ - on(event: 'cleaned', callback: CleanedEventCallback): this; - - // tslint:enable:unified-signatures - } - - type EventCallback = () => void; - - type ErrorEventCallback = (error: Error) => void; - - interface JobPromise { - /** - * Abort this job - */ - cancel(): void; - } - - type ActiveEventCallback = (job: Job, jobPromise?: JobPromise) => void; - - type StalledEventCallback = (job: Job) => void; - - type ProgressEventCallback = (job: Job, progress: any) => void; - - type CompletedEventCallback = (job: Job, result: any) => void; - - type FailedEventCallback = (job: Job, error: Error) => void; - - type CleanedEventCallback = (jobs: Job[], status: JobStatus) => void; + interface RateLimiter { + /** Max numbers of jobs processed */ + max: number; + /** Per duration in milliseconds */ + duration: number; + } + + interface QueueOptions { + /** + * Options passed directly to the `ioredis` constructor + */ + redis?: Redis.RedisOptions; + + /** + * When specified, the `Queue` will use this function to create new `ioredis` client connections. + * This is useful if you want to re-use connections. + */ + createClient?(type: 'client' | 'subscriber', redisOpts?: Redis.RedisOptions): Redis.Redis; + + /** + * Prefix to use for all redis keys + */ + prefix?: string; + + settings?: AdvancedSettings; + + limiter?: RateLimiter; + } + + interface AdvancedSettings { + /** + * Key expiration time for job locks + */ + lockDuration?: number; + + /** + * How often check for stalled jobs (use 0 for never checking) + */ + stalledInterval?: number; + + /** + * Max amount of times a stalled job will be re-processed + */ + maxStalledCount?: number; + + /** + * Poll interval for delayed jobs and added jobs + */ + guardInterval?: number; + + /** + * Delay before processing next job in case of internal error + */ + retryProcessDelay?: number; + } + + type DoneCallback = (error?: Error | null, value?: any) => void; + + type JobId = number | string; + + interface Job { + id: JobId; + + /** + * The custom data passed when the job was created + */ + data: any; + + /** + * Report progress on a job + */ + progress(value: any): Promise; + + /** + * Returns a promise resolving to the current job's status. + * Please take note that the implementation of this method is not very efficient, nor is + * it atomic. If your queue does have a very large quantity of jobs, you may want to + * avoid using this method. + */ + getState(): Promise; + + /** + * Update a specific job's data. Promise resolves when the job has been updated. + */ + update(data: any): Promise; + + /** + * Removes a job from the queue and from any lists it may be included in. + * The returned promise resolves when the job has been removed. + */ + remove(): Promise; + + /** + * Re-run a job that has failed. The returned promise resolves when the job + * has been scheduled for retry. + */ + retry(): Promise; + + /** + * Returns a promise that resolves to the returned data when the job has been finished. + * TODO: Add a watchdog to check if the job has finished periodically. + * since pubsub does not give any guarantees. + */ + finished(): Promise; + + /** + * Promotes a job that is currently "delayed" to the "waiting" state and executed as soon as possible. + */ + promote(): Promise; + } + + type JobStatus = 'completed' | 'waiting' | 'active' | 'delayed' | 'failed'; + + interface BackoffOptions { + /** + * Backoff type, which can be either `fixed` or `exponential` + */ + type: 'fixed' | 'exponential'; + + /** + * Backoff delay, in milliseconds + */ + delay: number; + } + + interface RepeatOptions { + /** + * Cron pattern specifying when the job should execute + */ + cron: string; + + /** + * Timezone + */ + tz?: string; + + /** + * End date when the repeat job should stop repeating + */ + endDate?: Date | string | number; + } + + interface JobOptions { + /** + * Optional priority value. ranges from 1 (highest priority) to MAX_INT (lowest priority). + * Note that using priorities has a slight impact on performance, so do not use it if not required + */ + priority?: number; + + /** + * An amount of miliseconds to wait until this job can be processed. + * Note that for accurate delays, both server and clients should have their clocks synchronized. [optional] + */ + delay?: number; + + /** + * The total number of attempts to try the job until it completes + */ + attempts?: number; + + /** + * Repeat job according to a cron specification + */ + repeat?: RepeatOptions; + + /** + * Backoff setting for automatic retries if the job fails + */ + backoff?: number | BackoffOptions; + + /** + * A boolean which, if true, adds the job to the right + * of the queue instead of the left (default false) + */ + lifo?: boolean; + + /** + * The number of milliseconds after which the job should be fail with a timeout error + */ + timeout?: number; + + /** + * Override the job ID - by default, the job ID is a unique + * integer, but you can use this setting to override it. + * If you use this option, it is up to you to ensure the + * jobId is unique. If you attempt to add a job with an id that + * already exists, it will not be added. + */ + jobId?: JobId; + + /** + * A boolean which, if true, removes the job when it successfully completes. + * Default behavior is to keep the job in the completed set. + */ + removeOnComplete?: boolean; + + /** + * A boolean which, if true, removes the job when it fails after all attempts + * Default behavior is to keep the job in the completed set. + */ + removeOnFail?: boolean; + } + + interface JobCounts { + wait: number; + active: number; + completed: number; + failed: number; + delayed: number; + } + + interface JobInformation { + key: string; + name: string; + id?: string; + endDate?: number; + tz?: string; + cron: string; + next: number; + } + + interface Queue { + /** + * Returns a promise that resolves when Redis is connected and the queue is ready to accept jobs. + * This replaces the `ready` event emitted on Queue in previous verisons. + */ + isReady(): Promise; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * The done callback can be called with an Error instance, to signal that the job did not complete successfully, + * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; + * results, as a second argument to the "completed" event. + */ + process(callback: (job: Job, done: DoneCallback) => void): void; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * A promise must be returned to signal job completion. + * If the promise is rejected, the error will be passed as a second argument to the "failed" event. + * If it is resolved, its value will be the "completed" event's second argument. + */ + process(callback: (job: Job) => void): Promise; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * A promise must be returned to signal job completion. + * If the promise is rejected, the error will be passed as a second argument to the "failed" event. + * If it is resolved, its value will be the "completed" event's second argument. + * + * @param concurrency Bull will then call you handler in parallel respecting this max number. + */ + process(concurrency: number, callback: (job: Job) => void): Promise; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * The done callback can be called with an Error instance, to signal that the job did not complete successfully, + * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; + * results, as a second argument to the "completed" event. + * + * @param concurrency Bull will then call you handler in parallel respecting this max number. + */ + process(concurrency: number, callback: (job: Job, done: DoneCallback) => void): void; + + /** + * Defines a named processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * A promise must be returned to signal job completion. + * If the promise is rejected, the error will be passed as a second argument to the "failed" event. + * If it is resolved, its value will be the "completed" event's second argument. + * + * @param name Bull will only call the handler if the job name matches + */ + // tslint:disable-next-line:unified-signatures + process(name: string, callback: (job: Job) => void): Promise; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * The done callback can be called with an Error instance, to signal that the job did not complete successfully, + * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; + * results, as a second argument to the "completed" event. + * + * @param name Bull will only call the handler if the job name matches + */ + // tslint:disable-next-line:unified-signatures + process(name: string, callback: (job: Job, done: DoneCallback) => void): void; + + /** + * Defines a named processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * A promise must be returned to signal job completion. + * If the promise is rejected, the error will be passed as a second argument to the "failed" event. + * If it is resolved, its value will be the "completed" event's second argument. + * + * @param name Bull will only call the handler if the job name matches + * @param concurrency Bull will then call you handler in parallel respecting this max number. + */ + process(name: string, concurrency: number, callback: (job: Job) => void): Promise; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * The done callback can be called with an Error instance, to signal that the job did not complete successfully, + * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; + * results, as a second argument to the "completed" event. + * + * @param name Bull will only call the handler if the job name matches + * @param concurrency Bull will then call you handler in parallel respecting this max number. + */ + process(name: string, concurrency: number, callback: (job: Job, done: DoneCallback) => void): void; + + /** + * Creates a new job and adds it to the queue. + * If the queue is empty the job will be executed directly, + * otherwise it will be placed in the queue and executed as soon as possible. + */ + add(data: any, opts?: JobOptions): Promise; + + /** + * Creates a new named job and adds it to the queue. + * If the queue is empty the job will be executed directly, + * otherwise it will be placed in the queue and executed as soon as possible. + */ + add(name: string, data: any, opts?: JobOptions): Promise; + + /** + * Returns a promise that resolves when the queue is paused. + * The pause is global, meaning that all workers in all queue instances for a given queue will be paused. + * A paused queue will not process new jobs until resumed, + * but current jobs being processed will continue until they are finalized. + * + * Pausing a queue that is already paused does nothing. + */ + pause(): Promise; + + /** + * Returns a promise that resolves when the queue is resumed after being paused. + * The resume is global, meaning that all workers in all queue instances for a given queue will be resumed. + * + * Resuming a queue that is not paused does nothing. + */ + resume(): Promise; + + /** + * Returns a promise that returns the number of jobs in the queue, waiting or paused. + * Since there may be other processes adding or processing jobs, this value may be true only for a very small amount of time. + */ + count(): Promise; + + /** + * Empties a queue deleting all the input lists and associated jobs. + */ + empty(): Promise; + + /** + * Closes the underlying redis client. Use this to perform a graceful shutdown. + * + * `close` can be called from anywhere, with one caveat: + * if called from within a job handler the queue won't close until after the job has been processed + */ + close(): Promise; + + /** + * Returns a promise that will return the job instance associated with the jobId parameter. + * If the specified job cannot be located, the promise callback parameter will be set to null. + */ + getJob(jobId: JobId): Promise; + + /** + * Returns a promise that will return an array with the active jobs between start and end. + */ + getActive(start?: number, end?: number): Promise; + + /** + * Returns a promise that will return an array with the delayed jobs between start and end. + */ + getDelayed(start?: number, end?: number): Promise; + + /** + * Returns a promise that will return an array with the completed jobs between start and end. + */ + getCompleted(start?: number, end?: number): Promise; + + /** + * Returns a promise that will return an array with the failed jobs between start and end. + */ + getFailed(start?: number, end?: number): Promise; + + /** + * Returns JobInformation of repeatable jobs (ordered descending). Provide a start and/or an end + * index to limit the number of results. Start defaults to 0, end to -1 and asc to false. + */ + getRepeatableJobs(start?: number, end?: number, asc?: boolean): Promise; + + /** + * ??? + */ + nextRepeatableJob(name: string, data: any, opts: JobOptions): Promise; + + /** + * Removes a given repeatable job. The RepeatOpts needs to be the same as the ones used for + * the job when it was added. + */ + removeRepeatable(repeat: RepeatOptions): Promise; + + /** + * Removes a given repeatable job. The RepeatOpts needs to be the same as the ones used for + * the job when it was added. + * + * name: The name of the to be removed job + */ + removeRepeatable(name: string, repeat: RepeatOptions): Promise; + + /** + * Returns a promise that resolves with the job counts for the given queue. + */ + getJobCounts(): Promise; + + /** + * Returns a promise that resolves with the quantity of completed jobs. + */ + getCompletedCount(): Promise; + + /** + * Returns a promise that resolves with the quantity of failed jobs. + */ + getFailedCount(): Promise; + + /** + * Returns a promise that resolves with the quantity of delayed jobs. + */ + getDelayedCount(): Promise; + + /** + * Returns a promise that resolves with the quantity of waiting jobs. + */ + getWaitingCount(): Promise; + + /** + * Returns a promise that resolves with the quantity of paused jobs. + */ + getPausedCount(): Promise; + + /** + * Returns a promise that resolves with the quantity of active jobs. + */ + getActiveCount(): Promise; + + /** + * Returns a promise that resolves to the quantity of repeatable jobs. + */ + getRepeatableCount(): Promise; + + /** + * Tells the queue remove all jobs created outside of a grace period in milliseconds. + * You can clean the jobs with the following states: completed, waiting, active, delayed, and failed. + * @param grace Grace period in milliseconds. + * @param status Status of the job to clean. Values are completed, wait, active, delayed, and failed. Defaults to completed. + * @param limit Maximum amount of jobs to clean per call. If not provided will clean all matching jobs. + */ + clean(grace: number, status?: JobStatus, limit?: number): Promise; + + // tslint:disable:unified-signatures + + /** + * Listens to queue events + */ + on(event: string, callback: (...args: any[]) => void): this; + + /** + * An error occured + */ + on(event: 'error', callback: ErrorEventCallback): this; + + /** + * A job has started. You can use `jobPromise.cancel()` to abort it + */ + on(event: 'active', callback: ActiveEventCallback): this; + + /** + * A job has been marked as stalled. + * This is useful for debugging job workers that crash or pause the event loop. + */ + on(event: 'stalled', callback: StalledEventCallback): this; + + /** + * A job's progress was updated + */ + on(event: 'progress', callback: ProgressEventCallback): this; + + /** + * A job successfully completed with a `result` + */ + on(event: 'completed', callback: CompletedEventCallback): this; + + /** + * A job failed with `err` as the reason + */ + on(event: 'failed', callback: FailedEventCallback): this; + + /** + * The queue has been paused + */ + on(event: 'paused', callback: EventCallback): this; + + /** + * The queue has been resumed + */ + on(event: 'resumed', callback: EventCallback): this; + + /** + * Old jobs have been cleaned from the queue. + * `jobs` is an array of jobs that were removed, and `type` is the type of those jobs. + * + * @see Queue#clean() for details + */ + on(event: 'cleaned', callback: CleanedEventCallback): this; + + // tslint:enable:unified-signatures + } + + type EventCallback = () => void; + + type ErrorEventCallback = (error: Error) => void; + + interface JobPromise { + /** + * Abort this job + */ + cancel(): void; + } + + type ActiveEventCallback = (job: Job, jobPromise?: JobPromise) => void; + + type StalledEventCallback = (job: Job) => void; + + type ProgressEventCallback = (job: Job, progress: any) => void; + + type CompletedEventCallback = (job: Job, result: any) => void; + + type FailedEventCallback = (job: Job, error: Error) => void; + + type CleanedEventCallback = (jobs: Job[], status: JobStatus) => void; } export = Bull; diff --git a/types/c3/index.d.ts b/types/c3/index.d.ts index eb727233a0..287e030445 100644 --- a/types/c3/index.d.ts +++ b/types/c3/index.d.ts @@ -636,7 +636,7 @@ declare namespace c3 { } interface LineOptions { - value: number; + value: string | number | Date; text?: string; axis?: string; position?: string; diff --git a/types/cassandra-driver/cassandra-driver-tests.ts b/types/cassandra-driver/cassandra-driver-tests.ts index 40971c7183..891c5a0167 100644 --- a/types/cassandra-driver/cassandra-driver-tests.ts +++ b/types/cassandra-driver/cassandra-driver-tests.ts @@ -1,9 +1,16 @@ import * as cassandra from 'cassandra-driver'; import * as util from 'util'; +import * as fs from 'fs'; -var client = new cassandra.Client({ contactPoints: ['h1', 'h2'], keyspace: 'ks1'}); +const client = new cassandra.Client({ + contactPoints: ['h1', 'h2'], + keyspace: 'ks1', + sslOptions: { + cert: fs.readFileSync('certFilePath') + } +}); -var query = 'SELECT email, last_name FROM user_profiles WHERE key=?'; +const query = 'SELECT email, last_name FROM user_profiles WHERE key=?'; client.execute(query, ['guy'], function(err, result) { console.log('got user profile with email ' + result.rows[0].email); }); diff --git a/types/cassandra-driver/index.d.ts b/types/cassandra-driver/index.d.ts index a581071dfb..bdaed6559c 100644 --- a/types/cassandra-driver/index.d.ts +++ b/types/cassandra-driver/index.d.ts @@ -12,11 +12,12 @@ export type ResultCallback = (err: Error, result: types.ResultSet) => void; import * as events from "events"; import * as stream from "stream"; +import * as tls from "tls"; import _Long = require("long"); export namespace policies { namespace addressResolution { - var EC2MultiRegionTranslator: EC2MultiRegionTranslatorStatic; + let EC2MultiRegionTranslator: EC2MultiRegionTranslatorStatic; interface AddressTranslator { translate(address: string, port: number, callback: Callback): void; @@ -32,10 +33,10 @@ export namespace policies { } namespace loadBalancing { - var DCAwareRoundRobinPolicy: DCAwareRoundRobinPolicyStatic; - var RoundRobinPolicy: RoundRobinPolicyStatic; - var TokenAwarePolicy: TokenAwarePolicyStatic; - var WhiteListPolicy: WhiteListPolicyStatic; + let DCAwareRoundRobinPolicy: DCAwareRoundRobinPolicyStatic; + let RoundRobinPolicy: RoundRobinPolicyStatic; + let TokenAwarePolicy: TokenAwarePolicyStatic; + let WhiteListPolicy: WhiteListPolicyStatic; interface LoadBalancingPolicy { init(client: Client, hosts: HostMap, callback: Callback): void; @@ -72,8 +73,8 @@ export namespace policies { } namespace reconnection { - var ConstantReconnectionPolicy: ConstantReconnectionPolicyStatic; - var ExponentialReconnectionPolicy: ExponentialReconnectionPolicyStatic; + let ConstantReconnectionPolicy: ConstantReconnectionPolicyStatic; + let ExponentialReconnectionPolicy: ExponentialReconnectionPolicyStatic; interface ReconnectionPolicy { newSchedule(): { next: Function }; @@ -93,7 +94,7 @@ export namespace policies { } namespace retry { - var RetryPolicy: RetryPolicyStatic; + let RetryPolicy: RetryPolicyStatic; interface DecisionInfo { decision: number; @@ -128,18 +129,18 @@ export namespace policies { } export namespace types { - var BigDecimal: BigDecimalStatic; - var InetAddress: InetAddressStatic; - var Integer: IntegerStatic; - var LocalDate: LocalDateStatic; - var LocalTime: LocalTimeStatic; - var Long: _Long; - var ResultSet: ResultSetStatic; - // var ResultStream: ResultStreamStatic; - var Row: RowStatic; - var TimeUuid: TimeUuidStatic; - var Tuple: TupleStatic; - var Uuid: UuidStatic; + let BigDecimal: BigDecimalStatic; + let InetAddress: InetAddressStatic; + let Integer: IntegerStatic; + let LocalDate: LocalDateStatic; + let LocalTime: LocalTimeStatic; + let Long: _Long; + let ResultSet: ResultSetStatic; + // let ResultStream: ResultStreamStatic; + let Row: RowStatic; + let TimeUuid: TimeUuidStatic; + let Tuple: TupleStatic; + let Uuid: UuidStatic; enum consistencies { any = 0, @@ -433,10 +434,10 @@ export namespace types { } } -export var Client: ClientStatic; -export var Host: HostStatic; -export var HostMap: HostMapStatic; -export var Encoder: EncoderStatic; +export let Client: ClientStatic; +export let Host: HostStatic; +export let HostMap: HostMapStatic; +export let Encoder: EncoderStatic; export interface ClientOptions { contactPoints: Array, @@ -468,7 +469,7 @@ export interface ClientOptions { coalescingThreshold: number }, authProvider?: auth.AuthProvider, - sslOptions?: any, + sslOptions?: tls.ConnectionOptions, encoding?: { map: Function, set: Function, @@ -564,8 +565,8 @@ export interface Encoder { } export namespace auth { - var Authenticator: AuthenticatorStatic; - var PlainTextAuthProvider: PlainTextAuthProviderStatic; + let Authenticator: AuthenticatorStatic; + let PlainTextAuthProvider: PlainTextAuthProviderStatic; interface AuthenticatorStatic { new (): Authenticator; @@ -623,12 +624,12 @@ export namespace errors { } export namespace metadata { - var Aggregate: AggregateStatic; - var Index: IndexStatic; - var MaterializedView: MaterializedViewStatic; - var Metadata: MetadataStatic; - var SchemaFunction: SchemaFunctionStatic; - var TableMetadata: TableMetadataStatic; + let Aggregate: AggregateStatic; + let Index: IndexStatic; + let MaterializedView: MaterializedViewStatic; + let Metadata: MetadataStatic; + let SchemaFunction: SchemaFunctionStatic; + let TableMetadata: TableMetadataStatic; type caching = "all" | "keys_only" | "rows_only" | "none"; diff --git a/types/chrome/index.d.ts b/types/chrome/index.d.ts index 4f37ae029c..bb2b4afcb5 100644 --- a/types/chrome/index.d.ts +++ b/types/chrome/index.d.ts @@ -5547,19 +5547,12 @@ declare namespace chrome.storage { */ set(items: Object, callback?: () => void): void; /** - * Removes one item from storage. - * @param key A single key for items to remove. + * Removes one or more items from storage. + * @param A single key or a list of keys for items to remove. * @param callback Optional. * Callback on success, or on failure (in which case runtime.lastError will be set). */ - remove(key: string, callback?: () => void): void; - /** - * Removes items from storage. - * @param keys A list of keys for items to remove. - * @param callback Optional. - * Callback on success, or on failure (in which case runtime.lastError will be set). - */ - remove(keys: string[], callback?: () => void): void; + remove(keys: string | string[], callback?: () => void): void; /** * Gets one or more items from storage. * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). diff --git a/types/cleave.js/index.d.ts b/types/cleave.js/index.d.ts index 1ec788cd8f..17e8c1c512 100644 --- a/types/cleave.js/index.d.ts +++ b/types/cleave.js/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for cleave.js 1.0 // Project: https://github.com/nosir/cleave.js -// Definitions by: C Lentfort +// Definitions by: C Lentfort , J Giancono // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/cleave.js/options.d.ts b/types/cleave.js/options.d.ts index 4320881649..81757fe097 100644 --- a/types/cleave.js/options.d.ts +++ b/types/cleave.js/options.d.ts @@ -10,6 +10,8 @@ export type CreditCardType = | "mastercard" | "uatp" | "unknown" + | "unionPay" + | "mir" | "visa"; export type CreditCardTypeChangeHandler = (owner: HTMLInputElement, type: CreditCardType) => void; @@ -33,7 +35,7 @@ export interface CleaveOptions { } // Numeral Options -export type NumeralThousandsGroupStyleType = "lakh" | "thousand" | "wan"; +export type NumeralThousandsGroupStyleType = "lakh" | "thousand" | "wan" | "none"; export interface CleaveOptions { numeral?: boolean; @@ -55,6 +57,7 @@ export interface CleaveOptions { lowercase?: boolean; numericOnly?: boolean; prefix?: string; + noImmediatePrefix?: boolean; rawValueTrimPrefix?: boolean; uppercase?: boolean; } diff --git a/types/cli/cli-tests.ts b/types/cli/cli-tests.ts index 294cb7dd8b..2a88a216db 100644 --- a/types/cli/cli-tests.ts +++ b/types/cli/cli-tests.ts @@ -52,7 +52,8 @@ cli.main(function (args, options) { } return str; } - for (i = 0, l = this.argc; i < l; i++) { + var l: number = this.argc; + for (i = 0; i < l; i++) { args[i] = escape(args[i]); } options.separator = escape(options.separator); diff --git a/types/codemirror/index.d.ts b/types/codemirror/index.d.ts index cfcbd9d5b3..126eafe013 100644 --- a/types/codemirror/index.d.ts +++ b/types/codemirror/index.d.ts @@ -692,7 +692,7 @@ declare namespace CodeMirror { interface EditorChangeCancellable extends CodeMirror.EditorChange { /** may be used to modify the change. All three arguments to update are optional, and can be left off to leave the existing value for that field intact. */ - update(from?: CodeMirror.Position, to?: CodeMirror.Position, text?: string): void; + update(from?: CodeMirror.Position, to?: CodeMirror.Position, text?: string[]): void; cancel(): void; } diff --git a/types/compute-stdev/compute-stdev-tests.ts b/types/compute-stdev/compute-stdev-tests.ts new file mode 100644 index 0000000000..72b9869ded --- /dev/null +++ b/types/compute-stdev/compute-stdev-tests.ts @@ -0,0 +1,4 @@ +import stdev = require('compute-stdev'); + +// $ExpectType number +stdev([1, 2, 3]); diff --git a/types/compute-stdev/index.d.ts b/types/compute-stdev/index.d.ts new file mode 100644 index 0000000000..7e981ae529 --- /dev/null +++ b/types/compute-stdev/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for compute-stdev 1.0 +// Project: https://github.com/compute-io/stdev +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function stdev(data: ArrayLike): number; + +export = stdev; diff --git a/types/compute-stdev/tsconfig.json b/types/compute-stdev/tsconfig.json new file mode 100644 index 0000000000..f622c386a3 --- /dev/null +++ b/types/compute-stdev/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "compute-stdev-tests.ts" + ] +} diff --git a/types/compute-stdev/tslint.json b/types/compute-stdev/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/compute-stdev/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/content-type/index.d.ts b/types/content-type/index.d.ts index 5ff4ae7ff1..c81c78c966 100644 --- a/types/content-type/index.d.ts +++ b/types/content-type/index.d.ts @@ -18,7 +18,7 @@ export interface MediaType { } export interface RequestLike { - headers: {[header: string]: string | string[]}; + headers: {[header: string]: string | string[] | undefined}; } export interface ResponseLike { diff --git a/types/daterangepicker/index.d.ts b/types/daterangepicker/index.d.ts index f01ffd59a3..4fddcc4fbd 100644 --- a/types/daterangepicker/index.d.ts +++ b/types/daterangepicker/index.d.ts @@ -25,6 +25,7 @@ declare namespace daterangepicker { startDate: moment.Moment; endDate: moment.Moment; + container: JQuery; setStartDate(date: Date | moment.Moment | string): void; setEndDate(date: Date | moment.Moment | string): void; diff --git a/types/echarts/index.d.ts b/types/echarts/index.d.ts index bcae4299d3..0ea8aa0c6a 100644 --- a/types/echarts/index.d.ts +++ b/types/echarts/index.d.ts @@ -4,77 +4,91 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace echarts { - function init(dom:HTMLDivElement|HTMLCanvasElement, theme?:Object|string, opts?:{ + function init(dom: HTMLDivElement | HTMLCanvasElement, theme?: Object | string, opts?: { devicePixelRatio?: number renderer?: string - }):ECharts; + }): ECharts; const graphic: { clipPointsByRect(points: number[][], rect: ERectangle): number[][]; clipRectByRect(targetRect: ERectangle, rect: ERectangle): ERectangle; + LinearGradient: { new (x: number, y: number, x2: number, y2: number, colorStops: Array, globalCoord?: boolean): LinearGradient } + + }; + + + function connect(group: string | Array): void; + + function disConnect(group: string): void; + + function dispose(target: ECharts | HTMLDivElement | HTMLCanvasElement): void; + + function getInstanceByDom(target: HTMLDivElement | HTMLCanvasElement): void; + + function registerMap(mapName: string, geoJson: Object, specialAreas?: Object): void; + + function registerTheme(themeName: string, theme: Object): void; + + interface LinearGradient { + colorStops: Array; + global: boolean; + type: string; + x: number + x2: number + y: number + y2: number } - - function connect(group:string|Array):void; - function disConnect(group:string):void; - - function dispose(target:ECharts|HTMLDivElement|HTMLCanvasElement):void; - - function getInstanceByDom(target:HTMLDivElement|HTMLCanvasElement):void; - - function registerMap(mapName:string, geoJson:Object, specialAreas?:Object):void; - - function registerTheme(themeName:string, theme:Object):void; interface ECharts { - group:string; + group: string; - setOption(option:EChartOption, notMerge?:boolean, notRefreshImmediately?:boolean):void + setOption(option: EChartOption, notMerge?: boolean, notRefreshImmediately?: boolean): void - getWidth():number + getWidth(): number - getHeight():number + getHeight(): number - getDom():HTMLCanvasElement|HTMLDivElement + getDom(): HTMLCanvasElement | HTMLDivElement - getOption():Object + getOption(): Object - resize():void + resize(): void - dispatchAction(payload:Object):void + dispatchAction(payload: Object): void - on(eventName:string, handler:Function, context?:Object):void + on(eventName: string, handler: Function, context?: Object): void - off(eventName:string, handler?:Function):void + off(eventName: string, handler?: Function): void - showLoading(type?:string, opts?:Object):void + showLoading(type?: string, opts?: Object): void - hideLoading():void + hideLoading(): void - getDataURL(opts:{ + getDataURL(opts: { // 导出的格式,可选 png, jpeg type?: string, // 导出的图片分辨率比例,默认为 1。 pixelRatio?: number, // 导出的图片背景色,默认使用 option 里的 backgroundColor backgroundColor?: string - }):string + }): string - getConnectedDataURL(opts:{ + getConnectedDataURL(opts: { // 导出的格式,可选 png, jpeg type: string, // 导出的图片分辨率比例,默认为 1。 pixelRatio: number, // 导出的图片背景色,默认使用 option 里的 backgroundColor backgroundColor: string - }):string + }): string - clear():void + clear(): void - isDisposed():boolean + isDisposed(): boolean + + dispose(): void - dispose():void - // 转换逻辑点到像素 convertToPixel(finder: { seriesIndex?: number, @@ -92,8 +106,8 @@ declare namespace echarts { gridIndex?: number, gridId?: string gridName?: string - } | string, value: string|Array): string|Array - + } | string, value: string | Array): string | Array + convertFromPixel(finder: { seriesIndex?: number, seriesId?: string, @@ -110,7 +124,7 @@ declare namespace echarts { gridIndex?: number, gridId?: string gridName?: string - } | string, value: Array|string): Array|string + } | string, value: Array | string): Array | string } interface ERectangle { @@ -177,6 +191,6 @@ declare namespace echarts { } } -declare module "echarts" { +declare module 'echarts' { export = echarts; } diff --git a/types/emoji-mart/dist-es/components/category.d.ts b/types/emoji-mart/dist-es/components/category.d.ts new file mode 100644 index 0000000000..8cd4ceefbb --- /dev/null +++ b/types/emoji-mart/dist-es/components/category.d.ts @@ -0,0 +1,20 @@ +import React = require('react'); + +import { EmojiData } from '..'; + +import { Emoji, EmojiProps, I18n } from '.'; + +export interface Props { + emojis?: Array; + hasStickyPosition?: boolean; + name: string; + native: boolean; + perLine: number; + emojiProps: EmojiProps; + recent?: string[]; + i18n: I18n; +} + +export default class Category extends React.Component { + // all methods and properties inside this are most likely intended to be private +} diff --git a/types/emoji-mart/dist-es/components/emoji.d.ts b/types/emoji-mart/dist-es/components/emoji.d.ts new file mode 100644 index 0000000000..030ff7ce12 --- /dev/null +++ b/types/emoji-mart/dist-es/components/emoji.d.ts @@ -0,0 +1,31 @@ +import React = require('react'); + +import { EmojiData, EmojiSkin } from '..'; + +export type BackgroundImageFn = (set: EmojiSet, sheetSize: EmojiSheetSize) => string; +export type EmojiSet = 'apple'|'google'|'twitter'|'emojione'|'messenger'|'facebook'; +export type EmojiSheetSize = 16|20|32|64; + +export interface Props { + onOver?(emoji: EmojiData, e: React.MouseEvent): void; + onLeave?(emoji: EmojiData, e: React.MouseEvent): void; + onClick?(emoji: EmojiData, e: React.MouseEvent): void; + /** defaults to returning a png from unpkg.com-hosted emoji-datasource-${set} */ + backgroundImageFn?: BackgroundImageFn; + native?: boolean; + forceSize?: boolean; + tooltip?: boolean; + /** defaults to 1 */ + skin?: EmojiSkin; + /** defaults to 64 */ + sheetSize?: EmojiSheetSize; + /** defaults to 'apple' */ + set?: EmojiSet; + size: number; + emoji: string|EmojiData; +} + +// tslint:disable-next-line strict-export-declare-modifiers +declare const Emoji: React.SFC; + +export { Emoji as default }; diff --git a/types/emoji-mart/dist-es/components/index.d.ts b/types/emoji-mart/dist-es/components/index.d.ts new file mode 100644 index 0000000000..6fc29ecd54 --- /dev/null +++ b/types/emoji-mart/dist-es/components/index.d.ts @@ -0,0 +1,4 @@ +// The other exports on the components folder are not public API +export { default as Category, Props as CategoryProps } from './category'; +export { default as Emoji, Props as EmojiProps, BackgroundImageFn, EmojiSet, EmojiSheetSize } from './emoji'; +export { default as Picker, Props as PickerProps, I18n, PartialI18n, CustomEmoji } from './picker'; diff --git a/types/emoji-mart/dist-es/components/picker.d.ts b/types/emoji-mart/dist-es/components/picker.d.ts new file mode 100644 index 0000000000..9f9132df05 --- /dev/null +++ b/types/emoji-mart/dist-es/components/picker.d.ts @@ -0,0 +1,54 @@ +import React = require('react'); + +import { EmojiData, EmojiSkin } from '..'; + +import { Category, Emoji, EmojiProps, BackgroundImageFn, EmojiSet, EmojiSheetSize } from '.'; + +// tslint:disable-next-line interface-name +export interface I18n { + search: string; + categories: Record<'search'|'recent'|'people'|'nature'|'foods'|'activity'|'places'|'objects'|'symbols'|'flags'|'custom', string>; + notfound: string; +} + +export type PartialI18n = Partial & { categories: Partial}>; + +export interface CustomEmoji { + // id is overridden by short_names[0] + name: string; + /** Must contain at least one name. The first name is used as the unique id. */ + short_names: string[]; + emoticons?: string[]; + keywords?: string[]; + imageUrl: string; +} + +export interface Props { + /** NOTE: default is not preventable */ + onClick?(emoji: EmojiData, e: React.MouseEvent): void; + perLine?: number; + emojiSize?: number; + i18n?: PartialI18n; + style?: React.CSSProperties; + title?: string; + emoji?: string; + color?: string; + set?: EmojiSet; + skin?: EmojiSkin; + native?: boolean; + backgroundImageFn?: BackgroundImageFn; + sheetSize?: EmojiSheetSize; + emojisToShowFilter?(emoji: EmojiData): boolean; + showPreview?: boolean; + emojiTooltip?: boolean; + include?: string[]; + exclude?: string[]; + recent?: string[]; + autoFocus?: boolean; + /** NOTE: custom emoji are copied into a singleton object on every new mount */ + custom: CustomEmoji[]; +} + +export default class Picker extends React.PureComponent { + // everything inside it is supposed to be private +} diff --git a/types/emoji-mart/dist-es/index.d.ts b/types/emoji-mart/dist-es/index.d.ts new file mode 100644 index 0000000000..e49d37fcf6 --- /dev/null +++ b/types/emoji-mart/dist-es/index.d.ts @@ -0,0 +1,15 @@ +export { default as emojiIndex, EmojiData, EmojiSkin } from './utils/emoji-index'; +export { default as store, StoreHandlers } from './utils/store'; +export { default as frequently } from './utils/frequently'; + +export { + Picker, + PickerProps, + I18n, + PartialI18n, + CustomEmoji, + Emoji, + EmojiProps, + Category, + CategoryProps +} from './components'; diff --git a/types/emoji-mart/dist-es/utils/emoji-index.d.ts b/types/emoji-mart/dist-es/utils/emoji-index.d.ts new file mode 100644 index 0000000000..c6499e663c --- /dev/null +++ b/types/emoji-mart/dist-es/utils/emoji-index.d.ts @@ -0,0 +1,25 @@ +export type EmojiSkin = 1|2|3|4|5|6; + +export interface EmojiData { + id: string; + name: string; + colons: string; + /** Reverse mapping to keyof emoticons */ + emoticons: string[]; + unified: string; + skin: EmojiSkin|null; + native: string; +} + +// tslint:disable-next-line strict-export-declare-modifiers +declare const _default: { + search(query: ''): null + search(query: string): EmojiData|null + + emojis: { [emoji: string]: EmojiData } + + /** Mapping of string to keyof emojis */ + emoticons: { [emoticon: string]: string } +}; + +export { _default as default }; diff --git a/types/emoji-mart/dist-es/utils/frequently.d.ts b/types/emoji-mart/dist-es/utils/frequently.d.ts new file mode 100644 index 0000000000..d2f318de5f --- /dev/null +++ b/types/emoji-mart/dist-es/utils/frequently.d.ts @@ -0,0 +1,9 @@ +import { EmojiData } from '..'; + +// tslint:disable-next-line strict-export-declare-modifiers +declare const _default: { + add(emoji: Pick): void + get(perLine: number): string[] +}; + +export { _default as default }; diff --git a/types/emoji-mart/dist-es/utils/store.d.ts b/types/emoji-mart/dist-es/utils/store.d.ts new file mode 100644 index 0000000000..009284bd7b --- /dev/null +++ b/types/emoji-mart/dist-es/utils/store.d.ts @@ -0,0 +1,15 @@ +export interface StoreHandlers { + getter?(key: string): any; + setter?(key: string, value: any): void; +} + +// tslint:disable-next-line strict-export-declare-modifiers +declare const _default: { + setHandlers(handlers?: StoreHandlers): void + setNamespace(namespace: string): void + update(state: {[key: string]: any}): void + set(key: string, value: any): void + get(key: string): any +}; + +export { _default as default }; diff --git a/types/emoji-mart/emoji-mart-tests.tsx b/types/emoji-mart/emoji-mart-tests.tsx new file mode 100644 index 0000000000..7b7b8d0471 --- /dev/null +++ b/types/emoji-mart/emoji-mart-tests.tsx @@ -0,0 +1,93 @@ +// Port of https://github.com/missive/emoji-mart/blob/master/src/components/emoji.js + +import React = require('react'); + +import { Picker, Emoji, EmojiProps, CustomEmoji } from 'emoji-mart'; + +declare var console: { log(...args: any[]): void; }; + +const CUSTOM_EMOJIS: CustomEmoji[] = [ + { + name: 'Party Parrot', + short_names: ['parrot'], + keywords: ['party'], + imageUrl: 'http://cultofthepartyparrot.com/parrots/hd/parrot.gif' + }, + { + name: 'Octocat', + short_names: ['octocat'], + keywords: ['github'], + imageUrl: 'https://assets-cdn.github.com/images/icons/emoji/octocat.png?v7' + }, + { + name: 'Squirrel', + short_names: ['shipit', 'squirrel'], + keywords: ['github'], + imageUrl: 'https://assets-cdn.github.com/images/icons/emoji/shipit.png?v7' + }, +]; + +interface State { + native: boolean; + set: EmojiProps['set']|'native'; + emoji: string; + title: string; + custom: CustomEmoji[]; +} + +class Example extends React.Component<{}, State> { + readonly state: Readonly = { + native: true, + set: 'apple', + emoji: 'point_up', + title: 'Pick your emoji…', + custom: CUSTOM_EMOJIS + }; + render() { + return ( +
+
+

Emoji Mart 🏬

+
+ +
+ {(['native', 'apple', 'google', 'twitter', 'emojione', 'messenger', 'facebook'] as Array).map((set) => { + const props = { disabled: !this.state.native && set === this.state.set }; + + if (set === 'native' && this.state.native) { + props.disabled = true; + } + + return ( + + ); + })} +
+ +
+ +
+
+ ); + } +} diff --git a/types/emoji-mart/index.d.ts b/types/emoji-mart/index.d.ts new file mode 100644 index 0000000000..1116d6eb6f --- /dev/null +++ b/types/emoji-mart/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for emoji-mart 2.2 +// Project: https://github.com/missive/emoji-mart +// Definitions by: Diogo Franco +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +// These definitions should work with 2.3, but the tests doesn't pass on 2.3. + +export * from './dist-es'; diff --git a/types/emoji-mart/tsconfig.json b/types/emoji-mart/tsconfig.json new file mode 100644 index 0000000000..fb776e9a21 --- /dev/null +++ b/types/emoji-mart/tsconfig.json @@ -0,0 +1,32 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "dist-es/components/category.d.ts", + "dist-es/components/emoji.d.ts", + "dist-es/components/index.d.ts", + "dist-es/components/picker.d.ts", + "dist-es/utils/emoji-index.d.ts", + "dist-es/utils/frequently.d.ts", + "dist-es/utils/store.d.ts", + "dist-es/index.d.ts", + "emoji-mart-tests.tsx" + ] +} diff --git a/types/emoji-mart/tslint.json b/types/emoji-mart/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/emoji-mart/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/error-stack-parser/error-stack-parser-tests.ts b/types/error-stack-parser/error-stack-parser-tests.ts deleted file mode 100644 index c8b9198261..0000000000 --- a/types/error-stack-parser/error-stack-parser-tests.ts +++ /dev/null @@ -1,3 +0,0 @@ - - -ErrorStackParser.parse(new Error('Boom')); diff --git a/types/error-stack-parser/index.d.ts b/types/error-stack-parser/index.d.ts deleted file mode 100644 index ad722b0f2b..0000000000 --- a/types/error-stack-parser/index.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -// Type definitions for ErrorStackParser v1.3.3 -// Project: https://github.com/stacktracejs/error-stack-parser -// Definitions by: Eric Wendelin -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module ErrorStackParser { - export interface StackFrame { - constructor(functionName: string, args: any, fileName: string, lineNumber: number, columnNumber: number, source: string): StackFrame; - - functionName?: string; - args?: any[]; - fileName?: string; - lineNumber?: number; - columnNumber?: number; - source?: string; - toString(): string; - } - - /** - * Given an Error object, extract the most information from it. - * - * @param {Error} error object - * @return {Array} of StackFrames - */ - export function parse(error: Error): StackFrame[]; -} diff --git a/types/error-stack-parser/tslint.json b/types/error-stack-parser/tslint.json deleted file mode 100644 index a41bf5d19a..0000000000 --- a/types/error-stack-parser/tslint.json +++ /dev/null @@ -1,79 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} diff --git a/types/execa/index.d.ts b/types/execa/index.d.ts index 84c6939798..ee33bea59e 100644 --- a/types/execa/index.d.ts +++ b/types/execa/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for execa 0.7 +// Type definitions for execa 0.8 // Project: https://github.com/sindresorhus/execa#readme // Definitions by: Douglas Duteil // BendingBender +// Borek Bernard // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -10,46 +11,46 @@ import { ChildProcess, ExecOptions, SpawnOptions, SpawnSyncOptions } from "child_process"; import { Stream } from 'stream'; -type StdIOOption = 'pipe' | 'ipc' | 'ignore' | number | Stream | undefined | null; - -interface ExecaOptions { - input: string | Buffer | Stream; - preferLocal: boolean; - stripEof: boolean; - extendEnv: boolean; - argv0: string; - localDir: string; - reject: boolean; - cleanup: boolean; - stdin: StdIOOption; - stdout: StdIOOption; - stderr: StdIOOption; -} - -type Options = SpawnOptions & ExecaOptions & ExecOptions; -type SyncOptions = SpawnSyncOptions & ExecaOptions & ExecOptions; - -interface ExecaReturns { - cmd: string; - code: number; - failed: boolean; - killed: boolean; - signal: string | null; - stderr: string; - stdout: string; - timedOut: boolean; -} - -type ExecaError = Error & ExecaReturns; - -interface ExecaChildPromise { - catch(onrejected?: ((reason: ExecaError) => TResult | PromiseLike) | null): Promise; -} -type ExecaChildProcess = ChildProcess & ExecaChildPromise & Promise; - -declare function execa(file: string, options?: Partial): ExecaChildProcess; -declare function execa(file: string, args?: string[], options?: Partial): ExecaChildProcess; +declare function execa(file: string, options?: Partial): execa.ExecaChildProcess; +declare function execa(file: string, args?: string[], options?: Partial): execa.ExecaChildProcess; declare namespace execa { + type StdIOOption = 'pipe' | 'ipc' | 'ignore' | number | Stream | undefined | null; + + interface ExecaOptions { + input: string | Buffer | Stream; + preferLocal: boolean; + stripEof: boolean; + extendEnv: boolean; + argv0: string; + localDir: string; + reject: boolean; + cleanup: boolean; + stdin: StdIOOption; + stdout: StdIOOption; + stderr: StdIOOption; + } + + type Options = SpawnOptions & ExecaOptions & ExecOptions; + type SyncOptions = SpawnSyncOptions & ExecaOptions & ExecOptions; + + interface ExecaReturns { + cmd: string; + code: number; + failed: boolean; + killed: boolean; + signal: string | null; + stderr: string; + stdout: string; + timedOut: boolean; + } + + type ExecaError = Error & ExecaReturns; + + interface ExecaChildPromise { + catch(onrejected?: ((reason: ExecaError) => TResult | PromiseLike) | null): Promise; + } + type ExecaChildProcess = ChildProcess & ExecaChildPromise & Promise; + function stdout(file: string, options?: Partial): Promise; function stdout(file: string, args?: string[], options?: Partial): Promise; function stderr(file: string, options?: Partial): Promise; diff --git a/types/express-cluster/express-cluster-tests.ts b/types/express-cluster/express-cluster-tests.ts new file mode 100644 index 0000000000..4eb096ffd6 --- /dev/null +++ b/types/express-cluster/express-cluster-tests.ts @@ -0,0 +1,6 @@ +import cluster = require('express-cluster'); + +() => { + cluster(worker => {}, {count: 5}); + cluster({count: 5}, worker => {}); +}; diff --git a/types/express-cluster/index.d.ts b/types/express-cluster/index.d.ts new file mode 100644 index 0000000000..bee845d02e --- /dev/null +++ b/types/express-cluster/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for express-cluster 0.0 +// Project: https://github.com/Flipboard/express-cluster +// Definitions by: Miloslav Nenadál +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import cluster = require('cluster'); + +interface Config { + count?: number; + respawn?: boolean; + verbose?: boolean; + workerListener?(): void; + outputStream?: NodeJS.WritableStream; +} + +type WorkerFunction = (worker: cluster.Worker) => void; + +interface Cluster { + (fn: WorkerFunction, config: Config): void; + (config: Config, fn: WorkerFunction): void; +} + +declare const c: Cluster; +export = c; diff --git a/types/error-stack-parser/tsconfig.json b/types/express-cluster/tsconfig.json similarity index 85% rename from types/error-stack-parser/tsconfig.json rename to types/express-cluster/tsconfig.json index 98f3beb1a5..5d27d3ec2e 100644 --- a/types/error-stack-parser/tsconfig.json +++ b/types/express-cluster/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "error-stack-parser-tests.ts" + "express-cluster-tests.ts" ] } \ No newline at end of file diff --git a/types/express-cluster/tslint.json b/types/express-cluster/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/express-cluster/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/express-oauth-server/express-oauth-server-tests.ts b/types/express-oauth-server/express-oauth-server-tests.ts new file mode 100644 index 0000000000..436763b9b8 --- /dev/null +++ b/types/express-oauth-server/express-oauth-server-tests.ts @@ -0,0 +1,83 @@ +import ExpressOAuthServer = require("express-oauth-server"); +import * as OAuth2Server from "oauth2-server"; +import * as express from "express"; + +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 serverOptions: OAuth2Server.ServerOptions = { + model: oauth2Model, +}; +const expressOAuthServer: ExpressOAuthServer = new ExpressOAuthServer(serverOptions); + +let oAuthServer: OAuth2Server; +let resultingTokenMiddleware: ( + request: express.Request, + response: express.Response, + next: express.NextFunction, +) => Promise; +let resultingAuthorizationCodeMiddleware: ( + request: express.Request, + response: express.Response, + next: express.NextFunction, +) => Promise; + +oAuthServer = expressOAuthServer.server; +resultingTokenMiddleware = expressOAuthServer.authenticate(); +resultingTokenMiddleware = expressOAuthServer.token(); +resultingAuthorizationCodeMiddleware = expressOAuthServer.authorize(); + +// Real-life example + +const expressApp = express(); + +expressApp.all( + "/path", + expressOAuthServer.authenticate(), + (req: express.Request, res: express.Response, next: express.NextFunction) => { + res.json({message: "Secure data"}); + }, +); + +expressApp.get( + "/profile", + expressOAuthServer.authenticate({scope: "profile"}), + (req: express.Request & {user?: OAuth2Server.Token}, res: express.Response, next: express.NextFunction) => { + res.json({ + profile: req.user + }); + }, +); + +expressApp.listen(1234); diff --git a/types/express-oauth-server/index.d.ts b/types/express-oauth-server/index.d.ts new file mode 100644 index 0000000000..0a5a1162ea --- /dev/null +++ b/types/express-oauth-server/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for express-oauth-server 2.0 +// Project: https://github.com/oauthjs/express-oauth-server#readme +// Definitions by: Arne Schubert +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import * as express from 'express'; +import * as OAuth2Server from 'oauth2-server'; + +declare class ExpressOAuthServer { + server: OAuth2Server; + + constructor(options: OAuth2Server.ServerOptions); + + authenticate(options?: OAuth2Server.AuthenticateOptions): ( + request: express.Request, + response: express.Response, + next: express.NextFunction, + ) => Promise; + + authorize(options?: OAuth2Server.AuthorizeOptions): ( + request: express.Request, + response: express.Response, + next: express.NextFunction, + ) => Promise; + + token(options?: OAuth2Server.TokenOptions): ( + request: express.Request, + response: express.Response, + next: express.NextFunction, + ) => Promise; +} + +export = ExpressOAuthServer; diff --git a/types/express-oauth-server/tsconfig.json b/types/express-oauth-server/tsconfig.json new file mode 100644 index 0000000000..197ec65f00 --- /dev/null +++ b/types/express-oauth-server/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "express-oauth-server-tests.ts" + ] +} diff --git a/types/express-oauth-server/tslint.json b/types/express-oauth-server/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/express-oauth-server/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/faker/faker-tests.ts b/types/faker/faker-tests.ts index 5fb6a53746..df671dcf6a 100644 --- a/types/faker/faker-tests.ts +++ b/types/faker/faker-tests.ts @@ -1,5 +1,3 @@ - - let resultStr: string; let resultBool: boolean; let resultNum: number; @@ -17,7 +15,7 @@ resultStr = faker.address.cityPrefix(); resultStr = faker.address.citySuffix(); resultStr = faker.address.streetName(); resultStr = faker.address.streetAddress(); -resultStr = faker.address.streetAddress(false);; +resultStr = faker.address.streetAddress(false); resultStr = faker.address.streetSuffix(); resultStr = faker.address.streetPrefix(); resultStr = faker.address.secondaryAddress(); @@ -63,6 +61,8 @@ resultDate = faker.date.between('foo', 'bar'); resultDate = faker.date.between(new Date(), new Date()); resultDate = faker.date.recent(); resultDate = faker.date.recent(100); +resultDate = faker.date.soon(); +resultDate = faker.date.soon(30); resultStr = faker.date.month(); resultStr = faker.date.month({ abbr: true, @@ -86,6 +86,9 @@ resultStr = faker.finance.currencyCode(); resultStr = faker.finance.currencyName(); resultStr = faker.finance.currencySymbol(); resultStr = faker.finance.bitcoinAddress(); +resultStr = faker.finance.ethereumAddress(); +resultStr = faker.finance.iban(); +resultStr = faker.finance.iban(true); resultStr = faker.finance.bic(); resultStr = faker.hacker.abbreviation(); @@ -96,7 +99,7 @@ resultStr = faker.hacker.ingverb(); resultStr = faker.hacker.phrase(); resultStr = faker.helpers.randomize(); -resultNum = faker.helpers.randomize([1,2,3,4]); +resultNum = faker.helpers.randomize([1, 2, 3, 4]); resultStr = faker.helpers.randomize(['foo', 'bar', 'quux']); resultStr = faker.helpers.slugify('foo bar quux'); resultStr = faker.helpers.replaceSymbolWithNumber('foo# bar#'); @@ -167,7 +170,6 @@ resultStr = faker.name.jobType(); resultStr = faker.phone.phoneNumber(); resultStr = faker.phone.phoneNumber('#'); resultStr = faker.phone.phoneNumberFormat(); -// https://github.com/Marak/faker.js/blob/master/lib/phone_number.js#L9-L13 resultStr = faker.phone.phoneNumberFormat(0); resultStr = faker.phone.phoneFormats(); @@ -179,27 +181,104 @@ resultNum = faker.random.number({ precision: 0 }); resultStr = faker.random.arrayElement(); -resultStr = faker.random.arrayElement(['foo', 'bar', 'quux']) +resultStr = faker.random.arrayElement(['foo', 'bar', 'quux']); resultStr = faker.random.objectElement(); resultStr = faker.random.objectElement({foo: 'bar', field: 'foo'}); resultStr = faker.random.uuid(); resultBool = faker.random.boolean(); resultStr = faker.random.word(); +resultStr = faker.random.word("noun"); resultStr = faker.random.words(); resultStr = faker.random.words(0); resultStr = faker.random.image(); resultStr = faker.random.locale(); resultStr = faker.random.alphaNumeric(); resultStr = faker.random.alphaNumeric(0); +resultStr = faker.random.hexaDecimal(); +resultStr = faker.random.hexaDecimal(3); -resultStr = faker.system.fileName( "foo", "bar" ); -resultStr = faker.system.commonFileName( "foo", "bar" ); +resultStr = faker.system.fileName("foo", "bar"); +resultStr = faker.system.commonFileName("foo", "bar"); resultStr = faker.system.mimeType(); resultStr = faker.system.commonFileType(); resultStr = faker.system.commonFileExt(); resultStr = faker.system.fileType(); -resultStr = faker.system.fileExt( "foo" ); +resultStr = faker.system.fileExt("foo"); +resultStr = faker.system.directoryPath(); +resultStr = faker.system.filePath(); resultStr = faker.system.semver(); +import fakerAz = require('faker/locale/az'); +resultStr = fakerAz.name.firstName(); +import fakerCz = require('faker/locale/cz'); +resultStr = fakerCz.name.firstName(); +import fakerDe = require('faker/locale/de'); +resultStr = fakerDe.name.firstName(); +import fakerDeAT = require('faker/locale/de_AT'); +resultStr = fakerDeAT.name.firstName(); +import fakerdeCH = require('faker/locale/de_CH'); +resultStr = fakerdeCH.name.firstName(); import fakerEn = require('faker/locale/en'); -resultStr = faker.name.firstName(); +resultStr = fakerEn.name.firstName(); +import fakerEnAU = require('faker/locale/en_AU'); +resultStr = fakerEnAU.name.firstName(); +import fakerEnBORK = require('faker/locale/en_BORK'); +resultStr = fakerEnBORK.name.firstName(); +import fakerEnCA = require('faker/locale/en_CA'); +resultStr = fakerEnCA.name.firstName(); +import fakerEnGB = require('faker/locale/en_GB'); +resultStr = fakerEnGB.name.firstName(); +import fakerEnIE = require('faker/locale/en_IE'); +resultStr = fakerEnIE.name.firstName(); +import fakerEnIND = require('faker/locale/en_IND'); +resultStr = fakerEnIND.name.firstName(); +import fakerEnUS = require('faker/locale/en_US'); +resultStr = fakerEnUS.name.firstName(); +import fakerEnAuOcker = require('faker/locale/en_au_ocker'); +resultStr = fakerEnAuOcker.name.firstName(); +import fakerEs = require('faker/locale/es'); +resultStr = fakerEs.name.firstName(); +import fakerEsMX = require('faker/locale/es_MX'); +resultStr = fakerEsMX.name.firstName(); +import fakerFa = require('faker/locale/fa'); +resultStr = fakerFa.name.firstName(); +import fakerFr = require('faker/locale/fr'); +resultStr = fakerFr.name.firstName(); +import fakerFrCA = require('faker/locale/fr_CA'); +resultStr = fakerFrCA.name.firstName(); +import fakerGe = require('faker/locale/ge'); +resultStr = fakerGe.name.firstName(); +import fakerIdID = require('faker/locale/id_ID'); +resultStr = fakerIdID.name.firstName(); +import fakerIt = require('faker/locale/it'); +resultStr = fakerIt.name.firstName(); +import fakerJa = require('faker/locale/ja'); +resultStr = fakerJa.name.firstName(); +import fakerKo = require('faker/locale/ko'); +resultStr = fakerKo.name.firstName(); +import fakerNbNO = require('faker/locale/nb_NO'); +resultStr = fakerNbNO.name.firstName(); +import fakerNep = require('faker/locale/nep'); +resultStr = fakerNep.name.firstName(); +import fakerNl = require('faker/locale/nl'); +resultStr = fakerNl.name.firstName(); +import fakerPl = require('faker/locale/pl'); +resultStr = fakerPl.name.firstName(); +import fakerPtBR = require('faker/locale/pt_BR'); +resultStr = fakerPtBR.name.firstName(); +import fakerRu = require('faker/locale/ru'); +resultStr = fakerRu.name.firstName(); +import fakerSk = require('faker/locale/sk'); +resultStr = fakerSk.name.firstName(); +import fakerSv = require('faker/locale/sv'); +resultStr = fakerSv.name.firstName(); +import fakerTr = require('faker/locale/tr'); +resultStr = fakerTr.name.firstName(); +import fakerUk = require('faker/locale/uk'); +resultStr = fakerUk.name.firstName(); +import fakerVi = require('faker/locale/vi'); +resultStr = fakerVi.name.firstName(); +import fakerZhCN = require('faker/locale/zh_CN'); +resultStr = fakerZhCN.name.firstName(); +import fakerZhTW = require('faker/locale/zh_TW'); +resultStr = fakerZhTW.name.firstName(); diff --git a/types/faker/index.d.ts b/types/faker/index.d.ts index eda944d515..552e7d3eeb 100644 --- a/types/faker/index.d.ts +++ b/types/faker/index.d.ts @@ -1,9 +1,12 @@ -// Type definitions for faker v4.1.0 +// Type definitions for faker 4.1 // Project: http://marak.com/faker.js/ -// Definitions by: Ben Swartz , Bas Pennings , Yuki Kokubun +// Definitions by: Ben Swartz , +// Bas Pennings , +// Yuki Kokubun , +// Matt Bishop // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare var fakerStatic: Faker.FakerStatic; +declare const fakerStatic: Faker.FakerStatic; declare namespace Faker { interface FakerStatic { @@ -64,6 +67,7 @@ declare namespace Faker { future(years?: number, refDate?: string|Date): Date; between(from: string|number|Date, to: string|Date): Date; recent(days?: number): Date; + soon(days?: number): Date; month(options?: { abbr?: boolean, context?: boolean }): string; weekday(options?: { abbr?: boolean, context?: boolean }): string; }; @@ -74,12 +78,14 @@ declare namespace Faker { account(length?: number): string; accountName(): string; mask(length?: number, parens?: boolean, elipsis?: boolean): string; - amount(min?:number, max?: number, dec?: number, symbol?: string): string; + amount(min?: number, max?: number, dec?: number, symbol?: string): string; transactionType(): string; currencyCode(): string; currencyName(): string; currencySymbol(): string; bitcoinAddress(): string; + ethereumAddress(): string; + iban(formatted?: boolean): string bic(): string }; @@ -101,13 +107,12 @@ declare namespace Faker { shuffle(o: T[]): T[]; shuffle(): string[]; mustache(str: string, data: { [key: string]: string|((substring: string, ...args: any[]) => string) }): string; - createCard(): Faker.Card; - contextualCard(): Faker.ContextualCard; - userCard(): Faker.UserCard; - createTransaction(): Faker.Transaction; + createCard(): Card; + contextualCard(): ContextualCard; + userCard(): UserCard; + createTransaction(): Transaction; }; - image: { image(): string; avatar(): string; @@ -186,11 +191,12 @@ declare namespace Faker { objectElement(object?: { [key: string]: T }, field?: any): T; uuid(): string; boolean(): boolean; - word(): string; // TODO: have ability to return specific type of word? As in: noun, adjective, verb, etc + word(type?: string): string; words(count?: number): string; image(): string; locale(): string; alphaNumeric(count?: number): string; + hexaDecimal(count?: number): string; }; system: { @@ -201,8 +207,8 @@ declare namespace Faker { commonFileExt(): string; fileType(): string; fileExt(mimeType: string): string; - //directoryPath(): string; - //filePath(): string; + directoryPath(): string; + filePath(): string; semver(): string; }; @@ -315,10 +321,6 @@ declare module "faker/locale/de_CH" { export = fakerStatic; } -declare module "faker/locale/el_GR" { - export = fakerStatic; -} - declare module "faker/locale/en" { export = fakerStatic; } diff --git a/types/fontfaceobserver/index.d.ts b/types/fontfaceobserver/index.d.ts index 8f461dbd4f..a10214a57d 100644 --- a/types/fontfaceobserver/index.d.ts +++ b/types/fontfaceobserver/index.d.ts @@ -25,7 +25,7 @@ declare class FontFaceObserver { * @param testString If your font doesn't contain latin characters you can pass a custom test string. * @param timeout The default timeout for giving up on font loading is 3 seconds. You can increase or decrease this by passing a number of milliseconds. */ - load(testString?: string, timeout?: number): Promise; + load(testString?: string | null, timeout?: number): Promise; } declare module "fontfaceobserver" { diff --git a/types/fs-extra/fs-extra-tests.ts b/types/fs-extra/fs-extra-tests.ts index f405486adb..1af094260d 100644 --- a/types/fs-extra/fs-extra-tests.ts +++ b/types/fs-extra/fs-extra-tests.ts @@ -14,7 +14,7 @@ const fd = 0; const modeNum = 0; const modeStr = ""; const object = {}; -const errorCallback = (err: Error | null) => { }; +const errorCallback = (err: Error) => { }; const readOptions: fs.ReadOptions = { reviver: {} }; diff --git a/types/fs-extra/index.d.ts b/types/fs-extra/index.d.ts index 934f6ce5e1..82bd401c39 100644 --- a/types/fs-extra/index.d.ts +++ b/types/fs-extra/index.d.ts @@ -14,142 +14,141 @@ import { Stats } from "fs"; export * from "fs"; export function copy(src: string, dest: string, options?: CopyOptions): Promise; -export function copy(src: string, dest: string, callback: (err: Error | null) => void): void; -export function copy(src: string, dest: string, options: CopyOptions, callback: (err: Error | null) => void): void; +export function copy(src: string, dest: string, callback: (err: Error) => void): void; +export function copy(src: string, dest: string, options: CopyOptions, callback: (err: Error) => void): void; export function copySync(src: string, dest: string, options?: CopyOptions): void; export function move(src: string, dest: string, options?: MoveOptions): Promise; -export function move(src: string, dest: string, callback: (err: Error | null) => void): void; -export function move(src: string, dest: string, options: MoveOptions, callback: (err: Error | null) => void): void; +export function move(src: string, dest: string, callback: (err: Error) => void): void; +export function move(src: string, dest: string, options: MoveOptions, callback: (err: Error) => void): void; export function moveSync(src: string, dest: string, options?: MoveOptions): void; export function createFile(file: string): Promise; -export function createFile(file: string, callback: (err: Error | null) => void): void; +export function createFile(file: string, callback: (err: Error) => void): void; export function createFileSync(file: string): void; export function ensureDir(path: string): Promise; -export function ensureDir(path: string, callback: (err: Error | null) => void): void; +export function ensureDir(path: string, callback: (err: Error) => void): void; export function ensureDirSync(path: string): void; export function mkdirs(dir: string): Promise; -export function mkdirs(dir: string, callback: (err: Error | null) => void): void; +export function mkdirs(dir: string, callback: (err: Error) => void): void; export function mkdirp(dir: string): Promise; -export function mkdirp(dir: string, callback: (err: Error | null) => 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 function outputFile(file: string, data: any, options?: WriteFileOptions | string): Promise; -export function outputFile(file: string, data: any, callback: (err: Error | null) => void): void; -export function outputFile(file: string, data: any, options: WriteFileOptions | string, callback: (err: Error | null) => void): void; +export function outputFile(file: string, data: any, callback: (err: Error) => void): void; +export function outputFile(file: string, data: any, options: WriteFileOptions | string, callback: (err: Error) => void): void; export function outputFileSync(file: string, data: any, options?: WriteFileOptions | string): void; export function readJson(file: string, options?: ReadOptions): Promise; -export function readJson(file: string, callback: (err: Error | null, jsonObject: any) => void): void; -export function readJson(file: string, options: ReadOptions, callback: (err: Error | null, jsonObject: any) => void): void; +export function readJson(file: string, callback: (err: Error, jsonObject: any) => void): void; +export function readJson(file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void): void; export function readJSON(file: string, options?: ReadOptions): Promise; -export function readJSON(file: string, callback: (err: Error | null, jsonObject: any) => void): void; -export function readJSON(file: string, options: ReadOptions, callback: (err: Error | null, jsonObject: any) => void): void; +export function readJSON(file: string, callback: (err: Error, jsonObject: any) => void): void; +export function readJSON(file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void): void; export function readJsonSync(file: string, options?: ReadOptions): any; export function readJSONSync(file: string, options?: ReadOptions): any; export function remove(dir: string): Promise; -export function remove(dir: string, callback: (err: Error | null) => void): void; +export function remove(dir: string, callback: (err: Error) => void): void; export function removeSync(dir: string): void; export function outputJSON(file: string, data: any, options?: WriteOptions): Promise; -export function outputJSON(file: string, data: any, options: WriteOptions, callback: (err: Error | null) => void): void; -export function outputJSON(file: string, data: any, callback: (err: Error | null) => void): void; +export function outputJSON(file: string, data: any, options: WriteOptions, callback: (err: Error) => void): void; +export function outputJSON(file: string, data: any, callback: (err: Error) => void): void; export function outputJson(file: string, data: any, options?: WriteOptions): Promise; -export function outputJson(file: string, data: any, options: WriteOptions, callback: (err: Error | null) => void): void; -export function outputJson(file: string, data: any, callback: (err: Error | null) => void): void; +export function outputJson(file: string, data: any, options: WriteOptions, callback: (err: Error) => void): void; +export function outputJson(file: string, data: any, callback: (err: Error) => void): void; export function outputJsonSync(file: string, data: any, options?: WriteOptions): void; export function outputJSONSync(file: string, data: any, options?: WriteOptions): void; export function writeJSON(file: string, object: any, options?: WriteOptions): Promise; -export function writeJSON(file: string, object: any, callback: (err: Error | null) => void): void; -export function writeJSON(file: string, object: any, options: WriteOptions, callback: (err: Error | null) => void): void; +export function writeJSON(file: string, object: any, callback: (err: Error) => void): void; +export function writeJSON(file: string, object: any, options: WriteOptions, callback: (err: Error) => void): void; export function writeJson(file: string, object: any, options?: WriteOptions): Promise; -export function writeJson(file: string, object: any, callback: (err: Error | null) => void): void; -export function writeJson(file: string, object: any, options: WriteOptions, callback: (err: Error | null) => void): void; +export function writeJson(file: string, object: any, callback: (err: Error) => void): void; +export function writeJson(file: string, object: any, options: WriteOptions, callback: (err: Error) => void): void; export function writeJsonSync(file: string, object: any, options?: WriteOptions): void; export function writeJSONSync(file: string, object: any, options?: WriteOptions): void; export function ensureFile(path: string): Promise; -export function ensureFile(path: string, callback: (err: Error | null) => void): void; +export function ensureFile(path: string, callback: (err: Error) => void): void; export function ensureFileSync(path: string): void; export function ensureLink(src: string, dest: string): Promise; -export function ensureLink(src: string, dest: string, callback: (err: Error | null) => void): void; +export function ensureLink(src: string, dest: string, callback: (err: Error) => void): void; export function ensureLinkSync(src: string, dest: string): void; export function ensureSymlink(src: string, dest: string, type?: SymlinkType): Promise; -export function ensureSymlink(src: string, dest: string, type: SymlinkType, callback: (err: Error | null) => void): void; -export function ensureSymlink(src: string, dest: string, callback: (err: Error | null) => void): void; +export function ensureSymlink(src: string, dest: string, type: SymlinkType, callback: (err: Error) => void): void; +export function ensureSymlink(src: string, dest: string, callback: (err: Error) => void): void; export function ensureSymlinkSync(src: string, dest: string, type?: SymlinkType): void; export function emptyDir(path: string): Promise; -export function emptyDir(path: string, callback: (err: Error | null) => void): void; +export function emptyDir(path: string, callback: (err: Error) => void): void; export function emptyDirSync(path: string): void; export function pathExists(path: string): Promise; -export function pathExists(path: string, callback: (err: Error | null, exists: boolean) => void): void; +export function pathExists(path: string, callback: (err: Error, exists: boolean) => void): void; export function pathExistsSync(path: string): boolean; // fs async methods // copied from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v6/index.d.ts -/** Tests a user's permissions for the file specified by path. */ -export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; -export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; +export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; +export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; export function access(path: string | Buffer, mode?: number): Promise; export function appendFile(file: string | Buffer | number, data: any, options: { encoding?: string; mode?: number | string; flag?: string; }, - callback: (err: NodeJS.ErrnoException | null) => void): void; -export function appendFile(file: string | Buffer | number, data: any, callback: (err: NodeJS.ErrnoException | null) => void): void; + callback: (err: NodeJS.ErrnoException) => void): void; +export function appendFile(file: string | Buffer | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; export function appendFile(file: string | Buffer | number, data: any, options?: { encoding?: string; mode?: number | string; flag?: string; }): Promise; -export function chmod(path: string | Buffer, mode: string | number, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function chmod(path: string | Buffer, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; export function chmod(path: string | Buffer, mode: string | number): Promise; export function chown(path: string | Buffer, uid: number, gid: number): Promise; -export function chown(path: string | Buffer, uid: number, gid: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function chown(path: string | Buffer, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; -export function close(fd: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function close(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; export function close(fd: number): Promise; -export function fchmod(fd: number, mode: string | number, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function fchmod(fd: number, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; export function fchmod(fd: number, mode: string | number): Promise; -export function fchown(fd: number, uid: number, gid: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function fchown(fd: number, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; export function fchown(fd: number, uid: number, gid: number): Promise; export function fdatasync(fd: number, callback: () => void): void; export function fdatasync(fd: number): Promise; -export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any): void; +export function fstat(fd: number, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; export function fstat(fd: number): Promise; -export function fsync(fd: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function fsync(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; export function fsync(fd: number): Promise; -export function ftruncate(fd: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; -export function ftruncate(fd: number, len: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function ftruncate(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function ftruncate(fd: number, len: number, callback: (err: NodeJS.ErrnoException) => void): void; export function ftruncate(fd: number, len?: number): Promise; -export function futimes(fd: number, atime: number, mtime: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; -export function futimes(fd: number, atime: Date, mtime: Date, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function futimes(fd: number, atime: number, mtime: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function futimes(fd: number, atime: Date, mtime: Date, callback: (err: NodeJS.ErrnoException) => void): void; export function futimes(fd: number, atime: number, mtime: number): Promise; export function futimes(fd: number, atime: Date, mtime: Date): Promise; -export function lchown(path: string | Buffer, uid: number, gid: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function lchown(path: string | Buffer, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; export function lchown(path: string | Buffer, uid: number, gid: number): Promise; -export function link(srcpath: string | Buffer, dstpath: string | Buffer, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function link(srcpath: string | Buffer, dstpath: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; export function link(srcpath: string | Buffer, dstpath: string | Buffer): Promise; -export function lstat(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any): void; +export function lstat(path: string | Buffer, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; export function lstat(path: string | Buffer): Promise; /** @@ -157,42 +156,42 @@ export function lstat(path: string | Buffer): Promise; * * @param callback No arguments other than a possible exception are given to the completion callback. */ -export function mkdir(path: string | Buffer, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function mkdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; /** * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * * @param callback No arguments other than a possible exception are given to the completion callback. */ -export function mkdir(path: string | Buffer, mode: number | string, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function mkdir(path: string | Buffer, mode: number | string, callback: (err: NodeJS.ErrnoException) => void): void; export function mkdir(path: string | Buffer): Promise; -export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; -export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; +export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; +export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; export function open(path: string | Buffer, flags: string | number, mode?: number): Promise; export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, - callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: Buffer) => void): void; + callback: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null): Promise; -export function readFile(file: string | Buffer | number, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; -export function readFile(file: string | Buffer | number, encoding: string, callback: (err: NodeJS.ErrnoException | null, data: string) => void): void; +export function readFile(file: string | Buffer | number, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; +export function readFile(file: string | Buffer | number, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; export function readFile(file: string | Buffer | number, options: { flag?: string; } | { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; export function readFile(file: string | Buffer | number, options: { flag?: string; } | { encoding: string; flag?: string; }): Promise; // tslint:disable-next-line:unified-signatures export function readFile(file: string | Buffer | number, encoding: string): Promise; export function readFile(file: string | Buffer | number): Promise; -export function readdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; +export function readdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; export function readdir(path: string | Buffer): Promise; -export function readlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, linkString: string) => any): void; +export function readlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException, linkString: string) => any): void; export function readlink(path: string | Buffer): Promise; -export function realpath(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => any): void; -export function realpath(path: string | Buffer, cache: { [path: string]: string }, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => any): void; +export function realpath(path: string | Buffer, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; +export function realpath(path: string | Buffer, cache: { [path: string]: string }, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; export function realpath(path: string | Buffer, cache?: { [path: string]: string }): Promise; -export function rename(oldPath: string, newPath: string, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function rename(oldPath: string, newPath: string, callback: (err: NodeJS.ErrnoException) => void): void; export function rename(oldPath: string, newPath: string): Promise; /** @@ -200,17 +199,17 @@ export function rename(oldPath: string, newPath: string): Promise; * * @param callback No arguments other than a possible exception are given to the completion callback. */ -export function rmdir(path: string | Buffer, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function rmdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; export function rmdir(path: string | Buffer): Promise; -export function stat(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any): void; +export function stat(path: string | Buffer, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; export function stat(path: string | Buffer): Promise; -export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type: string, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type: string, callback: (err: NodeJS.ErrnoException) => void): void; export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type?: string): Promise; -export function truncate(path: string | Buffer, callback: (err?: NodeJS.ErrnoException | null) => void): void; -export function truncate(path: string | Buffer, len: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function truncate(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; +export function truncate(path: string | Buffer, len: number, callback: (err: NodeJS.ErrnoException) => void): void; export function truncate(path: string | Buffer, len?: number): Promise; /** @@ -218,25 +217,25 @@ export function truncate(path: string | Buffer, len?: number): Promise; * * @param callback No arguments other than a possible exception are given to the completion callback. */ -export function unlink(path: string | Buffer, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function unlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; export function unlink(path: string | Buffer): Promise; -export function utimes(path: string | Buffer, atime: number, mtime: number, callback: (err?: NodeJS.ErrnoException) => void): void; -export function utimes(path: string | Buffer, atime: Date, mtime: Date, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function utimes(path: string | Buffer, atime: number, mtime: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function utimes(path: string | Buffer, atime: Date, mtime: Date, callback: (err: NodeJS.ErrnoException) => void): void; export function utimes(path: string | Buffer, atime: number, mtime: number): Promise; export function utimes(path: string | Buffer, atime: Date, mtime: Date): Promise; export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; -export function write(fd: number, buffer: Buffer, offset: number, length: number, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: Buffer) => void): void; -export function write(fd: number, data: any, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; -export function write(fd: number, data: any, offset: number, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; -export function write(fd: number, data: any, offset: number, encoding: string, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; +export function write(fd: number, buffer: Buffer, offset: number, length: number, callback: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; +export function write(fd: number, data: any, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; +export function write(fd: number, data: any, offset: number, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; +export function write(fd: number, data: any, offset: number, encoding: string, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; export function write(fd: number, buffer: Buffer, offset: number, length: number, position?: number | null): Promise; export function write(fd: number, data: any, offset: number, encoding?: string): Promise; -export function writeFile(file: string | Buffer | number, data: any, callback: (err: NodeJS.ErrnoException | null) => void): void; +export function writeFile(file: string | Buffer | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; export function writeFile(file: string | Buffer | number, data: any, options?: WriteFileOptions | string): Promise; -export function writeFile(file: string | Buffer | number, data: any, options: WriteFileOptions | string, callback: (err: NodeJS.ErrnoException | null) => void): void; +export function writeFile(file: string | Buffer | number, data: any, options: WriteFileOptions | string, callback: (err: NodeJS.ErrnoException) => void): void; /** * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. @@ -244,7 +243,7 @@ export function writeFile(file: string | Buffer | number, data: any, options: Wr * @param callback The created folder path is passed as a string to the callback's second parameter. */ export function mkdtemp(prefix: string): Promise; -export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; +export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException, folder: string) => void): void; export interface PathEntry { path: string; diff --git a/types/glob-parent/glob-parent-tests.ts b/types/glob-parent/glob-parent-tests.ts new file mode 100644 index 0000000000..13c7df5d59 --- /dev/null +++ b/types/glob-parent/glob-parent-tests.ts @@ -0,0 +1,4 @@ +import globParent = require('glob-parent'); + +// $ExpectType string +globParent('*.js'); diff --git a/types/glob-parent/index.d.ts b/types/glob-parent/index.d.ts new file mode 100644 index 0000000000..052bbcd1db --- /dev/null +++ b/types/glob-parent/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for glob-parent 3.1 +// Project: https://github.com/es128/glob-parent +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function globParent(pattern: string): string; + +export = globParent; diff --git a/types/glob-parent/tsconfig.json b/types/glob-parent/tsconfig.json new file mode 100644 index 0000000000..1e74b9bc82 --- /dev/null +++ b/types/glob-parent/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "glob-parent-tests.ts" + ] +} diff --git a/types/glob-parent/tslint.json b/types/glob-parent/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/glob-parent/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/google-apps-script/google-apps-script.card.d.ts b/types/google-apps-script/google-apps-script.card.d.ts new file mode 100644 index 0000000000..62d497eb4f --- /dev/null +++ b/types/google-apps-script/google-apps-script.card.d.ts @@ -0,0 +1,657 @@ +// Type definitions for Google Apps Script 2017-10-30 +// Project: https://developers.google.com/apps-script/ +// Definitions by: dhayab +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare namespace GoogleAppsScript { + export module Card { + export interface Action { + /** + * Sets the name of the callback function to be called. + */ + setFunctionName(functionName: string): Action; + /** + * Sets the loading indicator that displays while the action is in progress. + */ + setLoadIndicator(loadIndicator: LoadIndicator): Action; + /** + * Allows custom parameters to be passed to the callback function. + */ + setParameters(parameters: { [key: string]: string }): Action; + } + + export interface ActionEvent { + messageMetadata: { + /** + * An access token. You can use this to enable access to user data using temporary Gmail add-on scopes. + */ + accessToken: string; + /** + * The message ID of the thread open in the Gmail UI. + */ + messageId: string; + } + /** + * Indicates where the event originates (web, iOS, or Android). + */ + clientPlatform: string; + /** + * The current values of all form widgets in the card, restricted to one value per widget. The keys are the string IDs associated with the widgets. + * + * The event object provides `formInput` as a convenience for when you need to read data from multiple widgets with expected singular values, such as text inputs and switches. + * + * For multi-valued widgets such as checkboxes, you can read each value from `formInputs` instead. + */ + formInput: { [key: string]: string }; + /** + * The current values of widgets in the card, presented in arrays. The keys are the string IDs associated with the widget. + * + * For single-valued widgets, the value is presented in a single-element array. For multi-valued widgets such as checkboxes, all the values are presented in an array. + */ + formInputs: { [key: string]: string[] }; + /** + * Any additional parameters you supply to the `Action` using `Action.setParameters()`. + */ + parameters: { [key: string]: string }; + } + + export interface ActionResponse { + /** + * Prints the JSON representation of this object. + */ + printJson(): string; + } + + export interface ActionResponseBuilder { + /** + * Builds the current action response and validates it. + */ + build(): ActionResponse; + /** + * Sets the response to `Navigation` action. + */ + setNavigation(navigation: Navigation): ActionResponseBuilder; + /** + * Sets the notification to display when the action is activated. + */ + setNotification(notification: Notification): ActionResponseBuilder; + /** + * Sets the URL to navigate to when the action is activated. + */ + setOpenLink(openLink: OpenLink): ActionResponseBuilder; + } + + export interface AuthorizationAction { + /** + * Sets the authorization URL that user is taken to from the authorization prompt. + */ + setAuthorizationUrl(authorizationUrl: string): AuthorizationAction; + } + + export interface AuthorizationException { + /** + * Prints the JSON representation of this object. + */ + printJson(): string; + /** + * Sets the authorization URL that user is taken to from the authorization prompt. + */ + setAuthorizationUrl(authUrl: string): AuthorizationException; + /** + * The name of a function to call to generate a custom authorization prompt. + */ + setCustomUiCallback(callback: string): AuthorizationException; + /** + * Sets the name that is displayed to the user when asking for authorization. + */ + setResourceDisplayName(name: string): AuthorizationException; + /** + * Triggers this exception to be thrown. + */ + throwException(): void; + } + + interface Button extends Widget { + /** + * Sets an authorization action that opens a URL to the authorization flow when the object is clicked. + */ + setAuthorizationAction(action: AuthorizationAction): T; + /** + * Sets an action that composes a draft email when the object is clicked. + */ + setComposeAction(action: Action, composedEmailType: ComposedEmailType): T; + /** + * Sets an action that executes when the object is clicked. + */ + setOnClickAction(action: Action): T; + /** + * Sets an action that opens a URL in a tab when the object is clicked. + */ + setOnClickOpenLinkAction(action: Action): T; + /** + * Sets a URL to be opened when the object is clicked. + */ + setOpenLink(openLink: OpenLink): T; + } + + export interface ButtonSet extends Widget { + /** + * Adds a button. + */ + addButton(button: Button): ButtonSet; + } + + export interface Card { + /** + * Prints the JSON representation of this object. + */ + printJson(): string; + } + + export interface CardAction extends Button { + /** + * Sets the menu text for this action. + */ + setText(text: string): CardAction; + } + + export interface CardBuilder { + /** + * Adds a CardAction to this Card. + */ + addCardAction(cardAction: CardAction): CardBuilder; + /** + * Adds a section to this card. + */ + addSection(section: CardSection): CardBuilder; + /** + * Builds the current card and validates it. + */ + build(): Card; + /** + * Sets the header for this card. + */ + setHeader(cardHeader: CardHeader): CardBuilder; + /** + * Sets the name for this card. + */ + setName(name: string): CardBuilder; + } + + export interface CardHeader { + /** + * Sets the alternative text for the header image. + */ + setImageAltText(imageAltText: string): CardHeader; + /** + * Sets the cropping of the icon in the card header. + */ + setImageStyle(imageStyle: ImageStyle): CardHeader; + /** + * Sets the image to use in the header by providing its URL. + */ + setImageUrl(imageUrl: string): CardHeader; + /** + * Sets the subtitle of the card header. + */ + setSubtitle(subtitle: string): CardHeader; + /** + * Sets the title of the card header. + */ + setTitle(title: string): CardHeader; + } + + export interface CardSection { + /** + * Adds the given widget to this section. + */ + addWidget(widget: Widget): CardSection; + /** + * Sets whether the section can be collapsed. + */ + setCollapsible(collapsible: boolean): CardSection; + /** + * Sets the header of the section. + */ + setHeader(header: string): CardSection; + /** + * Sets the number of widgets that are still shown when this section is collapsed. + */ + setNumUncollapsibleWidgets(numUncollapsibleWidgets: Integer): CardSection; + } + + export interface CardService { + /** + * Specifies whether the composed email is a standalone or reply draft. + */ + ComposedEmailType: typeof ComposedEmailType; + /** + * Predefined icons that can be used in various UI objects, such as ImageButton or KeyValue widgets. + */ + Icon: typeof Icon; + /** + * Defines an image cropping style. + */ + ImageStyle: typeof ImageStyle; + /** + * Specifies the type of loading or progress indicator to display while an Action is being processed. + */ + LoadIndicator: typeof LoadIndicator; + /** + * Type of notification to show. + */ + NotificationType: typeof NotificationType; + /** + * Specifies what to do when a URL opened through an OpenLink is closed. + * + * When a link is opened, the client either forgets about it or waits until the window is closed. The implementation depends on the client platform capabilities. OnClose may cause OpenAs to be ignored; if the client platform cannot support both selected values together, OnClose takes precedence. + */ + OnClose: typeof OnClose; + /** + * Specifies how to open a URL. + * + * The client can open a URL as either a full size window (if that is the frame used by the client), or an overlay (such as a pop-up). The implementation depends on the client platform capabilities, and the value selected may be ignored if the client does not support it. FULL_SIZE is supported by all clients. + * + * Using OnClose may cause OpenAs to be ignored; if the client platform cannot support both selected values together, OnClose takes precedence. + */ + OpenAs: typeof OpenAs; + /** + * Type of selection input. + */ + SelectionInputType: typeof SelectionInputType; + /** + * Creates a new `Action`. + */ + newAction(): Action; + /** + * Creates a new `ActionResponseBuilder`. + */ + newActionResponseBuilder(): ActionResponseBuilder; + /** + * Creates a new `AuthorizationAction`. + */ + newAuthorizationAction(): AuthorizationAction; + /** + * Creates a new `AuthorizationException`. + */ + newAuthorizationException(): AuthorizationException; + /** + * Creates a new `ButtonSet`. + */ + newButtonSet(): ButtonSet; + /** + * Creates a new `CardAction`. + */ + newCardAction(): CardAction; + /** + * Creates a new `CardBuilder`. + */ + newCardBuilder(): CardBuilder; + /** + * Creates a new `CardHeader`. + */ + newCardHeader(): CardHeader; + /** + * Creates a new `CardSection`. + */ + newCardSection(): CardSection; + /** + * Creates a new `ComposeActionResponseBuilder`. + */ + newComposeActionResponseBuilder(): ComposeActionResponseBuilder; + /** + * Creates a new `Image`. + */ + newImage(): Image; + /** + * Creates a new `ImageButton`. + */ + newImageButton(): ImageButton; + /** + * Creates a new `KeyValue`. + */ + newKeyValue(): KeyValue; + /** + * Creates a new `Navigation`. + */ + newNavigation(): Navigation; + /** + * Creates a new `Notification`. + */ + newNotification(): Notification; + /** + * Creates a new `OpenLink`. + */ + newOpenLink(): OpenLink; + /** + * Creates a new `SelectionInput`. + */ + newSelectionInput(): SelectionInput; + /** + * Creates a new `Suggestions`. + */ + newSuggestions(): Suggestions; + /** + * Creates a new `SuggestionsResponseBuilder`. + */ + newSuggestionsResponseBuilder(): SuggestionsResponseBuilder; + /** + * Creates a new `Switch`. + */ + newSwitch(): Switch; + /** + * Creates a new `TextButton`. + */ + newTextButton(): TextButton; + /** + * Creates a new `TextInput`. + */ + newTextInput(): TextInput; + /** + * Creates a new `TextParagraph`. + */ + newTextParagraph(): TextParagraph; + /** + * Creates a new `UniversalActionResponseBuilder`. + */ + newUniversalActionResponseBuilder(): UniversalActionResponseBuilder; + } + + export interface ComposeActionResponse { + /** + * Prints the JSON representation of this object. + */ + printJson(): string; + } + + export interface ComposeActionResponseBuilder { + /** + * Builds the current compose action response and validates it. + */ + build(): ComposeActionResponse; + /** + * Sets the draft `GmailMessage` created using `GmailMessage.createDraftReply(body)` or similar functions. + */ + setGmailDraft(draft: Gmail.GmailDraft): ComposeActionResponseBuilder; + } + + export interface Image extends Button { + /** + * Sets the alternative text of the image for accessibility. + */ + setAltText(altText: string): Image; + /** + * Sets the URL of the image. + */ + setImageUrl(url: string): Image; + } + + export interface ImageButton extends Button { + /** + * Sets the alternative text of the button for accessibility. + */ + setAltText(altText: string): ImageButton; + /** + * Sets a predefined Icon to display on the button. + */ + setIcon(icon: Icon): ImageButton; + /** + * Sets the URL of an image to use as this button's icon. + */ + setIconUrl(url: string): ImageButton; + } + + export interface KeyValue extends Button { + /** + * Sets the label text to be used as the key. + */ + setBottomLabel(text: string): KeyValue; + /** + * Sets the Button that is displayed to the right of the context. + */ + setButton(button: Button): KeyValue; + /** + * Sets the text to be used as the value. + */ + setContent(text: string): KeyValue; + /** + * Sets the icon to be used as the key. + */ + setIcon(icon: Icon): KeyValue; + /** + * Sets the alternative text for the icon. + */ + setIconAltText(altText: string): KeyValue; + /** + * Sets the URL of the icon to be used as the key. + */ + setIconUrl(url: string): KeyValue; + /** + * Sets whether the value text should be displayed on a single line or multiple lines. + */ + setMultiline(multiline: boolean): KeyValue; + /** + * Sets the Switch that is displayed to the right of the content. + */ + setSwitch(switchToSet: Switch): KeyValue; + /** + * Sets the label text to be used as the key. + */ + setTopLabel(text: string): KeyValue; + } + + export interface Navigation { + /** + * Pops a card from the navigation stack. + */ + popCard(): Navigation; + /** + * Pops to the specified card by its card name. + */ + popToNamedCard(cardName: string): Navigation; + /** + * Pops the card stack to the root card. + */ + popToRoot(): Navigation; + /** + * Prints the JSON representation of this object. + */ + printJson(): string; + /** + * Pushes the given card onto the stack. + */ + pushCard(card: Card): Navigation; + /** + * Does an in-place replacement of the current card. + */ + updateCard(card: Card): Navigation; + } + + export interface Notification { + /** + * Sets the text to show in the notification. + */ + setText(text: string): Notification; + /** + * Sets the notification type to show. + */ + setType(type: NotificationType): Notification; + } + + export interface OpenLink { + /** + * Sets the behavior of the URL action when the URL window or tab is closed. + */ + setOnClose(onClose: OnClose): OpenLink; + /** + * Sets the behavior of URL when it is opened. + */ + setOpenAs(openAs: OpenAs): OpenLink; + /** + * Sets the URL to be opened. + */ + setUrl(url: string): OpenLink; + } + + export interface SelectionInput extends Widget { + /** + * Adds a new item that can be selected. + */ + addItem(text: Object, value: Object, selected: boolean): SelectionInput; + /** + * Sets the key that identifies this selection input in the event object that is generated when there is a UI interaction. + */ + setFieldName(fieldName: string): SelectionInput; + /** + * Sets an Action to be performed whenever the selection input changes. + */ + setOnChangeAction(action: Action): SelectionInput; + /** + * Sets the title to be shown ahead of the input field. + */ + setTitle(title: string): SelectionInput; + /** + * Sets the type of this input. + */ + setType(type: SelectionInputType): SelectionInput; + } + + export interface Suggestions { + /** + * Add a text suggestion. + */ + addSuggestion(suggestion: string): Suggestions; + /** + * Add a list of text suggestions. + */ + addSuggestions(suggestions: string[]): Suggestions; + } + + export interface SuggestionsResponse { + /** + * Prints the JSON representation of this object. + */ + printJson(): string; + } + + export interface SuggestionsResponseBuilder { + /** + * Builds the current suggestions response and validates it. + */ + build(): SuggestionsResponse; + /** + * Sets the suggestions used in auto complete in text fields. + */ + setSuggestions(suggestions: Suggestions): SuggestionsResponseBuilder; + } + + export interface Switch extends Widget { + /** + * Sets the key that identified this switch in the event object that is generated when there is a UI interaction. + */ + setFieldName(fieldName: string): Switch; + /** + * Sets the action to take when the switch is toggled. + */ + setOnChangeAction(action: Action): Switch; + /** + * Sets whether this switch should start as selected or unselected. + */ + setSelected(selected: boolean): Switch; + /** + * Sets the value that is sent as the form input when this switch is toggled on. + */ + setValue(value: string): Switch; + } + + export interface TextButton extends Button { + /** + * Sets the text to be displayed on the button. + */ + setText(text: string): TextButton; + } + + export interface TextInput extends Widget { + /** + * Sets the key that identifies this text input in the event object that is generated when there is a UI interaction. + */ + setFieldName(fieldName: string): TextInput; + /** + * Sets a hint for the text input. + */ + setHint(hint: string): TextInput; + /** + * Sets whether the input text shows on one line or multiple lines. + */ + setMultiline(multiline: boolean): TextInput; + /** + * Sets an action to be performed whenever the text input changes. + */ + setOnChangeAction(action: Action): TextInput; + /** + * Sets the suggestions for autocompletion in the text field. + */ + setSuggestions(suggestions: Suggestions): TextInput; + /** + * Sets the callback action to fetch suggestions based on user input for autocompletion. + */ + setSuggestionsAction(suggestionsAction: Action): TextInput + /** + * Sets the title to be shown above the input field. + */ + setTitle(title: string): TextInput; + /** + * Sets the pre-filled value to be set in the input field. + */ + setValue(value: string): TextInput; + } + + export interface TextParagraph extends Widget { + /** + * Sets the text of the paragraph. + */ + setText(text: string): TextParagraph; + } + + export interface UniversalActionResponse { + /** + * Prints the JSON representation of this object. + */ + printJson(): string; + } + + export interface UniversalActionResponseBuilder { + /** + * Builds the current universal action response and validates it. + */ + build(): UniversalActionResponse; + /** + * Displays the add-on with the specified cards. + */ + displayAddOnCards(cardObjects: Card[]): UniversalActionResponseBuilder; + /** + * Sets the URL to open when the universal action is selected. + */ + setOpenLink(openLink: OpenLink): UniversalActionResponseBuilder; + } + + export interface Widget { } + + export enum ComposedEmailType { REPLY_AS_DRAFT, STANDALONE_DRAFT } + export enum Icon { NONE, AIRPLANE, BOOKMARK, BUS, CAR, CLOCK, CONFIRMATION_NUMBER_ICON, DOLLAR, DESCRIPTION, EMAIL, EVENT_PERFORMER, EVENT_SEAT, FLIGHT_ARRIVAL, FLIGHT_DEPARTURE, HOTEL, HOTEL_ROOM_TYPE, INVITE, MAP_PIN, MEMBERSHIP, MULTIPLE_PEOPLE, OFFER, PERSON, PHONE, RESTAURANT_ICON, SHOPPING_CART, STAR, STORE, TICKET, TRAIN, VIDEO_CAMERA, VIDEO_PLAY } + export enum ImageStyle { SQUARE, CIRCLE } + export enum LoadIndicator { SPINNER, NONE } + export enum NotificationType { INFO, ERROR, WARNING } + export enum OnClose { NOTHING, RELOAD_ADD_ON } + export enum OpenAs { FULL_SIZE, OVERLAY } + export enum SelectionInputType { CHECK_BOX, RADIO_BUTTON, DROPDOWN } + } +} + +/** + * CardService provides the ability to create generic cards used across different Google extensibility products, such as [Gmail add-ons](https://developers.google.com/gmail/add-ons). + */ +declare var CardService: GoogleAppsScript.Card.CardService; diff --git a/types/google-apps-script/google-apps-script.gmail.d.ts b/types/google-apps-script/google-apps-script.gmail.d.ts index 41be4dbb56..4967f53394 100644 --- a/types/google-apps-script/google-apps-script.gmail.d.ts +++ b/types/google-apps-script/google-apps-script.gmail.d.ts @@ -1,6 +1,7 @@ // Type definitions for Google Apps Script 2017-05-12 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen +// dhayab // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -12,12 +13,16 @@ declare namespace GoogleAppsScript { * Provides access to Gmail threads, messages, and labels. */ export interface GmailApp { + createDraft(recipient: string, subject: string, body: string): GmailDraft; + createDraft(recipient: string, subject: string, body: string, options: GmailDraftOptions): GmailDraft; createLabel(name: string): GmailLabel; deleteLabel(label: GmailLabel): GmailApp; getAliases(): string[]; getChatThreads(): GmailThread[]; getChatThreads(start: Integer, max: Integer): GmailThread[]; + getDraft(draftId: string): GmailDraft; getDraftMessages(): GmailMessage[]; + getDrafts(): GmailDraft[]; getInboxThreads(): GmailThread[]; getInboxThreads(start: Integer, max: Integer): GmailThread[]; getInboxUnreadCount(): Integer; @@ -68,6 +73,7 @@ declare namespace GoogleAppsScript { search(query: string, start: Integer, max: Integer): GmailThread[]; sendEmail(recipient: string, subject: string, body: string): GmailApp; sendEmail(recipient: string, subject: string, body: string, options: Object): GmailApp; + setCurrentMessageAccessToken(accessToken: string): void; starMessage(message: GmailMessage): GmailApp; starMessages(messages: GmailMessage[]): GmailApp; unstarMessage(message: GmailMessage): GmailApp; @@ -112,6 +118,72 @@ declare namespace GoogleAppsScript { getAllBlobs(): Base.Blob[]; } + export interface GmailDraft { + /** + * Deletes this draft message. + */ + deleteDraft(): void; + /** + * Gets the ID of this draft message. + */ + getId(): string; + /** + * Returns a GmailMessage representing this draft. + */ + getMessage(): GmailMessage; + /** + * Returns the ID of the `GmailMessage` representing this draft. + */ + getMessageId(): string; + /** + * Sends this draft email message. + */ + send(): GmailMessage; + /** + * Replaces the contents of this draft message. + */ + update(recipient: string, subject: string, body: string): GmailDraft; + /** + * Replaces the contents of this draft message using optional arguments. + */ + update(recipient: string, subject: string, body: string, options: GmailDraftOptions): GmailDraft; + } + + export type GmailDraftOptions = { + /** + * An array of files to send with the email. + */ + attachments?: Base.BlobSource[]; + /** + * A comma-separated list of email addresses to BCC. + */ + bcc?: string; + /** + * A comma-separated list of email addresses to CC. + */ + cc?: string; + /** + * The address that the email should be sent from, which must be one of the values returned by `GmailApp.getAliases()`. + */ + from?: string; + /** + * If set, devices capable of rendering HTML will use it instead of the required body argument; you can add an optional `inlineImages` field in HTML body if you have inlined images for your email. + */ + htmlBody?: string; + /** + * A JavaScript object containing a mapping from image key (`String`) to image data (`BlobSource`) ; this assumes that the `htmlBody` parameter is used and contains references to these images in the format ``. + */ + inlineImages?: { [imageKey: string]: Base.BlobSource }; + /** + * The name of the sender of the email (default: the user's name). + */ + name?: string; + /** + * An email address to use as the default reply-to address (default: the user's email address). + */ + replyTo?: string; + } + /** * A user-created label in a user's Gmail account. */ @@ -131,6 +203,10 @@ declare namespace GoogleAppsScript { * A message in a user's Gmail account. */ export interface GmailMessage { + createDraftReply(body: string): GmailDraft; + createDraftReply(body: string, options: GmailDraftOptions): GmailDraft; + createDraftReplyAll(body: string): GmailDraft; + createDraftReplyAll(body: string, options: GmailDraftOptions): GmailDraft; forward(recipient: string): GmailMessage; forward(recipient: string, options: Object): GmailMessage; getAttachments(): GmailAttachment[]; @@ -169,6 +245,10 @@ declare namespace GoogleAppsScript { */ export interface GmailThread { addLabel(label: GmailLabel): GmailThread; + createDraftReply(body: string): GmailDraft; + createDraftReply(body: string, options: GmailDraftOptions): GmailDraft; + createDraftReplyAll(body: string): GmailDraft; + createDraftReplyAll(body: string, options: GmailDraftOptions): GmailDraft; getFirstMessageSubject(): string; getId(): string; getLabels(): GmailLabel[]; diff --git a/types/google-apps-script/index.d.ts b/types/google-apps-script/index.d.ts index f80598c391..0e4ca164a9 100644 --- a/types/google-apps-script/index.d.ts +++ b/types/google-apps-script/index.d.ts @@ -7,6 +7,7 @@ /// /// /// +/// /// /// /// diff --git a/types/googlemaps/index.d.ts b/types/googlemaps/index.d.ts index 66ddb31f5d..5e977257b8 100644 --- a/types/googlemaps/index.d.ts +++ b/types/googlemaps/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Google Maps JavaScript API 3.29 +// Type definitions for Google Maps JavaScript API 3.30 // Project: https://developers.google.com/maps/ -// Definitions by: Folia A/S , Chris Wrench , Kiarash Ghiaseddin , Grant Hutchins , Denis Atyasov , Michael McMullin , Martin Costello +// Definitions by: Folia A/S , Chris Wrench , Kiarash Ghiaseddin , Grant Hutchins , Denis Atyasov , Michael McMullin , Martin Costello , Sven Kreiss // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /* @@ -2697,7 +2697,7 @@ declare namespace google.maps { * Accepted values are 'marker', 'polygon', 'polyline', 'rectangle', 'circle', or null. A drawing mode * of null means that the user can interact with the map as normal, and clicks do not draw anything. */ - drawingMode?: OverlayType; + drawingMode?: OverlayType | null; /** * The Map to which the DrawingManager is attached, which is the Map on which the overlays created * will be placed. diff --git a/types/gzip-size/index.d.ts b/types/gzip-size/index.d.ts index 12b1899b54..cab8ec225b 100644 --- a/types/gzip-size/index.d.ts +++ b/types/gzip-size/index.d.ts @@ -1,13 +1,19 @@ -// Type definitions for gzip-size 3.0 +// Type definitions for gzip-size 4.0 // Project: https://github.com/sindresorhus/gzip-size // Definitions by: York Yao +// Jimi van der Woning // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -declare function gzipSize(input: string | Buffer, callback: (error: Error, size: number) => void): string; -export = gzipSize; +import * as stream from 'stream'; +import * as zlib from 'zlib'; + +declare function gzipSize(input: string | Buffer, options?: zlib.ZlibOptions): Promise; + declare namespace gzipSize { - function sync(input: string | Buffer): number; - function stream(): NodeJS.ReadWriteStream; + function sync(input: string | Buffer, options?: zlib.ZlibOptions): number; + function stream(options?: zlib.ZlibOptions): stream.PassThrough; } + +export = gzipSize; diff --git a/types/gzip-size/v3/gzip-size-tests.ts b/types/gzip-size/v3/gzip-size-tests.ts new file mode 100644 index 0000000000..f07d99bd50 --- /dev/null +++ b/types/gzip-size/v3/gzip-size-tests.ts @@ -0,0 +1,7 @@ +import gzipSize = require('gzip-size'); + +const string = 'Lorem ipsum dolor sit amet.'; + +console.log(string.length); + +console.log(gzipSize.sync(string)); diff --git a/types/gzip-size/v3/index.d.ts b/types/gzip-size/v3/index.d.ts new file mode 100644 index 0000000000..12b1899b54 --- /dev/null +++ b/types/gzip-size/v3/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for gzip-size 3.0 +// Project: https://github.com/sindresorhus/gzip-size +// Definitions by: York Yao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare function gzipSize(input: string | Buffer, callback: (error: Error, size: number) => void): string; +export = gzipSize; +declare namespace gzipSize { + function sync(input: string | Buffer): number; + function stream(): NodeJS.ReadWriteStream; +} diff --git a/types/gzip-size/v3/tsconfig.json b/types/gzip-size/v3/tsconfig.json new file mode 100644 index 0000000000..88a695711b --- /dev/null +++ b/types/gzip-size/v3/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "gzip-size": [ + "gzip-size/v3" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gzip-size-tests.ts" + ] +} diff --git a/types/gzip-size/v3/tslint.json b/types/gzip-size/v3/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/gzip-size/v3/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/history/index.d.ts b/types/history/index.d.ts index 528ab7ff21..eb15aaa0fc 100644 --- a/types/history/index.d.ts +++ b/types/history/index.d.ts @@ -18,7 +18,7 @@ export interface History { go(n: number): void; goBack(): void; goForward(): void; - block(prompt?: boolean): UnregisterCallback; + block(prompt?: boolean | string | TransitionPromptHook): UnregisterCallback; listen(listener: LocationListener): UnregisterCallback; createHref(location: LocationDescriptorObject): Href; } @@ -48,6 +48,7 @@ export namespace History { export type Pathname = string; export type Search = string; export type TransitionHook = (location: Location, callback: (result: any) => void) => any; + export type TransitionPromptHook = (location: Location, action: Action) => string | false | void; export type Hash = string; export type Href = string; } @@ -60,6 +61,7 @@ export type Path = History.Path; export type Pathname = History.Pathname; export type Search = History.Search; export type TransitionHook = History.TransitionHook; +export type TransitionPromptHook = History.TransitionPromptHook; export type Hash = History.Hash; export type Href = History.Href; diff --git a/types/holderjs/holderjs-tests.ts b/types/holderjs/holderjs-tests.ts new file mode 100644 index 0000000000..5a33d74aac --- /dev/null +++ b/types/holderjs/holderjs-tests.ts @@ -0,0 +1,7 @@ +import * as Holder from "holderjs"; + +const myImage = document.getElementById('myImage'); + +Holder.run({ + images: myImage +}); diff --git a/types/holderjs/index.d.ts b/types/holderjs/index.d.ts new file mode 100644 index 0000000000..a77d5cda60 --- /dev/null +++ b/types/holderjs/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for holderjs 2.9 +// Project: http://holderjs.com +// Definitions by: Soner Köksal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface Options { + images: HTMLElement | null; +} + +export function run(options: Options): void; diff --git a/types/holderjs/tsconfig.json b/types/holderjs/tsconfig.json new file mode 100644 index 0000000000..6cf9415ee2 --- /dev/null +++ b/types/holderjs/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "holderjs-tests.ts" + ] +} diff --git a/types/holderjs/tslint.json b/types/holderjs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/holderjs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ioredis/index.d.ts b/types/ioredis/index.d.ts index 8353b4e563..f1d7f6eb95 100644 --- a/types/ioredis/index.d.ts +++ b/types/ioredis/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for ioredis +// Type definitions for ioredis 3.2 // Project: https://github.com/luin/ioredis -// Definitions by: York Yao +// Definitions by: York Yao // Christopher Eck // Yoga Aliarham // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -13,635 +13,738 @@ /// interface RedisStatic { - new (port?: number, host?: string, options?: IORedis.RedisOptions): IORedis.Redis; - new (host?: string, options?: IORedis.RedisOptions): IORedis.Redis; - new (options: IORedis.RedisOptions): IORedis.Redis; - new (url: string): IORedis.Redis; + new(port?: number, host?: string, options?: IORedis.RedisOptions): IORedis.Redis; + new(host?: string, options?: IORedis.RedisOptions): IORedis.Redis; + new(options?: IORedis.RedisOptions): IORedis.Redis; (port?: number, host?: string, options?: IORedis.RedisOptions): IORedis.Redis; (host?: string, options?: IORedis.RedisOptions): IORedis.Redis; - (options: IORedis.RedisOptions): IORedis.Redis; - (url: string): IORedis.Redis; + (options?: IORedis.RedisOptions): IORedis.Redis; Cluster: IORedis.Cluster; + Command: IORedis.Command; } declare var IORedis: RedisStatic; export = IORedis; -declare module IORedis { - interface Commander { - new (): Commander; - getBuiltinCommands(): string[]; - createBuiltinCommand(commandName: string): {}; - defineCommand(name: string, definition: { - numberOfKeys?: number; - lua?: string; - }): any; - sendCommand(): void; +declare class Commander { + getBuiltinCommands(): string[]; + createBuiltinCommand(commandName: string): {}; + defineCommand(name: string, definition: { + numberOfKeys?: number; + lua?: string; + }): any; + sendCommand(): void; +} + +declare namespace IORedis { + interface Command { + setArgumentTransformer(name: string, fn: (args: any[]) => any[]): void; + setReplyTransformer(name: string, fn: (result: any) => any): void; } interface Redis extends NodeJS.EventEmitter, Commander { status: string; - connect(callback?: Function): Promise; + connect(callback?: () => void): Promise; disconnect(): void; duplicate(): Redis; - monitor(calback: (error: Error, monitor: NodeJS.EventEmitter) => void): Promise; send_command(command: string, ...args: any[]): any; - auth(password: string, callback?: ResCallbackT): any; - ping(callback?: ResCallbackT): any; - append(key: string, value: string, callback?: ResCallbackT): any; - bitcount(key: string, callback?: ResCallbackT): any; - bitcount(key: string, start: number, end: number, callback?: ResCallbackT): any; - set(key: string, value: string, callback?: ResCallbackT): any; - get(key: string, callback?: ResCallbackT): any; - exists(key: string, value: string, callback?: ResCallbackT): any; - publish(channel: string, value: any): any; - subscribe(channel: string): any; - get(args: any[], callback?: ResCallbackT): any; - get(...args: any[]): any; - getBuffer(key: string, callback?: ResCallbackT): any; - set(args: any[], callback?: ResCallbackT): any; - set(...args: any[]): any; - setnx(args: any[], callback?: ResCallbackT): any; - setnx(...args: any[]): any; - setex(args: any[], callback?: ResCallbackT): any; - setex(...args: any[]): any; - psetex(args: any[], callback?: ResCallbackT): any; - psetex(...args: any[]): any; - append(args: any[], callback?: ResCallbackT): any; - append(...args: any[]): any; - strlen(args: any[], callback?: ResCallbackT): any; - strlen(...args: any[]): any; - del(args: any[], callback?: ResCallbackT): any; - del(...args: any[]): any; - exists(args: any[], callback?: ResCallbackT): any; - exists(...args: any[]): any; - setbit(args: any[], callback?: ResCallbackT): any; - setbit(...args: any[]): any; - getbit(args: any[], callback?: ResCallbackT): any; - getbit(...args: any[]): any; - setrange(args: any[], callback?: ResCallbackT): any; - setrange(...args: any[]): any; - getrange(args: any[], callback?: ResCallbackT): any; - getrange(...args: any[]): any; - substr(args: any[], callback?: ResCallbackT): any; - substr(...args: any[]): any; - incr(args: any[], callback?: ResCallbackT): any; - incr(...args: any[]): any; - decr(args: any[], callback?: ResCallbackT): any; - decr(...args: any[]): any; - mget(args: any[], callback?: ResCallbackT): any; - mget(...args: any[]): any; - rpush(...args: any[]): any; - lpush(args: any[], callback?: ResCallbackT): any; - lpush(...args: any[]): any; - rpushx(args: any[], callback?: ResCallbackT): any; - rpushx(...args: any[]): any; - lpushx(args: any[], callback?: ResCallbackT): any; - lpushx(...args: any[]): any; - linsert(args: any[], callback?: ResCallbackT): any; - linsert(...args: any[]): any; - rpop(args: any[], callback?: ResCallbackT): any; - rpop(...args: any[]): any; - lpop(args: any[], callback?: ResCallbackT): any; - lpop(...args: any[]): any; - brpop(args: any[], callback?: ResCallbackT): any; - brpop(...args: any[]): any; - brpoplpush(args: any[], callback?: ResCallbackT): any; - brpoplpush(...args: any[]): any; - blpop(args: any[], callback?: ResCallbackT): any; - blpop(...args: any[]): any; - llen(args: any[], callback?: ResCallbackT): any; - llen(...args: any[]): any; - lindex(args: any[], callback?: ResCallbackT): any; - lindex(...args: any[]): any; - lset(args: any[], callback?: ResCallbackT): any; - lset(...args: any[]): any; - lrange(args: any[], callback?: ResCallbackT): any; - lrange(...args: any[]): any; - ltrim(args: any[], callback?: ResCallbackT): any; - ltrim(...args: any[]): any; - lrem(args: any[], callback?: ResCallbackT): any; - lrem(...args: any[]): any; - rpoplpush(args: any[], callback?: ResCallbackT): any; - rpoplpush(...args: any[]): any; - sadd(args: any[], callback?: ResCallbackT): any; - sadd(...args: any[]): any; - srem(args: any[], callback?: ResCallbackT): any; - srem(...args: any[]): any; - smove(args: any[], callback?: ResCallbackT): any; - smove(...args: any[]): any; - sismember(args: any[], callback?: ResCallbackT): any; - sismember(...args: any[]): any; - scard(args: any[], callback?: ResCallbackT): any; - scard(...args: any[]): any; - spop(args: any[], callback?: ResCallbackT): any; - spop(...args: any[]): any; - srandmember(args: any[], callback?: ResCallbackT): any; - srandmember(...args: any[]): any; - sinter(args: any[], callback?: ResCallbackT): any; - sinter(...args: any[]): any; - sinterstore(args: any[], callback?: ResCallbackT): any; - sinterstore(...args: any[]): any; - sunion(args: any[], callback?: ResCallbackT): any; - sunion(...args: any[]): any; - sunionstore(args: any[], callback?: ResCallbackT): any; - sunionstore(...args: any[]): any; - sdiff(args: any[], callback?: ResCallbackT): any; - sdiff(...args: any[]): any; - sdiffstore(args: any[], callback?: ResCallbackT): any; - sdiffstore(...args: any[]): any; - smembers(args: any[], callback?: ResCallbackT): any; - smembers(...args: any[]): any; - zadd(args: any[], callback?: ResCallbackT): any; - zadd(...args: any[]): any; - zincrby(args: any[], callback?: ResCallbackT): any; - zincrby(...args: any[]): any; - zrem(args: any[], callback?: ResCallbackT): any; - zrem(...args: any[]): any; - zremrangebyscore(args: any[], callback?: ResCallbackT): any; - zremrangebyscore(...args: any[]): any; - zremrangebyrank(args: any[], callback?: ResCallbackT): any; - zremrangebyrank(...args: any[]): any; - zunionstore(args: any[], callback?: ResCallbackT): any; - zunionstore(...args: any[]): any; - zinterstore(args: any[], callback?: ResCallbackT): any; - zinterstore(...args: any[]): any; - zrange(args: any[], callback?: ResCallbackT): any; - zrange(...args: any[]): any; - zrangebyscore(args: any[], callback?: ResCallbackT): any; - zrangebyscore(...args: any[]): any; - zrevrangebyscore(args: any[], callback?: ResCallbackT): any; - zrevrangebyscore(...args: any[]): any; - zcount(args: any[], callback?: ResCallbackT): any; - zcount(...args: any[]): any; - zrevrange(args: any[], callback?: ResCallbackT): any; - zrevrange(...args: any[]): any; - zcard(args: any[], callback?: ResCallbackT): any; - zcard(...args: any[]): any; - zscore(args: any[], callback?: ResCallbackT): any; - zscore(...args: any[]): any; - zrank(args: any[], callback?: ResCallbackT): any; - zrank(...args: any[]): any; - zrevrank(args: any[], callback?: ResCallbackT): any; - zrevrank(...args: any[]): any; - hset(args: any[], callback?: ResCallbackT): any; - hset(...args: any[]): any; - hsetnx(args: any[], callback?: ResCallbackT): any; - hsetnx(...args: any[]): any; - hget(args: any[], callback?: ResCallbackT): any; - hget(...args: any[]): any; - hmset(args: any[], callback?: ResCallbackT): any; - hmset(key: string, hash: any, callback?: ResCallbackT): any; - hmset(...args: any[]): any; - hmget(args: any[], callback?: ResCallbackT): any; - hmget(...args: any[]): any; - hincrby(args: any[], callback?: ResCallbackT): any; - hincrby(...args: any[]): any; - hincrbyfloat(args: any[], callback?: ResCallbackT): any; - hincrbyfloat(...args: any[]): any; - hdel(args: any[], callback?: ResCallbackT): any; - hdel(...args: any[]): any; - hlen(args: any[], callback?: ResCallbackT): any; - hlen(...args: any[]): any; - hkeys(args: any[], callback?: ResCallbackT): any; - hkeys(...args: any[]): any; - hvals(args: any[], callback?: ResCallbackT): any; - hvals(...args: any[]): any; - hgetall(args: any[], callback?: ResCallbackT): any; - hgetall(...args: any[]): any; - hgetall(key: string, callback?: ResCallbackT): any; - hexists(args: any[], callback?: ResCallbackT): any; - hexists(...args: any[]): any; - incrby(args: any[], callback?: ResCallbackT): any; - incrby(...args: any[]): any; - incrbyfloat(args: any[], callback?: ResCallbackT): any; - incrbyfloat(...args: any[]): any; - decrby(args: any[], callback?: ResCallbackT): any; - decrby(...args: any[]): any; - getset(args: any[], callback?: ResCallbackT): any; - getset(...args: any[]): any; - mset(args: any[], callback?: ResCallbackT): any; - mset(...args: any[]): any; - msetnx(args: any[], callback?: ResCallbackT): any; - msetnx(...args: any[]): any; - randomkey(args: any[], callback?: ResCallbackT): any; - randomkey(...args: any[]): any; - select(args: any[], callback?: ResCallbackT): void; - select(...args: any[]): void; - move(args: any[], callback?: ResCallbackT): any; - move(...args: any[]): any; - rename(args: any[], callback?: ResCallbackT): any; - rename(...args: any[]): any; - renamenx(args: any[], callback?: ResCallbackT): any; - renamenx(...args: any[]): any; - expire(args: any[], callback?: ResCallbackT): any; - expire(...args: any[]): any; - pexpire(args: any[], callback?: ResCallbackT): any; - pexpire(...args: any[]): any; - expireat(args: any[], callback?: ResCallbackT): any; - expireat(...args: any[]): any; - pexpireat(args: any[], callback?: ResCallbackT): any; - pexpireat(...args: any[]): any; - keys(args: any[], callback?: ResCallbackT): any; - keys(...args: any[]): any; - dbsize(args: any[], callback?: ResCallbackT): any; - dbsize(...args: any[]): any; - auth(args: any[], callback?: ResCallbackT): void; - auth(...args: any[]): void; - ping(args: any[], callback?: ResCallbackT): any; - ping(...args: any[]): any; - echo(args: any[], callback?: ResCallbackT): any; - echo(...args: any[]): any; - save(args: any[], callback?: ResCallbackT): any; - save(...args: any[]): any; - bgsave(args: any[], callback?: ResCallbackT): any; - bgsave(...args: any[]): any; - bgrewriteaof(args: any[], callback?: ResCallbackT): any; - bgrewriteaof(...args: any[]): any; - shutdown(args: any[], callback?: ResCallbackT): any; - shutdown(...args: any[]): any; - lastsave(args: any[], callback?: ResCallbackT): any; - lastsave(...args: any[]): any; - type(args: any[], callback?: ResCallbackT): any; - type(...args: any[]): any; - multi(args: any[], callback?: ResCallbackT): Pipeline; - multi(...args: any[]): Pipeline; - exec(args: any[], callback?: ResCallbackT): any; - exec(...args: any[]): any; - discard(args: any[], callback?: ResCallbackT): any; - discard(...args: any[]): any; - sync(args: any[], callback?: ResCallbackT): any; - sync(...args: any[]): any; - flushdb(args: any[], callback?: ResCallbackT): any; - flushdb(...args: any[]): any; - flushall(args: any[], callback?: ResCallbackT): any; - flushall(...args: any[]): any; - sort(args: any[], callback?: ResCallbackT): any; - sort(...args: any[]): any; - info(args: any[], callback?: ResCallbackT): any; - info(...args: any[]): any; - time(args: any[], callback?: ResCallbackT): any; - time(...args: any[]): any; - monitor(args: any[], callback?: ResCallbackT): any; - monitor(...args: any[]): any; - ttl(args: any[], callback?: ResCallbackT): any; - ttl(...args: any[]): any; - persist(args: any[], callback?: ResCallbackT): any; - persist(...args: any[]): any; - slaveof(args: any[], callback?: ResCallbackT): any; - slaveof(...args: any[]): any; - debug(args: any[], callback?: ResCallbackT): any; + + bitcount(key: string, callback: (err: Error, res: number) => void): void; + bitcount(key: string, start: number, end: number, callback: (err: Error, res: number) => void): void; + bitcount(key: string): Promise; + bitcount(key: string, start: number, end: number): Promise; + + get(key: string, callback: (err: Error, res: string) => void): void; + get(key: string): Promise; + getBuffer(key: string, callback: (err: Error, res: Buffer) => void): void; + getBuffer(key: string): Promise; + + set(key: string, value: any, ...args: any[]): any; + + setnx(key: string, value: any, callback: (err: Error, res: any) => void): void; + setnx(key: string, value: any): Promise; + + setex(key: string, seconds: number, value: any, callback: (err: Error, res: any) => void): void; + setex(key: string, seconds: number, value: any): Promise; + + psetex(key: string, milliseconds: number, value: any, callback: (err: Error, res: any) => void): void; + psetex(key: string, milliseconds: number, value: any): Promise; + + append(key: string, value: any, callback: (err: Error, res: number) => void): void; + append(key: string, value: any): Promise; + + strlen(key: string, callback: (err: Error, res: number) => void): void; + strlen(key: string): Promise; + + del(key: string, ...keys: string[]): any; + + exists(key: string, ...keys: string[]): any; + + setbit(key: string, offset: number, value: any, callback: (err: Error, res: number) => void): void; + setbit(key: string, offset: number, value: any): Promise; + + getbit(key: string, offset: number, callback: (err: Error, res: number) => void): void; + getbit(key: string, offset: number): Promise; + + setrange(key: string, offset: number, value: any, callback: (err: Error, res: number) => void): void; + setrange(key: string, offset: number, value: any): Promise; + + getrange(key: string, start: number, end: number, callback: (err: Error, res: string) => void): void; + getrange(key: string, start: number, end: number): Promise; + + substr(key: string, start: number, end: number, callback: (err: Error, res: string) => void): void; + substr(key: string, start: number, end: number): Promise; + + incr(key: string, callback: (err: Error, res: number) => void): void; + incr(key: string): Promise; + + decr(key: string, callback: (err: Error, res: number) => void): void; + decr(key: string): Promise; + + mget(key: string, ...keys: string[]): any; + + rpush(key: string, value: any, ...values: string[]): any; + + lpush(key: string, value: any, ...values: string[]): any; + + rpushx(key: string, value: any, callback: (err: Error, res: number) => void): void; + rpushx(key: string, value: any): Promise; + + lpushx(key: string, value: any, callback: (err: Error, res: number) => void): void; + lpushx(key: string, value: any): Promise; + + linsert(key: string, direction: "BEFORE" | "AFTER", pivot: string, value: any, callback: (err: Error, res: number) => void): void; + linsert(key: string, direction: "BEFORE" | "AFTER", pivot: string, value: any): Promise; + + rpop(key: string, callback: (err: Error, res: string) => void): void; + rpop(key: string): Promise; + + lpop(key: string, callback: (err: Error, res: string) => void): void; + lpop(key: string): Promise; + + brpop(key: string, ...keys: string[]): any; + + blpop(key: string, ...keys: string[]): any; + + brpoplpush(source: string, destination: string, timeout: number, callback: (err: Error, res: any) => void): void; + brpoplpush(source: string, destination: string, timeout: number): Promise; + + llen(key: string, callback: (err: Error, res: number) => void): void; + llen(key: string): Promise; + + lindex(key: string, index: number, callback: (err: Error, res: string) => void): void; + lindex(key: string, index: number): Promise; + + lset(key: string, index: number, value: any, callback: (err: Error, res: any) => void): void; + lset(key: string, index: number, value: any): Promise; + + lrange(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; + lrange(key: string, start: number, stop: number): Promise; + + ltrim(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; + ltrim(key: string, start: number, stop: number): Promise; + + lrem(key: string, count: number, value: any, callback: (err: Error, res: number) => void): void; + lrem(key: string, count: number, value: any): Promise; + + rpoplpush(source: string, destination: string, callback: (err: Error, res: string) => void): void; + rpoplpush(source: string, destination: string): Promise; + + sadd(key: string, ...members: any[]): any; + + srem(key: string, ...members: any[]): any; + + smove(source: string, destination: string, member: string, callback: (err: Error, res: string) => void): void; + smove(source: string, destination: string, member: string): Promise; + + sismember(key: string, member: string, callback: (err: Error, res: 1 | 0) => void): void; + sismember(key: string, member: string): Promise<1 | 0>; + + scard(key: string, callback: (err: Error, res: number) => void): void; + scard(key: string): Promise; + + spop(key: string, callback: (err: Error, res: any) => void): void; + spop(key: string, count: number, callback: (err: Error, res: any) => void): void; + spop(key: string, count?: number): Promise; + + srandmember(key: string, callback: (err: Error, res: any) => void): void; + srandmember(key: string, count: number, callback: (err: Error, res: any) => void): void; + srandmember(key: string, count?: number): Promise; + + sinter(key: string, ...keys: string[]): any; + + sinterstore(destination: string, key: string, ...keys: string[]): any; + + sunion(key: string, ...keys: string[]): any; + + sunionstore(destination: string, key: string, ...keys: string[]): any; + + sdiff(key: string, ...keys: string[]): any; + + sdiffstore(destination: string, key: string, ...keys: string[]): any; + + smembers(key: string, callback: (err: Error, res: any) => void): void; + smembers(key: string): Promise; + + zadd(key: string, ...args: string[]): any; + + zincrby(key: string, increment: number, member: string, callback: (err: Error, res: any) => void): void; + zincrby(key: string, increment: number, member: string): Promise; + + zrem(key: string, member: string, ...members: any[]): any; + + zremrangebyscore(key: string, min: number, max: number, callback: (err: Error, res: any) => void): void; + zremrangebyscore(key: string, min: number, max: number): Promise; + + zremrangebyrank(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; + zremrangebyrank(key: string, start: number, stop: number): Promise; + + zunionstore(destination: string, numkeys: number, key: string, ...args: string[]): any; + + zinterstore(destination: string, numkeys: number, key: string, ...args: string[]): any; + + zrange(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; + zrange(key: string, start: number, stop: number, withScores: "WITHSCORES", callback: (err: Error, res: any) => void): void; + zrange(key: string, start: number, stop: number, withScores?: "WITHSCORES"): Promise; + + zrevrange(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; + zrevrange(key: string, start: number, stop: number, withScores: "WITHSCORES", callback: (err: Error, res: any) => void): void; + zrevrange(key: string, start: number, stop: number, withScores?: "WITHSCORES"): Promise; + + zrangebyscore(key: string, min: number, max: number, ...args: string[]): any; + + zrevrangebyscore(key: string, max: number, min: number, ...args: string[]): any; + + zcount(key: string, min: number, max: number, callback: (err: Error, res: number) => void): void; + zcount(key: string, min: number, max: number): Promise; + + zcard(key: string, callback: (err: Error, res: number) => void): void; + zcard(key: string): Promise; + + zscore(key: string, member: string, callback: (err: Error, res: number) => void): void; + zscore(key: string, member: string): Promise; + + zrank(key: string, member: string, callback: (err: Error, res: number) => void): void; + zrank(key: string, member: string): Promise; + + zrevrank(key: string, member: string, callback: (err: Error, res: number) => void): void; + zrevrank(key: string, member: string): Promise; + + hset(key: string, field: string, value: any, callback: (err: Error, res: 0 | 1) => void): void; + hset(key: string, field: string, value: any): Promise<0 | 1>; + + hsetnx(key: string, field: string, value: any, callback: (err: Error, res: 0 | 1) => void): void; + hsetnx(key: string, field: string, value: any): Promise<0 | 1>; + + hget(key: string, field: string, callback: (err: Error, res: string) => void): void; + hget(key: string, field: string): Promise; + + hmset(key: string, field: string, value: any, ...args: string[]): any; + + hmget(key: string, field: string, ...fields: string[]): any; + + hincrby(key: string, field: string, increment: number, callback: (err: Error, res: number) => void): void; + hincrby(key: string, field: string, increment: number): Promise; + + hincrbyfloat(key: string, field: string, increment: number, callback: (err: Error, res: number) => void): void; + hincrbyfloat(key: string, field: string, increment: number): Promise; + + hdel(key: string, field: string, ...fields: string[]): any; + + hlen(key: string, callback: (err: Error, res: number) => void): void; + hlen(key: string): Promise; + + hkeys(key: string, callback: (err: Error, res: any) => void): void; + hkeys(key: string): Promise; + + hvals(key: string, callback: (err: Error, res: any) => void): void; + hvals(key: string): Promise; + + hgetall(key: string, callback: (err: Error, res: any) => void): void; + hgetall(key: string): Promise; + + hexists(key: string, field: string, callback: (err: Error, res: 0 | 1) => void): void; + hexists(key: string, field: string): Promise<0 | 1>; + + incrby(key: string, increment: number, callback: (err: Error, res: number) => void): void; + incrby(key: string, increment: number): Promise; + + incrbyfloat(key: string, increment: number, callback: (err: Error, res: number) => void): void; + incrbyfloat(key: string, increment: number): Promise; + + decrby(key: string, decrement: number, callback: (err: Error, res: number) => void): void; + decrby(key: string, decrement: number): Promise; + + getset(key: string, value: any, callback: (err: Error, res: string) => void): void; + getset(key: string, value: any): Promise; + + mset(key: string, value: any, ...args: string[]): any; + + msetnx(key: string, value: any, ...args: string[]): any; + + randomkey(callback: (err: Error, res: string) => void): void; + randomkey(): Promise; + + select(index: number, callback: (err: Error, res: string) => void): void; + select(index: number): Promise; + + move(key: string, db: string, callback: (err: Error, res: 0 | 1) => void): void; + move(key: string, db: string): Promise<0 | 1>; + + rename(key: string, newkey: string, callback: (err: Error, res: string) => void): void; + rename(key: string, newkey: string): Promise; + + renamenx(key: string, newkey: string, callback: (err: Error, res: 0 | 1) => void): void; + renamenx(key: string, newkey: string): Promise<0 | 1>; + + expire(key: string, seconds: number, callback: (err: Error, res: 0 | 1) => void): void; + expire(key: string, seconds: number): Promise<0 | 1>; + + pexpire(key: string, milliseconds: number, callback: (err: Error, res: 0 | 1) => void): void; + pexpire(key: string, milliseconds: number): Promise<0 | 1>; + + expireat(key: string, timestamp: number, callback: (err: Error, res: 0 | 1) => void): void; + expireat(key: string, timestamp: number): Promise<0 | 1>; + + pexpireat(key: string, millisecondsTimestamp: number, callback: (err: Error, res: 0 | 1) => void): void; + pexpireat(key: string, millisecondsTimestamp: number): Promise<0 | 1>; + + keys(pattern: string, callback: (err: Error, res: string[]) => void): void; + keys(pattern: string): Promise; + + dbsize(callback: (err: Error, res: number) => void): void; + dbsize(): Promise; + + auth(password: string, callback: (err: Error, res: string) => void): void; + auth(password: string): Promise; + + ping(callback: (err: Error, res: string) => void): void; + ping(message: string, callback: (err: Error, res: string) => void): void; + ping(message?: string): Promise; + + echo(message: string, callback: (err: Error, res: string) => void): void; + echo(message: string): Promise; + + save(callback: (err: Error, res: string) => void): void; + save(): Promise; + + bgsave(callback: (err: Error, res: string) => void): void; + bgsave(): Promise; + + bgrewriteaof(callback: (err: Error, res: string) => void): void; + bgrewriteaof(): Promise; + + shutdown(save: "SAVE" | "NOSAVE", callback: (err: Error, res: any) => void): void; + shutdown(save: "SAVE" | "NOSAVE"): Promise; + + lastsave(callback: (err: Error, res: number) => void): void; + lastsave(): Promise; + + type(key: string, callback: (err: Error, res: string) => void): void; + type(key: string): Promise; + + multi(callback: (err: Error, res: string) => void): void; + multi(): Promise; + + exec(callback: (err: Error, res: any) => void): void; + exec(): Promise; + + discard(callback: (err: Error, res: any) => void): void; + discard(): Promise; + + sync(callback: (err: Error, res: any) => void): void; + sync(): Promise; + + flushdb(callback: (err: Error, res: string) => void): void; + flushdb(): Promise; + + flushall(callback: (err: Error, res: string) => void): void; + flushall(): Promise; + + sort(key: string, ...args: string[]): any; + + info(callback: (err: Error, res: any) => void): void; + info(section: string, callback: (err: Error, res: any) => void): void; + info(section?: string): Promise; + + time(callback: (err: Error, res: any) => void): void; + time(): Promise; + + monitor(callback: (err: Error, res: NodeJS.EventEmitter) => void): void; + monitor(): Promise; + + ttl(key: string, callback: (err: Error, res: number) => void): void; + ttl(key: string): Promise; + + persist(key: string, callback: (err: Error, res: 0 | 1) => void): void; + persist(key: string): Promise<0 | 1>; + + slaveof(host: string, port: number, callback: (err: Error, res: string) => void): void; + slaveof(host: string, port: number): Promise; + debug(...args: any[]): any; - config(args: any[], callback?: ResCallbackT): any; + config(...args: any[]): any; - subscribe(args: any[], callback?: ResCallbackT): any; - subscribe(...args: any[]): any; - unsubscribe(args: any[], callback?: ResCallbackT): any; - unsubscribe(...args: any[]): any; - psubscribe(args: any[], callback?: ResCallbackT): any; - psubscribe(...args: any[]): any; - punsubscribe(args: any[], callback?: ResCallbackT): any; - punsubscribe(...args: any[]): any; - publish(args: any[], callback?: ResCallbackT): any; - publish(...args: any[]): any; - watch(args: any[], callback?: ResCallbackT): any; - watch(...args: any[]): any; - unwatch(args: any[], callback?: ResCallbackT): any; - unwatch(...args: any[]): any; - cluster(args: any[], callback?: ResCallbackT): any; + + subscribe(channel: string, ...channels: any[]): any; + + unsubscribe(...channels: string[]): any; + + psubscribe(pattern: string, ...patterns: string[]): any; + + punsubscribe(...patterns: string[]): any; + + publish(channel: string, message: string, callback: (err: Error, res: number) => void): void; + publish(channel: string, message: string): Promise; + + watch(key: string, ...keys: string[]): any; + + unwatch(callback: (err: Error, res: string) => void): void; + unwatch(): Promise; + cluster(...args: any[]): any; - restore(args: any[], callback?: ResCallbackT): any; + restore(...args: any[]): any; - migrate(args: any[], callback?: ResCallbackT): any; + migrate(...args: any[]): any; - dump(args: any[], callback?: ResCallbackT): any; - dump(...args: any[]): any; - object(args: any[], callback?: ResCallbackT): any; - object(...args: any[]): any; - client(args: any[], callback?: ResCallbackT): any; + + dump(key: string, callback: (err: Error, res: string) => void): void; + dump(key: string): Promise; + + object(subcommand: string, ...args: any[]): any; + client(...args: any[]): any; - eval(args: any[], callback?: ResCallbackT): any; + eval(...args: any[]): any; - evalsha(args: any[], callback?: ResCallbackT): any; + evalsha(...args: any[]): any; - script(args: any[], callback?: ResCallbackT): any; - script(key: string, callback?: ResCallbackT): any; + script(...args: any[]): any; - quit(args: any[], callback?: ResCallbackT): any; - quit(...args: any[]): any; - scan(args: any[], callback?: ResCallbackT): any; - scan(...args: any[]): any; - hscan(args: any[], callback?: ResCallbackT): any; - hscan(...args: any[]): any; - zscan(args: any[], callback?: ResCallbackT): any; - zscan(...args: any[]): any; - pfmerge(args: any[], callback?: ResCallbackT): any; - pfmerge(...args: any[]): any; - pfadd(args: any[], callback?: ResCallbackT): any; - pfadd(...args: any[]): any; - pfcount(args: any[], callback?: ResCallbackT): any; - pfcount(...args: any[]): any; - pipeline(): Pipeline; - pipeline(commands: string[][]): Pipeline; + quit(callback: (err: Error, res: string) => void): void; + quit(): Promise; - scanStream(options?: IORedis.ScanStreamOption): NodeJS.EventEmitter; - hscanStream(key: string, options?: IORedis.ScanStreamOption): NodeJS.EventEmitter; - zscanStream(key: string, options?: IORedis.ScanStreamOption): NodeJS.EventEmitter; + scan(cursor: number, ...args: any[]): any; + + hscan(key: string, cursor: number, ...args: any[]): any; + + zscan(key: string, cursor: number, ...args: any[]): any; + + pfmerge(destkey: string, sourcekey: string, ...sourcekeys: string[]): any; + + pfadd(key: string, element: string, ...elements: string[]): any; + + pfcount(key: string, ...keys: string[]): any; + + pipeline(commands?: string[][]): Pipeline; + + scanStream(options?: ScanStreamOption): NodeJS.EventEmitter; + hscanStream(key: string, options?: ScanStreamOption): NodeJS.EventEmitter; + zscanStream(key: string, options?: ScanStreamOption): NodeJS.EventEmitter; } interface Pipeline { - exec(callback?: ResCallbackT): any; + bitcount(key: string, callback?: (err: Error, res: number) => void): Pipeline; + bitcount(key: string, start: number, end: number, callback?: (err: Error, res: number) => void): Pipeline; + + get(key: string, callback?: (err: Error, res: string) => void): Pipeline; + getBuffer(key: string, callback?: (err: Error, res: Buffer) => void): Pipeline; + + set(key: string, value: any, ...args: any[]): Pipeline; + + setnx(key: string, value: any, callback?: (err: Error, res: any) => void): Pipeline; + + setex(key: string, seconds: number, value: any, callback?: (err: Error, res: any) => void): Pipeline; + + psetex(key: string, milliseconds: number, value: any, callback?: (err: Error, res: any) => void): Pipeline; + + append(key: string, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + strlen(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + del(key: string, ...keys: string[]): Pipeline; + + exists(key: string, ...keys: string[]): Pipeline; + + setbit(key: string, offset: number, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + getbit(key: string, offset: number, callback?: (err: Error, res: number) => void): Pipeline; + + setrange(key: string, offset: number, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + getrange(key: string, start: number, end: number, callback?: (err: Error, res: string) => void): Pipeline; + + substr(key: string, start: number, end: number, callback?: (err: Error, res: string) => void): Pipeline; + + incr(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + decr(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + mget(key: string, ...keys: string[]): Pipeline; + + rpush(key: string, value: any, ...values: string[]): Pipeline; + + lpush(key: string, value: any, ...values: string[]): Pipeline; + + rpushx(key: string, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + lpushx(key: string, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + linsert(key: string, direction: "BEFORE" | "AFTER", pivot: string, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + rpop(key: string, callback?: (err: Error, res: string) => void): Pipeline; + + lpop(key: string, callback?: (err: Error, res: string) => void): Pipeline; + + brpop(key: string, ...keys: string[]): Pipeline; + + blpop(key: string, ...keys: string[]): Pipeline; + + brpoplpush(source: string, destination: string, timeout: number, callback?: (err: Error, res: any) => void): Pipeline; + + llen(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + lindex(key: string, index: number, callback?: (err: Error, res: string) => void): Pipeline; + + lset(key: string, index: number, value: any, callback?: (err: Error, res: any) => void): Pipeline; + + lrange(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; + + ltrim(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; + + lrem(key: string, count: number, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + rpoplpush(source: string, destination: string, callback?: (err: Error, res: string) => void): Pipeline; + + sadd(key: string, ...members: any[]): Pipeline; + + srem(key: string, ...members: any[]): Pipeline; + + smove(source: string, destination: string, member: string, callback?: (err: Error, res: string) => void): Pipeline; + + sismember(key: string, member: string, callback?: (err: Error, res: 1 | 0) => void): Pipeline; + + scard(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + spop(key: string, callback?: (err: Error, res: any) => void): Pipeline; + spop(key: string, count: number, callback?: (err: Error, res: any) => void): Pipeline; + + srandmember(key: string, callback?: (err: Error, res: any) => void): Pipeline; + srandmember(key: string, count: number, callback?: (err: Error, res: any) => void): Pipeline; + + sinter(key: string, ...keys: string[]): Pipeline; + + sinterstore(destination: string, key: string, ...keys: string[]): Pipeline; + + sunion(key: string, ...keys: string[]): Pipeline; + + sunionstore(destination: string, key: string, ...keys: string[]): Pipeline; + + sdiff(key: string, ...keys: string[]): Pipeline; + + sdiffstore(destination: string, key: string, ...keys: string[]): Pipeline; + + smembers(key: string, callback?: (err: Error, res: any) => void): Pipeline; + + zadd(key: string, ...args: string[]): Pipeline; + + zincrby(key: string, increment: number, member: string, callback?: (err: Error, res: any) => void): Pipeline; + + zrem(key: string, member: string, ...members: any[]): Pipeline; + + zremrangebyscore(key: string, min: number, max: number, callback?: (err: Error, res: any) => void): Pipeline; + + zremrangebyrank(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; + + zunionstore(destination: string, numkeys: number, key: string, ...args: string[]): Pipeline; + + zinterstore(destination: string, numkeys: number, key: string, ...args: string[]): Pipeline; + + zrange(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; + zrange(key: string, start: number, stop: number, withScores: "WITHSCORES", callback?: (err: Error, res: any) => void): Pipeline; + + zrevrange(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; + zrevrange(key: string, start: number, stop: number, withScores: "WITHSCORES", callback?: (err: Error, res: any) => void): Pipeline; + + zrangebyscore(key: string, min: number, max: number, ...args: string[]): Pipeline; + + zrevrangebyscore(key: string, max: number, min: number, ...args: string[]): Pipeline; + + zcount(key: string, min: number, max: number, callback?: (err: Error, res: number) => void): Pipeline; + + zcard(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + zscore(key: string, member: string, callback?: (err: Error, res: number) => void): Pipeline; + + zrank(key: string, member: string, callback?: (err: Error, res: number) => void): Pipeline; + + zrevrank(key: string, member: string, callback?: (err: Error, res: number) => void): Pipeline; + + hset(key: string, field: string, value: any, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + hsetnx(key: string, field: string, value: any, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + hget(key: string, field: string, callback?: (err: Error, res: string) => void): Pipeline; + + hmset(key: string, field: string, value: any, ...args: string[]): Pipeline; + + hmget(key: string, field: string, ...fields: string[]): Pipeline; + + hincrby(key: string, field: string, increment: number, callback?: (err: Error, res: number) => void): Pipeline; + + hincrbyfloat(key: string, field: string, increment: number, callback?: (err: Error, res: number) => void): Pipeline; + + hdel(key: string, field: string, ...fields: string[]): Pipeline; + + hlen(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + hkeys(key: string, callback?: (err: Error, res: any) => void): Pipeline; + + hvals(key: string, callback?: (err: Error, res: any) => void): Pipeline; + + hgetall(key: string, callback?: (err: Error, res: any) => void): Pipeline; + + hexists(key: string, field: string, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + incrby(key: string, increment: number, callback?: (err: Error, res: number) => void): Pipeline; + + incrbyfloat(key: string, increment: number, callback?: (err: Error, res: number) => void): Pipeline; + + decrby(key: string, decrement: number, callback?: (err: Error, res: number) => void): Pipeline; + + getset(key: string, value: any, callback?: (err: Error, res: string) => void): Pipeline; + + mset(key: string, value: any, ...args: string[]): Pipeline; + + msetnx(key: string, value: any, ...args: string[]): Pipeline; + + randomkey(callback?: (err: Error, res: string) => void): Pipeline; + + select(index: number, callback?: (err: Error, res: string) => void): Pipeline; + + move(key: string, db: string, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + rename(key: string, newkey: string, callback?: (err: Error, res: string) => void): Pipeline; + + renamenx(key: string, newkey: string, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + expire(key: string, seconds: number, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + pexpire(key: string, milliseconds: number, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + expireat(key: string, timestamp: number, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + pexpireat(key: string, millisecondsTimestamp: number, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + keys(pattern: string, callback?: (err: Error, res: string[]) => void): Pipeline; + + dbsize(callback?: (err: Error, res: number) => void): Pipeline; + + auth(password: string, callback?: (err: Error, res: string) => void): Pipeline; + + ping(callback?: (err: Error, res: string) => void): Pipeline; + ping(message: string, callback?: (err: Error, res: string) => void): Pipeline; + + echo(message: string, callback?: (err: Error, res: string) => void): Pipeline; + + save(callback?: (err: Error, res: string) => void): Pipeline; + + bgsave(callback?: (err: Error, res: string) => void): Pipeline; + + bgrewriteaof(callback?: (err: Error, res: string) => void): Pipeline; + + shutdown(save: "SAVE" | "NOSAVE", callback?: (err: Error, res: any) => void): Pipeline; + + lastsave(callback?: (err: Error, res: number) => void): Pipeline; + + type(key: string, callback?: (err: Error, res: string) => void): Pipeline; + + multi(callback?: (err: Error, res: string) => void): Pipeline; + + exec(callback?: (err: Error, res: any) => void): Promise; + + discard(callback?: (err: Error, res: any) => void): Pipeline; + + sync(callback?: (err: Error, res: any) => void): Pipeline; + + flushdb(callback?: (err: Error, res: string) => void): Pipeline; + + flushall(callback?: (err: Error, res: string) => void): Pipeline; + + sort(key: string, ...args: string[]): Pipeline; + + info(callback?: (err: Error, res: any) => void): Pipeline; + info(section: string, callback?: (err: Error, res: any) => void): Pipeline; + + time(callback?: (err: Error, res: any) => void): Pipeline; + + monitor(callback?: (err: Error, res: NodeJS.EventEmitter) => void): Pipeline; + + ttl(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + persist(key: string, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + slaveof(host: string, port: number, callback?: (err: Error, res: string) => void): Pipeline; - get(args: any[], callback?: ResCallbackT): Pipeline; - get(...args: any[]): Pipeline; - set(args: any[], callback?: ResCallbackT): Pipeline; - set(...args: any[]): Pipeline; - setnx(args: any[], callback?: ResCallbackT): Pipeline; - setnx(...args: any[]): Pipeline; - setex(args: any[], callback?: ResCallbackT): Pipeline; - setex(...args: any[]): Pipeline; - psetex(args: any[], callback?: ResCallbackT): Pipeline; - psetex(...args: any[]): Pipeline; - append(args: any[], callback?: ResCallbackT): Pipeline; - append(...args: any[]): Pipeline; - strlen(args: any[], callback?: ResCallbackT): Pipeline; - strlen(...args: any[]): Pipeline; - del(args: any[], callback?: ResCallbackT): Pipeline; - del(...args: any[]): Pipeline; - exists(args: any[], callback?: ResCallbackT): Pipeline; - exists(...args: any[]): Pipeline; - setbit(args: any[], callback?: ResCallbackT): Pipeline; - setbit(...args: any[]): Pipeline; - getbit(args: any[], callback?: ResCallbackT): Pipeline; - getbit(...args: any[]): Pipeline; - setrange(args: any[], callback?: ResCallbackT): Pipeline; - setrange(...args: any[]): Pipeline; - getrange(args: any[], callback?: ResCallbackT): Pipeline; - getrange(...args: any[]): Pipeline; - substr(args: any[], callback?: ResCallbackT): Pipeline; - substr(...args: any[]): Pipeline; - incr(args: any[], callback?: ResCallbackT): Pipeline; - incr(...args: any[]): Pipeline; - decr(args: any[], callback?: ResCallbackT): Pipeline; - decr(...args: any[]): Pipeline; - mget(args: any[], callback?: ResCallbackT): Pipeline; - mget(...args: any[]): Pipeline; - rpush(...args: any[]): Pipeline; - lpush(args: any[], callback?: ResCallbackT): Pipeline; - lpush(...args: any[]): Pipeline; - rpushx(args: any[], callback?: ResCallbackT): Pipeline; - rpushx(...args: any[]): Pipeline; - lpushx(args: any[], callback?: ResCallbackT): Pipeline; - lpushx(...args: any[]): Pipeline; - linsert(args: any[], callback?: ResCallbackT): Pipeline; - linsert(...args: any[]): Pipeline; - rpop(args: any[], callback?: ResCallbackT): Pipeline; - rpop(...args: any[]): Pipeline; - lpop(args: any[], callback?: ResCallbackT): Pipeline; - lpop(...args: any[]): Pipeline; - brpop(args: any[], callback?: ResCallbackT): Pipeline; - brpop(...args: any[]): Pipeline; - brpoplpush(args: any[], callback?: ResCallbackT): Pipeline; - brpoplpush(...args: any[]): Pipeline; - blpop(args: any[], callback?: ResCallbackT): Pipeline; - blpop(...args: any[]): Pipeline; - llen(args: any[], callback?: ResCallbackT): Pipeline; - llen(...args: any[]): Pipeline; - lindex(args: any[], callback?: ResCallbackT): Pipeline; - lindex(...args: any[]): Pipeline; - lset(args: any[], callback?: ResCallbackT): Pipeline; - lset(...args: any[]): Pipeline; - lrange(args: any[], callback?: ResCallbackT): Pipeline; - lrange(...args: any[]): Pipeline; - ltrim(args: any[], callback?: ResCallbackT): Pipeline; - ltrim(...args: any[]): Pipeline; - lrem(args: any[], callback?: ResCallbackT): Pipeline; - lrem(...args: any[]): Pipeline; - rpoplpush(args: any[], callback?: ResCallbackT): Pipeline; - rpoplpush(...args: any[]): Pipeline; - sadd(args: any[], callback?: ResCallbackT): Pipeline; - sadd(...args: any[]): Pipeline; - srem(args: any[], callback?: ResCallbackT): Pipeline; - srem(...args: any[]): Pipeline; - smove(args: any[], callback?: ResCallbackT): Pipeline; - smove(...args: any[]): Pipeline; - sismember(args: any[], callback?: ResCallbackT): Pipeline; - sismember(...args: any[]): Pipeline; - scard(args: any[], callback?: ResCallbackT): Pipeline; - scard(...args: any[]): Pipeline; - spop(args: any[], callback?: ResCallbackT): Pipeline; - spop(...args: any[]): Pipeline; - srandmember(args: any[], callback?: ResCallbackT): Pipeline; - srandmember(...args: any[]): Pipeline; - sinter(args: any[], callback?: ResCallbackT): Pipeline; - sinter(...args: any[]): Pipeline; - sinterstore(args: any[], callback?: ResCallbackT): Pipeline; - sinterstore(...args: any[]): Pipeline; - sunion(args: any[], callback?: ResCallbackT): Pipeline; - sunion(...args: any[]): Pipeline; - sunionstore(args: any[], callback?: ResCallbackT): Pipeline; - sunionstore(...args: any[]): Pipeline; - sdiff(args: any[], callback?: ResCallbackT): Pipeline; - sdiff(...args: any[]): Pipeline; - sdiffstore(args: any[], callback?: ResCallbackT): Pipeline; - sdiffstore(...args: any[]): Pipeline; - smembers(args: any[], callback?: ResCallbackT): Pipeline; - smembers(...args: any[]): Pipeline; - zadd(args: any[], callback?: ResCallbackT): Pipeline; - zadd(...args: any[]): Pipeline; - zincrby(args: any[], callback?: ResCallbackT): Pipeline; - zincrby(...args: any[]): Pipeline; - zrem(args: any[], callback?: ResCallbackT): Pipeline; - zrem(...args: any[]): Pipeline; - zremrangebyscore(args: any[], callback?: ResCallbackT): Pipeline; - zremrangebyscore(...args: any[]): Pipeline; - zremrangebyrank(args: any[], callback?: ResCallbackT): Pipeline; - zremrangebyrank(...args: any[]): Pipeline; - zunionstore(args: any[], callback?: ResCallbackT): Pipeline; - zunionstore(...args: any[]): Pipeline; - zinterstore(args: any[], callback?: ResCallbackT): Pipeline; - zinterstore(...args: any[]): Pipeline; - zrange(args: any[], callback?: ResCallbackT): Pipeline; - zrange(...args: any[]): Pipeline; - zrangebyscore(args: any[], callback?: ResCallbackT): Pipeline; - zrangebyscore(...args: any[]): Pipeline; - zrevrangebyscore(args: any[], callback?: ResCallbackT): Pipeline; - zrevrangebyscore(...args: any[]): Pipeline; - zcount(args: any[], callback?: ResCallbackT): Pipeline; - zcount(...args: any[]): Pipeline; - zrevrange(args: any[], callback?: ResCallbackT): Pipeline; - zrevrange(...args: any[]): Pipeline; - zcard(args: any[], callback?: ResCallbackT): Pipeline; - zcard(...args: any[]): Pipeline; - zscore(args: any[], callback?: ResCallbackT): Pipeline; - zscore(...args: any[]): Pipeline; - zrank(args: any[], callback?: ResCallbackT): Pipeline; - zrank(...args: any[]): Pipeline; - zrevrank(args: any[], callback?: ResCallbackT): Pipeline; - zrevrank(...args: any[]): Pipeline; - hset(args: any[], callback?: ResCallbackT): Pipeline; - hset(...args: any[]): Pipeline; - hsetnx(args: any[], callback?: ResCallbackT): Pipeline; - hsetnx(...args: any[]): Pipeline; - hget(args: any[], callback?: ResCallbackT): Pipeline; - hget(...args: any[]): Pipeline; - hmset(args: any[], callback?: ResCallbackT): Pipeline; - hmset(key: string, hash: any, callback?: ResCallbackT): Pipeline; - hmset(...args: any[]): Pipeline; - hmget(args: any[], callback?: ResCallbackT): Pipeline; - hmget(...args: any[]): Pipeline; - hincrby(args: any[], callback?: ResCallbackT): Pipeline; - hincrby(...args: any[]): Pipeline; - hincrbyfloat(args: any[], callback?: ResCallbackT): Pipeline; - hincrbyfloat(...args: any[]): Pipeline; - hdel(args: any[], callback?: ResCallbackT): Pipeline; - hdel(...args: any[]): Pipeline; - hlen(args: any[], callback?: ResCallbackT): Pipeline; - hlen(...args: any[]): Pipeline; - hkeys(args: any[], callback?: ResCallbackT): Pipeline; - hkeys(...args: any[]): Pipeline; - hvals(args: any[], callback?: ResCallbackT): Pipeline; - hvals(...args: any[]): Pipeline; - hgetall(args: any[], callback?: ResCallbackT): Pipeline; - hgetall(...args: any[]): Pipeline; - hgetall(key: string, callback?: ResCallbackT): Pipeline; - hexists(args: any[], callback?: ResCallbackT): Pipeline; - hexists(...args: any[]): Pipeline; - incrby(args: any[], callback?: ResCallbackT): Pipeline; - incrby(...args: any[]): Pipeline; - incrbyfloat(args: any[], callback?: ResCallbackT): Pipeline; - incrbyfloat(...args: any[]): Pipeline; - decrby(args: any[], callback?: ResCallbackT): Pipeline; - decrby(...args: any[]): Pipeline; - getset(args: any[], callback?: ResCallbackT): Pipeline; - getset(...args: any[]): Pipeline; - mset(args: any[], callback?: ResCallbackT): Pipeline; - mset(...args: any[]): Pipeline; - msetnx(args: any[], callback?: ResCallbackT): Pipeline; - msetnx(...args: any[]): Pipeline; - randomkey(args: any[], callback?: ResCallbackT): Pipeline; - randomkey(...args: any[]): Pipeline; - select(args: any[], callback?: ResCallbackT): void; - select(...args: any[]): Pipeline; - move(args: any[], callback?: ResCallbackT): Pipeline; - move(...args: any[]): Pipeline; - rename(args: any[], callback?: ResCallbackT): Pipeline; - rename(...args: any[]): Pipeline; - renamenx(args: any[], callback?: ResCallbackT): Pipeline; - renamenx(...args: any[]): Pipeline; - expire(args: any[], callback?: ResCallbackT): Pipeline; - expire(...args: any[]): Pipeline; - pexpire(args: any[], callback?: ResCallbackT): Pipeline; - pexpire(...args: any[]): Pipeline; - expireat(args: any[], callback?: ResCallbackT): Pipeline; - expireat(...args: any[]): Pipeline; - pexpireat(args: any[], callback?: ResCallbackT): Pipeline; - pexpireat(...args: any[]): Pipeline; - keys(args: any[], callback?: ResCallbackT): Pipeline; - keys(...args: any[]): Pipeline; - dbsize(args: any[], callback?: ResCallbackT): Pipeline; - dbsize(...args: any[]): Pipeline; - auth(args: any[], callback?: ResCallbackT): void; - auth(...args: any[]): void; - ping(args: any[], callback?: ResCallbackT): Pipeline; - ping(...args: any[]): Pipeline; - echo(args: any[], callback?: ResCallbackT): Pipeline; - echo(...args: any[]): Pipeline; - save(args: any[], callback?: ResCallbackT): Pipeline; - save(...args: any[]): Pipeline; - bgsave(args: any[], callback?: ResCallbackT): Pipeline; - bgsave(...args: any[]): Pipeline; - bgrewriteaof(args: any[], callback?: ResCallbackT): Pipeline; - bgrewriteaof(...args: any[]): Pipeline; - shutdown(args: any[], callback?: ResCallbackT): Pipeline; - shutdown(...args: any[]): Pipeline; - lastsave(args: any[], callback?: ResCallbackT): Pipeline; - lastsave(...args: any[]): Pipeline; - type(args: any[], callback?: ResCallbackT): Pipeline; - type(...args: any[]): Pipeline; - multi(args: any[], callback?: ResCallbackT): Pipeline; - multi(...args: any[]): Pipeline; - exec(args: any[], callback?: ResCallbackT): Pipeline; - exec(...args: any[]): Pipeline; - discard(args: any[], callback?: ResCallbackT): Pipeline; - discard(...args: any[]): Pipeline; - sync(args: any[], callback?: ResCallbackT): Pipeline; - sync(...args: any[]): Pipeline; - flushdb(args: any[], callback?: ResCallbackT): Pipeline; - flushdb(...args: any[]): Pipeline; - flushall(args: any[], callback?: ResCallbackT): Pipeline; - flushall(...args: any[]): Pipeline; - sort(args: any[], callback?: ResCallbackT): Pipeline; - sort(...args: any[]): Pipeline; - info(args: any[], callback?: ResCallbackT): Pipeline; - info(...args: any[]): Pipeline; - time(args: any[], callback?: ResCallbackT): Pipeline; - time(...args: any[]): Pipeline; - monitor(args: any[], callback?: ResCallbackT): Pipeline; - monitor(...args: any[]): Pipeline; - ttl(args: any[], callback?: ResCallbackT): Pipeline; - ttl(...args: any[]): Pipeline; - persist(args: any[], callback?: ResCallbackT): Pipeline; - persist(...args: any[]): Pipeline; - slaveof(args: any[], callback?: ResCallbackT): Pipeline; - slaveof(...args: any[]): Pipeline; - debug(args: any[], callback?: ResCallbackT): Pipeline; debug(...args: any[]): Pipeline; - config(args: any[], callback?: ResCallbackT): Pipeline; + config(...args: any[]): Pipeline; - subscribe(args: any[], callback?: ResCallbackT): Pipeline; - subscribe(...args: any[]): Pipeline; - unsubscribe(args: any[], callback?: ResCallbackT): Pipeline; - unsubscribe(...args: any[]): Pipeline; - psubscribe(args: any[], callback?: ResCallbackT): Pipeline; - psubscribe(...args: any[]): Pipeline; - punsubscribe(args: any[], callback?: ResCallbackT): Pipeline; - punsubscribe(...args: any[]): Pipeline; - publish(args: any[], callback?: ResCallbackT): Pipeline; - publish(...args: any[]): Pipeline; - watch(args: any[], callback?: ResCallbackT): Pipeline; - watch(...args: any[]): Pipeline; - unwatch(args: any[], callback?: ResCallbackT): Pipeline; - unwatch(...args: any[]): Pipeline; - cluster(args: any[], callback?: ResCallbackT): Pipeline; + + subscribe(channel: string, ...channels: any[]): Pipeline; + + unsubscribe(...channels: string[]): Pipeline; + + psubscribe(pattern: string, ...patterns: string[]): Pipeline; + + punsubscribe(...patterns: string[]): Pipeline; + + publish(channel: string, message: string, callback?: (err: Error, res: number) => void): Pipeline; + + watch(key: string, ...keys: string[]): Pipeline; + + unwatch(callback?: (err: Error, res: string) => void): Pipeline; + cluster(...args: any[]): Pipeline; - restore(args: any[], callback?: ResCallbackT): Pipeline; + restore(...args: any[]): Pipeline; - migrate(args: any[], callback?: ResCallbackT): Pipeline; + migrate(...args: any[]): Pipeline; - dump(args: any[], callback?: ResCallbackT): Pipeline; - dump(...args: any[]): Pipeline; - object(args: any[], callback?: ResCallbackT): Pipeline; - object(...args: any[]): Pipeline; - client(args: any[], callback?: ResCallbackT): Pipeline; + + dump(key: string, callback?: (err: Error, res: string) => void): Pipeline; + + object(subcommand: string, ...args: any[]): Pipeline; + client(...args: any[]): Pipeline; - eval(args: any[], callback?: ResCallbackT): Pipeline; + eval(...args: any[]): Pipeline; - evalsha(args: any[], callback?: ResCallbackT): Pipeline; + evalsha(...args: any[]): Pipeline; - quit(args: any[], callback?: ResCallbackT): Pipeline; - quit(...args: any[]): Pipeline; - scan(...args: any[]): Pipeline; - scan(args: any[], callback?: ResCallbackT): Pipeline; - hscan(...args: any[]): Pipeline; - hscan(args: any[], callback?: ResCallbackT): Pipeline; - zscan(...args: any[]): Pipeline; - zscan(args: any[], callback?: ResCallbackT): Pipeline; + + script(...args: any[]): Pipeline; + + quit(callback?: (err: Error, res: string) => void): Pipeline; + + scan(cursor: number, ...args: any[]): Pipeline; + + hscan(key: string, cursor: number, ...args: any[]): Pipeline; + + zscan(key: string, cursor: number, ...args: any[]): Pipeline; + + pfmerge(destkey: string, sourcekey: string, ...sourcekeys: string[]): Pipeline; + + pfadd(key: string, element: string, ...elements: string[]): Pipeline; + + pfcount(key: string, ...keys: string[]): Pipeline; } interface Cluster extends NodeJS.EventEmitter, Commander { - new (nodes: { host: string; port: number; }[], options?: IORedis.ClusterOptions): Redis; - connect(callback: Function): Promise; + new(nodes: Array<{ host: string; port: number; }>, options?: ClusterOptions): Redis; + connect(callback: () => void): Promise; disconnect(): void; nodes(role: string): Redis[]; } - interface ResCallbackT { - (err: Error, res: R): void; - } - interface RedisOptions { port?: number; host?: string; @@ -678,8 +781,8 @@ declare module IORedis { * When the return value isn't a number, ioredis will stop trying to reconnect. * Fixed in: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/15858 */ - retryStrategy?: (times: number) => number | false; - reconnectOnError?: (error: Error) => boolean; + retryStrategy?(times: number): number | false; + reconnectOnError?(error: Error): boolean; /** * By default, if there is no active connection to the Redis server, commands are added to a queue * and are executed once the connection is "ready" (when enableReadyCheck is true, "ready" means @@ -707,7 +810,7 @@ declare module IORedis { tls?: { ca: Buffer; }; - sentinels?: { host: string; port: number; }[]; + sentinels?: Array<{ host: string; port: number; }>; name?: string; /** * Enable READONLY mode for the connection. Only available for cluster mode. @@ -715,8 +818,9 @@ declare module IORedis { */ readOnly?: boolean; /** - * If you are using the hiredis parser, it's highly recommended to enable this option. Create another instance with dropBufferSupport disabled for other commands that you want to return binary instead of string: - */ + * If you are using the hiredis parser, it's highly recommended to enable this option. + * Create another instance with dropBufferSupport disabled for other commands that you want to return binary instead of string + */ dropBufferSupport?: boolean; /** * Whether to show a friendly error stack. Will decrease the performance significantly. @@ -730,7 +834,7 @@ declare module IORedis { } interface ClusterOptions { - clusterRetryStrategy?: (times: number) => number; + clusterRetryStrategy?(times: number): number; enableOfflineQueue?: boolean; enableReadyCheck?: boolean; scaleReads?: string; diff --git a/types/ioredis/ioredis-tests.ts b/types/ioredis/ioredis-tests.ts index 373fba52c5..2be342c2bd 100644 --- a/types/ioredis/ioredis-tests.ts +++ b/types/ioredis/ioredis-tests.ts @@ -1,15 +1,13 @@ - - import * as Redis from "ioredis"; -var redis = new Redis(); +const redis = new Redis(); redis.set('foo', 'bar'); -redis.get('foo', function(err, result) { +redis.get('foo', (err, result) => { console.log(result); }); // Or using a promise if the last argument isn't a function -redis.get('foo').then(function(result: any) { +redis.get('foo').then((result: any) => { console.log(result); }); @@ -18,24 +16,24 @@ redis.sadd('set', 1, 3, 5, 7); redis.sadd('set', [1, 3, 5, 7]); // All arguments are passed directly to the redis server: -redis.set('key', 100, 'EX', 10); +redis.set('key', '100', 'EX', 10); -new Redis() // Connect to 127.0.0.1:6379 -new Redis(6380) // 127.0.0.1:6380 -new Redis(6379, '192.168.1.1') // 192.168.1.1:6379 -new Redis('/tmp/redis.sock') +new Redis(); // Connect to 127.0.0.1:6379 +new Redis(6380); // 127.0.0.1:6380 +new Redis(6379, '192.168.1.1'); // 192.168.1.1:6379 +new Redis('/tmp/redis.sock'); new Redis({ port: 6379, // Redis port host: '127.0.0.1', // Redis host family: 4, // 4 (IPv4) or 6 (IPv6) password: 'auth', db: 0, - retryStrategy: function() { return false; }, + retryStrategy() { return false; }, showFriendlyErrorStack: true -}) +}); -var pub = new Redis(); -redis.subscribe('news', 'music', function(err: any, count: any) { +const pub = new Redis(); +redis.subscribe('news', 'music', (err: any, count: any) => { // Now we are subscribed to both the 'news' and 'music' channels. // `count` represents the number of channels we are currently subscribed to. @@ -43,7 +41,7 @@ redis.subscribe('news', 'music', function(err: any, count: any) { pub.publish('music', 'Hello again!'); }); -redis.on('message', function(channel: any, message: any) { +redis.on('message', (channel: any, message: any) => { // Receive message Hello world! from channel news // Receive message Hello again! from channel music console.log('Receive message %s from channel %s', message, channel); @@ -51,6 +49,44 @@ redis.on('message', function(channel: any, message: any) { // There's also an event called 'messageBuffer', which is the same as 'message' except // it returns buffers instead of strings. -redis.on('messageBuffer', function(channel: any, message: any) { +redis.on('messageBuffer', (channel: any, message: any) => { // Both `channel` and `message` are buffers. }); + +const pipeline = redis.pipeline(); +pipeline.set('foo', 'bar'); +pipeline.del('cc'); +pipeline.exec((err, results) => { + // `err` is always null, and `results` is an array of responses + // corresponding to the sequence of queued commands. + // Each response follows the format `[err, result]`. +}); + +// You can even chain the commands: +redis.pipeline().set('foo', 'bar').del('cc').exec((err, results) => { +}); + +// `exec` also returns a Promise: +const promise = redis.pipeline().set('foo', 'bar').get('foo').exec(); +promise.then((result) => { + // result === [[null, 'OK'], [null, 'bar']] +}); + +redis.pipeline().set('foo', 'bar').get('foo', (err, result) => { + // result === 'bar' +}).exec((err, result) => { + // result[1][1] === 'bar' +}); + +redis.pipeline([ + ['set', 'foo', 'bar'], + ['get', 'foo'] +]).exec(() => { /* ... */ }); + +Redis.Command.setArgumentTransformer('set', args => { + return args; +}); + +Redis.Command.setReplyTransformer('get', (result: any) => { + return result; +}); diff --git a/types/ioredis/tslint.json b/types/ioredis/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/ioredis/tslint.json +++ b/types/ioredis/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/jasmine-given/index.d.ts b/types/jasmine-given/index.d.ts index 28338d7664..e2b630eccd 100644 --- a/types/jasmine-given/index.d.ts +++ b/types/jasmine-given/index.d.ts @@ -6,5 +6,6 @@ declare function Given(func: (done?: () => void) => void): void; declare function When(func: (done?: () => void) => void): void; declare function Then(func: (done?: () => void) => void): void; +declare function Then(label: string, func: (done?: () => void) => void): void; declare function And(func: (done?: () => void) => void): void; declare function Invariant(func: (done?: () => void) => void): void; diff --git a/types/jasmine-given/jasmine-given-tests.ts b/types/jasmine-given/jasmine-given-tests.ts index e9603e3aaf..7658502b68 100644 --- a/types/jasmine-given/jasmine-given-tests.ts +++ b/types/jasmine-given/jasmine-given-tests.ts @@ -4,6 +4,8 @@ When(() => { }); Then(() => { }); +Then('expected condition 1', () => { }); + And(() => { }); Invariant(() => { }); @@ -20,7 +22,7 @@ When((done) => { } }); -Then((done) => { +Then('expected condition 2', (done) => { if (done) { done(); } diff --git a/types/jasmine/index.d.ts b/types/jasmine/index.d.ts index e4249f116e..c1c15e45de 100644 --- a/types/jasmine/index.d.ts +++ b/types/jasmine/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Jasmine 2.6.0 +// Type definitions for Jasmine 2.8.0 // Project: http://jasmine.github.io/ // Definitions by: Boris Yankov , Theodore Brown , David Pärsson , Gabe Moothart , Lukas Zech // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -90,6 +90,11 @@ declare function expect(actual: ArrayLike): jasmine.ArrayLikeMatchers; */ declare function expect(actual: T): jasmine.Matchers; +/** + * Create an expectation for a spec. + */ +declare function expect(): jasmine.NothingMatcher; + /** * Explicitly mark a spec as failed. * @param e @@ -134,9 +139,10 @@ declare namespace jasmine { function anything(): Any; - function arrayContaining(sample: any[]): ArrayContaining; + function arrayContaining(sample: ArrayLike): ArrayContaining; + function arrayWithExactContents(sample: ArrayLike): ArrayContaining; function objectContaining(sample: Partial): ObjectContaining; - function createSpy(name: string, originalFn?: Function): Spy; + function createSpy(name?: string, originalFn?: Function): Spy; function createSpyObj(baseName: string, methodNames: any[] | {[methodName: string]: any}): any; function createSpyObj(baseName: string, methodNames: any[] | {[methodName: string]: any}): SpyObj; @@ -172,8 +178,8 @@ declare namespace jasmine { [n: number]: T; } - interface ArrayContaining { - new (sample: any[]): any; + interface ArrayContaining { + new (sample: ArrayLike): ArrayLike; asymmetricMatch(other: any): boolean; jasmineToString(): string; @@ -440,18 +446,23 @@ declare namespace jasmine { toThrow(expected?: any): boolean; toThrowError(message?: string | RegExp): boolean; toThrowError(expected?: new (...args: any[]) => Error, message?: string | RegExp): boolean; + not: Matchers; Any: Any; } interface ArrayLikeMatchers extends Matchers> { - toBe(expected: Expected>, expectationFailOutput?: any): boolean; - toEqual(expected: Expected>, expectationFailOutput?: any): boolean; + toBe(expected: Expected> | ArrayContaining, expectationFailOutput?: any): boolean; + toEqual(expected: Expected> | ArrayContaining, expectationFailOutput?: any): boolean; toContain(expected: Expected, expectationFailOutput?: any): boolean; not: ArrayLikeMatchers; } + interface NothingMatcher { + nothing(): void; + } + interface Reporter { reportRunnerStarting(runner: Runner): void; reportRunnerResults(runner: Runner): void; diff --git a/types/jasmine/jasmine-tests.ts b/types/jasmine/jasmine-tests.ts index 2d3a4b3fa9..ab132d3cee 100644 --- a/types/jasmine/jasmine-tests.ts +++ b/types/jasmine/jasmine-tests.ts @@ -33,7 +33,7 @@ describe("Included matchers:", () => { var b = a; expect(a).toBe(b); - expect(a).not.toBe(null); + expect(a).not.toBe(24); }); describe("The 'toEqual' matcher", () => { @@ -54,6 +54,11 @@ describe("Included matchers:", () => { }; expect(foo).toEqual(bar); }); + + it("should work for optional values", () => { + var opt: string | undefined = "s"; + expect(opt as (string | undefined)).toEqual(undefined); + }); }); it("The 'toMatch' matcher is for regular expressions", () => { @@ -83,7 +88,7 @@ describe("Included matchers:", () => { }); it("The 'toBeNull' matcher compares against null", () => { - var a: string = null; + var a: string | null = null; var foo = "foo"; expect(null).toBeNull(); @@ -92,14 +97,14 @@ describe("Included matchers:", () => { }); it("The 'toBeTruthy' matcher is for boolean casting testing", () => { - var a: string, foo = "foo"; + var a: string | undefined, foo = "foo"; expect(foo).toBeTruthy(); expect(a).not.toBeTruthy(); }); it("The 'toBeFalsy' matcher is for boolean casting testing", () => { - var a: string, foo = "foo"; + var a: string | undefined, foo = "foo"; expect(a).toBeFalsy(); expect(foo).not.toBeFalsy(); @@ -665,6 +670,12 @@ describe("Multiple spies, when created manually", () => { }); }); +describe("jasmine.nothing", () => { + it("matches any value", () => { + expect().nothing(); + }); +}); + describe("jasmine.any", () => { it("matches any value", () => { expect({}).toEqual(jasmine.any(Object)); @@ -754,7 +765,7 @@ describe("jasmine.objectContaining", () => { }); describe("jasmine.arrayContaining", () => { - var foo: any; + var foo: Array; beforeEach(() => { foo = [1, 2, 3, 4]; @@ -763,6 +774,9 @@ describe("jasmine.arrayContaining", () => { it("matches arrays with some of the values", () => { expect(foo).toEqual(jasmine.arrayContaining([3, 1])); expect(foo).not.toEqual(jasmine.arrayContaining([6])); + + expect(foo).toBe(jasmine.arrayContaining([3, 1])); + expect(foo).not.toBe(jasmine.arrayContaining([6])); }); describe("when used with a spy", () => { @@ -777,6 +791,33 @@ describe("jasmine.arrayContaining", () => { }); }); +describe("jasmine.arrayWithExactContents", () => { + var foo: Array; + + beforeEach(() => { + foo = [1, 2, 3, 4]; + }); + + it("matches arrays with exactly the same values", () => { + expect(foo).toEqual(jasmine.arrayWithExactContents([1, 2, 3, 4])); + expect(foo).not.toEqual(jasmine.arrayWithExactContents([6])); + + expect(foo).toBe(jasmine.arrayWithExactContents([1, 2, 3, 4])); + expect(foo).not.toBe(jasmine.arrayWithExactContents([6])); + }); + + describe("when used with a spy", () => { + it("is useful when comparing arguments", () => { + var callback = jasmine.createSpy('callback'); + + callback([1, 2, 3, 4]); + + expect(callback).toHaveBeenCalledWith(jasmine.arrayWithExactContents([1, 2, 3, 4])); + expect(callback).not.toHaveBeenCalledWith(jasmine.arrayWithExactContents([5, 2])); + }); + }); +}); + describe("Manually ticking the Jasmine Clock", () => { var timerCallback: any; @@ -990,19 +1031,19 @@ var myReporter: jasmine.CustomReporter = { specDone: (result: jasmine.CustomReporterResult) => { console.log("Spec: " + result.description + " was " + result.status); //tslint:disable-next-line:prefer-for-of - for (var i = 0; i < result.failedExpectations.length; i++) { + for (var i = 0; result.failedExpectations && i < result.failedExpectations.length; i++) { console.log("Failure: " + result.failedExpectations[i].message); console.log("Actual: " + result.failedExpectations[i].actual); console.log("Expected: " + result.failedExpectations[i].expected); console.log(result.failedExpectations[i].stack); } - console.log(result.passedExpectations.length); + console.log(result.passedExpectations && result.passedExpectations.length); }, suiteDone: (result: jasmine.CustomReporterResult) => { console.log('Suite: ' + result.description + ' was ' + result.status); //tslint:disable-next-line:prefer-for-of - for (var i = 0; i < result.failedExpectations.length; i++) { + for (var i = 0; result.failedExpectations && i < result.failedExpectations.length; i++) { console.log('AfterAll ' + result.failedExpectations[i].message); console.log(result.failedExpectations[i].stack); } diff --git a/types/jasmine/tsconfig.json b/types/jasmine/tsconfig.json index 3af72e4d8b..55b83c6d3a 100644 --- a/types/jasmine/tsconfig.json +++ b/types/jasmine/tsconfig.json @@ -11,7 +11,7 @@ ], "noImplicitAny": true, "noImplicitThis": false, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": false, "baseUrl": "../", "typeRoots": [ @@ -21,4 +21,4 @@ "noEmit": true, "forceConsistentCasingInFileNames": true } -} \ No newline at end of file +} diff --git a/types/js-yaml/index.d.ts b/types/js-yaml/index.d.ts index 8f7c0a346d..543391b23b 100644 --- a/types/js-yaml/index.d.ts +++ b/types/js-yaml/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for js-yaml 3.9.1 +// Type definitions for js-yaml 3.10.0 // Project: https://github.com/nodeca/js-yaml // Definitions by: Bart van der Schoor , Sebastian Clausen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -18,8 +18,8 @@ declare namespace jsyaml { public static create(schemas: Schema[] | Schema, types: Type[] | Type): Schema; } - export function safeLoadAll(str: string, iterator: (doc: any) => void, opts?: LoadOptions): any; - export function loadAll(str: string, iterator: (doc: any) => void, opts?: LoadOptions): any; + export function safeLoadAll(str: string, iterator?: (doc: any) => void, opts?: LoadOptions): any; + export function loadAll(str: string, iterator?: (doc: any) => void, opts?: LoadOptions): any; export function safeDump(obj: any, opts?: DumpOptions): string; export function dump(obj: any, opts?: DumpOptions): string; diff --git a/types/js-yaml/js-yaml-tests.ts b/types/js-yaml/js-yaml-tests.ts index aff53acd3c..af932cb934 100644 --- a/types/js-yaml/js-yaml-tests.ts +++ b/types/js-yaml/js-yaml-tests.ts @@ -82,19 +82,23 @@ value = yaml.load(str, loadOpts); // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +value = yaml.safeLoadAll(str); value = yaml.safeLoadAll(str, (doc) => { value = doc; }); value = yaml.safeLoadAll(str, (doc) => { value = doc; }, loadOpts); +value = yaml.safeLoadAll(str, undefined, loadOpts); +value = yaml.loadAll(str); value = yaml.loadAll(str, (doc) => { value = doc; }); value = yaml.loadAll(str, (doc) => { value = doc; }, loadOpts); +value = yaml.loadAll(str, undefined, loadOpts); // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- diff --git a/types/jws/index.d.ts b/types/jws/index.d.ts new file mode 100644 index 0000000000..f384fadefc --- /dev/null +++ b/types/jws/index.d.ts @@ -0,0 +1,152 @@ +// Type definitions for jws 3.1 +// Project: https://github.com/brianloveswords/node-jws +// Definitions by: Justin Beckwith +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as events from 'events'; +import * as stream from 'stream'; + +/** + * (Synchronous) Return a JSON Web Signature for a header + * and a payload. + */ +export function sign(options: SignOptions): string; + +/** + * (Synchronous) Returns true or false for whether a signature + * matches a secret or key. + * @param signature JWS Signature + * @param algorithm Algorithm + * @param secretOrKey string or buffer containing either the secret + * for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA + */ +export function verify(signature: string, algorithm: Algorithm, secretOrKey: string|Buffer): boolean; + +/** + * (Synchronous) Returns the decoded header, decoded payload, + * and signature parts of the JWS Signature. + */ +export function decode(signature: string): Signature; + +/** + * Returns a new SignStream object. + */ +export function createSign(options: SignOptions): SignStream; + +/** + * Returns a new VerifyStream object. + */ +export function createVerify(options?: VerifyOptions): VerifyStream; + +/** + * A Readable Stream that emits a single data event, the + * calculated signature, when done. + */ +export interface SignStream extends stream.Readable { + /** + * A Writable Stream that expects the JWS payload. Do not + * use if you passed a payload option to the constructor. + * + * Example: payloadStream.pipe(signer.payload); + */ + payload: stream.Writable; + + /** + * Can be a string, Buffer, Readable stream, or object. + */ + secret: any; + + /** + * Can be a string, Buffer, Readable stream, or object. + */ + key: any; + + /** + * A Writable Stream. Expects the JWS secret for HMAC, or + * the privateKey for ECDSA and RSA. Do not use if you + * passed a secret or key option to the constructor. + * + * Example: privateKeyStream.pipe(signer.privateKey); + */ + privateKey: any; +} + +/** + * This is a Readable Stream that emits a single data event, + * the result of whether or not that signature was valid. + */ +export interface VerifyStream extends events.EventEmitter { + /** + * A Writable Stream that expects a JWS Signature. Do not + * use if you passed a signature option to the constructor. + */ + signature: stream.Writable; + + /** + * Secret. Can be a string, buffer, or object. + */ + secret: any; + + /** + * Key. Can be a string, buffer, or object. + */ + key: any; + + /** + * A Writable Stream that expects a public key or secret. + * Do not use if you passed a key or secret option to the + * constructor. + */ + publicKey: stream.Writable; +} + +export interface Signature { + header: Header; + payload: any; + signature: string; +} + +export interface SignOptions { + header: Header; + + /** + * Can be a string, Buffer, Readable stream, or object. + */ + payload?: any; + + /** + * Can be a string, Buffer, Readable stream, or object. + */ + key?: any; + + /** + * Can be a string, Buffer, Readable stream, or object. + */ + secret?: any; + + /** + * Can be a string, Buffer, Readable stream, or object. + */ + privateKey?: any; + + encoding?: string|Buffer|stream.Readable; +} + +export interface VerifyOptions { + signature?: string|Buffer|stream.Readable; + algorithm?: Algorithm|Buffer|stream.Readable; + key?: string|stream.Readable|Buffer; + secret?: string|stream.Readable|Buffer; + publicKey?: string|stream.Readable|Buffer; + encoding?: string|Buffer|stream.Readable; +} + +export type Algorithm = 'HS256' | 'HS384' | 'HS512' | 'RS256' | + 'RS384' | 'RS512' | 'ES256' | 'ES384' | + 'ES512' | 'none'; + +export interface Header { + alg: Algorithm; +} diff --git a/types/jws/jws-tests.ts b/types/jws/jws-tests.ts new file mode 100644 index 0000000000..d5271b24ca --- /dev/null +++ b/types/jws/jws-tests.ts @@ -0,0 +1,51 @@ +/** + * Tests are built by copying samples from the github repository: + * https://github.com/brianloveswords/node-jws + */ + +import * as jws from 'jws'; +import * as fs from "fs"; + +// set up mock objects +const fakeStream = fs.createReadStream('fakefile'); +const privateKeyStream = fakeStream; +const payloadStream = fakeStream; +const pubKeyStream = fakeStream; +const sigStream = fakeStream; + +// jws.sign +const signature = jws.sign({ + header: { alg: 'HS256' }, + payload: 'h. jon benjamin', + secret: 'has a van', +}); + +// jws.decode +const message = jws.decode('djfakdid'); + +// jws.createSign +jws.createSign({ + header: { alg: 'RS256' }, + privateKey: privateKeyStream, + payload: payloadStream, +}).on('done', signature => {}); + +// jws.createSign no params +const signer = jws.createSign({ + header: { alg: 'RS256' }, +}); +privateKeyStream.pipe(signer.privateKey); +payloadStream.pipe(signer.payload); +signer.on('done', signature => {}); + +// jws.createVerify +jws.createVerify({ + publicKey: pubKeyStream, + signature: sigStream, +}).on('done', (verified, obj) => {}); + +// jws.createVerify with no options +const verifier = jws.createVerify(); +pubKeyStream.pipe(verifier.publicKey); +sigStream.pipe(verifier.signature); +verifier.on('done', (verified, obj) => {}); diff --git a/types/jws/tsconfig.json b/types/jws/tsconfig.json new file mode 100644 index 0000000000..a8a2f625d3 --- /dev/null +++ b/types/jws/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jws-tests.ts" + ] +} diff --git a/types/jws/tslint.json b/types/jws/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jws/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index 974c3eb0a4..aaee0b27f7 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Knex.js // Project: https://github.com/tgriesser/knex -// Definitions by: Qubo , Baronfel +// Definitions by: Qubo , Baronfel , Pablo Rodríguez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -8,7 +8,7 @@ import events = require("events"); import stream = require ("stream"); -import Promise = require("bluebird"); +import Bluebird = require("bluebird"); type Callback = Function; type Client = Function; @@ -22,9 +22,9 @@ interface Knex extends Knex.QueryInterface { __knex__: string; raw: Knex.RawBuilder; - transaction(transactionScope: (trx: Knex.Transaction) => any): Promise; + transaction(transactionScope: (trx: Knex.Transaction) => Promise | Bluebird | void): Bluebird; destroy(callback: Function): void; - destroy(): Promise; + destroy(): Bluebird; batchInsert(tableName : TableName, data: any[], chunkSize : number) : Knex.QueryBuilder; schema: Knex.SchemaBuilder; queryBuilder(): Knex.QueryBuilder; @@ -351,7 +351,7 @@ declare namespace Knex { and: QueryBuilder; //TODO: Promise? - columnInfo(column?: string): Promise; + columnInfo(column?: string): Bluebird; forUpdate(): QueryBuilder; forShare(): QueryBuilder; @@ -372,18 +372,18 @@ declare namespace Knex { // Chainable interface // - interface ChainableInterface extends Promise { + interface ChainableInterface extends Bluebird { toQuery(): string; options(options: any): QueryBuilder; - stream(callback: (readable: stream.PassThrough) => any): Promise; + stream(callback: (readable: stream.PassThrough) => any): Bluebird; stream(options?: { [key: string]: any }): stream.PassThrough; - stream(options: { [key: string]: any }, callback: (readable: stream.PassThrough) => any): Promise; + stream(options: { [key: string]: any }, callback: (readable: stream.PassThrough) => any): Bluebird; pipe(writable: any): stream.PassThrough; exec(callback: Function): QueryBuilder; } interface Transaction extends Knex { - savepoint(transactionScope: (trx: Transaction) => any): Promise; + savepoint(transactionScope: (trx: Transaction) => any): Bluebird; commit(value?: any): QueryBuilder; rollback(error?: any): QueryBuilder; } @@ -392,14 +392,14 @@ declare namespace Knex { // Schema builder // - interface SchemaBuilder extends Promise { + interface SchemaBuilder extends Bluebird { createTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; createTableIfNotExists(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; - renameTable(oldTableName: string, newTableName: string): Promise; + renameTable(oldTableName: string, newTableName: string): Bluebird; dropTable(tableName: string): SchemaBuilder; - hasTable(tableName: string): Promise; - hasColumn(tableName: string, columnName: string): Promise; - table(tableName: string, callback: (tableBuilder: AlterTableBuilder) => any): Promise; + hasTable(tableName: string): Bluebird; + hasColumn(tableName: string, columnName: string): Bluebird; + table(tableName: string, callback: (tableBuilder: AlterTableBuilder) => any): Bluebird; dropTableIfExists(tableName: string): SchemaBuilder; raw(statement: string): SchemaBuilder; withSchema(schemaName: string): SchemaBuilder; @@ -666,11 +666,11 @@ declare namespace Knex { } interface Migrator { - make(name: string, config?: MigratorConfig): Promise; - latest(config?: MigratorConfig): Promise; - rollback(config?: MigratorConfig): Promise; - status(config?: MigratorConfig): Promise; - currentVersion(config?: MigratorConfig): Promise; + make(name: string, config?: MigratorConfig): Bluebird; + latest(config?: MigratorConfig): Bluebird; + rollback(config?: MigratorConfig): Bluebird; + status(config?: MigratorConfig): Bluebird; + currentVersion(config?: MigratorConfig): Bluebird; } interface FunctionHelper { diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index 95d28b1b2b..dec1bf055f 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -520,7 +520,6 @@ knex.transaction(function(trx) { }) .then(trx.commit) .catch(trx.rollback); - }).then(function() { console.log('Transaction complete.'); }).catch(function(err) { @@ -537,7 +536,17 @@ knex.transaction(function(trx) { .transacting(trx) .forShare() .select('*') -}); +}) + +const transactionReturnValue = knex.transaction(function(trx) { + return knex("table") + .insert({ foo: "bar" }) + .returning(["id"]) + .then(function(result) { return result[0].id as number }) +}) + +// Tests that the transaction has kept the type of its return value by referencing a method of number +transactionReturnValue.then(value => value.toExponential); knex('users').count('active'); @@ -616,7 +625,7 @@ knex.transaction(function(trx) { }); // Using trx as a transaction object: -knex.transaction(function(trx) { +knex.transaction<{ length: number }>(function(trx) { trx.raw(''); diff --git a/types/knockout-amd-helpers/index.d.ts b/types/knockout-amd-helpers/index.d.ts index d12c8d9a8f..6f3a5493e1 100644 --- a/types/knockout-amd-helpers/index.d.ts +++ b/types/knockout-amd-helpers/index.d.ts @@ -2,10 +2,10 @@ // Project: https://github.com/rniemeyer/knockout-amd-helpers // Definitions by: David Sichau // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// - interface KnockoutAMDModule { baseDir: string; initializer: string; diff --git a/types/knockout-secure-binding/index.d.ts b/types/knockout-secure-binding/index.d.ts index 84a432738b..f7c7500cff 100644 --- a/types/knockout-secure-binding/index.d.ts +++ b/types/knockout-secure-binding/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/brianmhunt/knockout-secure-binding // Definitions by: Pine Mizune // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// @@ -28,4 +29,4 @@ declare module "knockout-secure-binding" { }; export = klass; -} \ No newline at end of file +} diff --git a/types/knockout-transformations/index.d.ts b/types/knockout-transformations/index.d.ts index 958eb99fb6..5fab318c1b 100644 --- a/types/knockout-transformations/index.d.ts +++ b/types/knockout-transformations/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/One-com/knockout-transformations // Definitions by: John Reilly , Wim Looman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.deferred.updates/index.d.ts b/types/knockout.deferred.updates/index.d.ts index 89fb752089..c02f371277 100644 --- a/types/knockout.deferred.updates/index.d.ts +++ b/types/knockout.deferred.updates/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/mbest/knockout-deferred-updates // Definitions by: Sebastián Galiano // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// @@ -42,4 +43,4 @@ interface KnockoutUtils { // Deferred extender interface KnockoutExtenders { deferred(target: any, value: boolean): any; -} \ No newline at end of file +} diff --git a/types/knockout.editables/index.d.ts b/types/knockout.editables/index.d.ts index 4a4ed59d3b..5167287e7e 100644 --- a/types/knockout.editables/index.d.ts +++ b/types/knockout.editables/index.d.ts @@ -2,6 +2,7 @@ // Project: http://romanych.github.com/ko.editables/ // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.es5/index.d.ts b/types/knockout.es5/index.d.ts index ce41db0d73..0ae2526c25 100644 --- a/types/knockout.es5/index.d.ts +++ b/types/knockout.es5/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/SteveSanderson/knockout-es5 // Definitions by: Sebastián Galiano // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.mapper/index.d.ts b/types/knockout.mapper/index.d.ts index 747a3d1f4a..d77f3e8f22 100644 --- a/types/knockout.mapper/index.d.ts +++ b/types/knockout.mapper/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/LucasLorentz/knockout.mapper // Definitions by: Brandon Meyer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.mapping/index.d.ts b/types/knockout.mapping/index.d.ts index 23f7aae8b5..e6d5fe2f6c 100644 --- a/types/knockout.mapping/index.d.ts +++ b/types/knockout.mapping/index.d.ts @@ -1,7 +1,9 @@ // Type definitions for Knockout.Mapping 2.0 // Project: https://github.com/SteveSanderson/knockout.mapping -// Definitions by: Boris Yankov +// Definitions by: Boris Yankov , +// Mathias Lorenzen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// @@ -33,17 +35,25 @@ declare global { update?: (options: KnockoutMappingUpdateOptions) => void; key?: (data: any) => any; } + + type KnockoutObservableType = { + [P in keyof T]: KnockoutObservable; + }; interface KnockoutMapping { isMapped(viewModel: any): boolean; - fromJS(jsObject: any): any; - fromJS(jsObject: any, targetOrOptions: any): any; - fromJS(jsObject: any, inputOptions: any, target: any): any; + fromJS(jsObject: T[]): KnockoutObservableType[]; + fromJS(jsObject: T[], targetOrOptions: any): KnockoutObservableType[]; + fromJS(jsObject: T[], inputOptions: any, target: any): KnockoutObservableType[]; + fromJS(jsObject: T): KnockoutObservableType; + fromJS(jsObject: T, targetOrOptions: any): KnockoutObservableType; + fromJS(jsObject: T, inputOptions: any, target: any): KnockoutObservableType; fromJSON(jsonString: string): any; fromJSON(jsonString: string, targetOrOptions: any): any; fromJSON(jsonString: string, inputOptions: any, target: any): any; - toJS(rootObject: any, options?: KnockoutMappingOptions): any; - toJSON(rootObject: any, options?: KnockoutMappingOptions): any; + toJS(rootObject: KnockoutObservableArray|T, options?: KnockoutMappingOptions): T[]; + toJS(rootObject: KnockoutObservableType|T, options?: KnockoutMappingOptions): T; + toJSON(rootObject: any, options?: KnockoutMappingOptions): string; defaultOptions(): KnockoutMappingOptions; resetDefaultOptions(): void; getType(x: any): any; diff --git a/types/knockout.postbox/index.d.ts b/types/knockout.postbox/index.d.ts index 56afa3a2b6..d7e967bcb9 100644 --- a/types/knockout.postbox/index.d.ts +++ b/types/knockout.postbox/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/rniemeyer/knockout-postbox // Definitions by: Judah Gabriel Himango // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.projections/index.d.ts b/types/knockout.projections/index.d.ts index aae8b55f57..bed2ac82ca 100644 --- a/types/knockout.projections/index.d.ts +++ b/types/knockout.projections/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/stevesanderson/knockout-projections // Definitions by: John Reilly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.punches/index.d.ts b/types/knockout.punches/index.d.ts index aec2860bd9..c378d68c37 100644 --- a/types/knockout.punches/index.d.ts +++ b/types/knockout.punches/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/mbest/knockout.punches // Definitions by: Stephen Lautier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.rx/index.d.ts b/types/knockout.rx/index.d.ts index 82a5473f1c..fea2c5175b 100644 --- a/types/knockout.rx/index.d.ts +++ b/types/knockout.rx/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/Igorbek/knockout.rx // Definitions by: Igor Oleinikov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// /// diff --git a/types/knockout.validation/index.d.ts b/types/knockout.validation/index.d.ts index 8b0300bd7f..e302ee6279 100644 --- a/types/knockout.validation/index.d.ts +++ b/types/knockout.validation/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/ericmbarnard/Knockout-Validation // Definitions by: Dan Ludwig // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.viewmodel/index.d.ts b/types/knockout.viewmodel/index.d.ts index 5e57afb449..2ea6815531 100644 --- a/types/knockout.viewmodel/index.d.ts +++ b/types/knockout.viewmodel/index.d.ts @@ -2,6 +2,7 @@ // Project: http://coderenaissance.github.com/knockout.viewmodel/ // Definitions by: Oisin Grehan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout/index.d.ts b/types/knockout/index.d.ts index 4ef3bc8739..8d035ed8d2 100644 --- a/types/knockout/index.d.ts +++ b/types/knockout/index.d.ts @@ -1,12 +1,13 @@ // Type definitions for Knockout v3.4.0 // Project: http://knockoutjs.com -// Definitions by: Boris Yankov -// Igor Oleinikov -// Clément Bourgeois -// Matt Brooks -// Benjamin Eckardt +// Definitions by: Boris Yankov , +// Igor Oleinikov , +// Clément Bourgeois , +// Matt Brooks , +// Benjamin Eckardt , +// Mathias Lorenzen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.3 interface KnockoutExtensionFunctions { [key: string]: any; diff --git a/types/knockout/test/index.ts b/types/knockout/test/index.ts index e3f7820f94..9913b64fa8 100644 --- a/types/knockout/test/index.ts +++ b/types/knockout/test/index.ts @@ -484,8 +484,8 @@ function test_mappingplugin() { ko.mapping.fromJS(data, {}, this); var alice, aliceMappingOptions, bob, bobMappingOptions; - var viewModel = ko.mapping.fromJS(alice, aliceMappingOptions); - ko.mapping.fromJS(bob, bobMappingOptions, viewModel); + var aliceViewModel = ko.mapping.fromJS(alice, aliceMappingOptions); + ko.mapping.fromJS(bob, bobMappingOptions, aliceViewModel); var obj; var result = ko.mapping.fromJS(obj, { diff --git a/types/koa-router/index.d.ts b/types/koa-router/index.d.ts index ba7815ef54..b543a764b0 100644 --- a/types/koa-router/index.d.ts +++ b/types/koa-router/index.d.ts @@ -34,15 +34,25 @@ declare module Router { export interface IRouterOptions { /** - * Router prefixes + * Prefix for all routes. */ prefix?: string; /** - * HTTP verbs + * Methods which should be supported by the router. */ methods?: string[]; routerPath?: string; + /** + * Whether or not routing should be case-sensitive. + */ sensitive?: boolean; + /** + * Whether or not routes should matched strictly. + * + * If strict matching is enabled, the trailing slash is taken into + * account when matching routes. + */ + strict?: boolean; } export interface IRouterContext extends Koa.Context { diff --git a/types/kolite/knockout.activity.d.ts b/types/kolite/knockout.activity.d.ts index 8a1f1a0fac..8022e18cff 100644 --- a/types/kolite/knockout.activity.d.ts +++ b/types/kolite/knockout.activity.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/CodeSeven/kolite // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.3 /// /// diff --git a/types/kolite/knockout.command.d.ts b/types/kolite/knockout.command.d.ts index ff509dbd16..786bbcfaae 100644 --- a/types/kolite/knockout.command.d.ts +++ b/types/kolite/knockout.command.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/CodeSeven/kolite // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.3 /// /// diff --git a/types/kolite/knockout.dirtyFlag.d.ts b/types/kolite/knockout.dirtyFlag.d.ts index 1c63ce8b7d..2f63a110e0 100644 --- a/types/kolite/knockout.dirtyFlag.d.ts +++ b/types/kolite/knockout.dirtyFlag.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/CodeSeven/kolite // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.3 /// /// diff --git a/types/mithril-global/index.d.ts b/types/mithril-global/index.d.ts index 4dd8240303..fe1814e4ed 100644 --- a/types/mithril-global/index.d.ts +++ b/types/mithril-global/index.d.ts @@ -2,7 +2,7 @@ // Project: https://mithril.js.org/ // Definitions by: Mike Linkovich , Isiah Meadows // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 // Global Mithril types diff --git a/types/mithril/index.d.ts b/types/mithril/index.d.ts index 32a76fca0e..79706617e8 100644 --- a/types/mithril/index.d.ts +++ b/types/mithril/index.d.ts @@ -2,7 +2,7 @@ // Project: https://mithril.js.org/ // Definitions by: Mike Linkovich , András Parditka , Isiah Meadows // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 /** Manually triggers a redraw of mounted components. */ declare function redraw(): void; @@ -63,7 +63,7 @@ declare namespace Mithril { trust(html: string): Vnode; } - interface RouteResolver { + interface RouteResolver { /** The onmatch hook is called when the router needs to find a component to render. */ onmatch?(this: this, args: Attrs, requestedPath: string): ComponentTypes | Promise | void; /** The render method is called on every redraw for a matching route. */ @@ -173,7 +173,7 @@ declare namespace Mithril { type ChildArrayOrPrimitive = ChildArray | string | number | boolean; /** Virtual DOM nodes, or vnodes, are Javascript objects that represent an element (or parts of the DOM). */ - interface Vnode> { + interface Vnode = Lifecycle> { /** The nodeName of a DOM element. It may also be the string [ if a vnode is a fragment, # if it's a text vnode, or < if it's a trusted HTML vnode. Additionally, it may be a component. */ tag: string | ComponentTypes; /** A hashmap of DOM attributes, events, properties and lifecycle methods. */ @@ -194,23 +194,23 @@ declare namespace Mithril { // In some lifecycle methods, Vnode will have a dom property // and possibly a domSize property. - interface VnodeDOM> extends Vnode { + interface VnodeDOM = Lifecycle> extends Vnode { /** Points to the element that corresponds to the vnode. */ dom: Element; /** This defines the number of DOM elements that the vnode represents (starting from the element referenced by the dom property). */ domSize?: number; } - interface CVnode extends Vnode> { } + interface CVnode extends Vnode> { } - interface CVnodeDOM extends VnodeDOM> { } + interface CVnodeDOM extends VnodeDOM> { } /** * Components are a mechanism to encapsulate parts of a view to make code easier to organize and/or reuse. * Any Javascript object that has a view method can be used as a Mithril component. * Components can be consumed via the m() utility. */ - interface Component> extends Lifecycle { + interface Component = Lifecycle> extends Lifecycle { /** Creates a view out of virtual elements. */ view(this: State, vnode: Vnode): Children | null | void; } @@ -220,7 +220,7 @@ declare namespace Mithril { * Any class that implements a view method can be used as a Mithril component. * Components can be consumed via the m() utility. */ - interface ClassComponent extends Lifecycle> { + interface ClassComponent extends Lifecycle> { /** The oninit hook is called before a vnode is touched by the virtual DOM engine. */ oninit?(vnode: Vnode): any; /** The oncreate hook is called after a DOM element is created and attached to the document. */ @@ -242,16 +242,16 @@ declare namespace Mithril { * Any function that returns an object with a view method can be used as a Mithril component. * Components can be consumed via the m() utility. */ - type FactoryComponent = (vnode: Vnode) => Component; + type FactoryComponent = (vnode: Vnode) => Component; /** * Components are a mechanism to encapsulate parts of a view to make code easier to organize and/or reuse. * Any Javascript object that has a view method is a Mithril component. Components can be consumed via the m() utility. */ - type Comp> = Component & State; + type Comp = Lifecycle> = Component & State; /** Components are a mechanism to encapsulate parts of a view to make code easier to organize and/or reuse. Components can be consumed via the m() utility. */ - type ComponentTypes = Component | { new (vnode: CVnode): ClassComponent } | FactoryComponent; + type ComponentTypes = Lifecycle> = Component | { new (vnode: CVnode): ClassComponent } | FactoryComponent; /** This represents the attributes available for configuring virtual elements, beyond the applicable DOM attributes. */ interface Attributes extends Lifecycle { diff --git a/types/mithril/test/test-class-component.ts b/types/mithril/test/test-class-component.ts index 11e9fa3279..ceaf9d08d3 100644 --- a/types/mithril/test/test-class-component.ts +++ b/types/mithril/test/test-class-component.ts @@ -5,8 +5,8 @@ import { ClassComponent, Vnode, CVnode, CVnodeDOM } from 'mithril'; // 0. // Simplest component example - no attrs or state. // -class Comp0 implements ClassComponent<{}> { - constructor(vnode: CVnode<{}>) { +class Comp0 implements ClassComponent { + constructor(vnode: CVnode) { } view() { return m('span', "Test"); @@ -23,12 +23,12 @@ m.mount(document.getElementById('comp0')!, null); // 1. // Simple example with lifecycle methods. // -class Comp1 implements ClassComponent<{}> { - oninit(vnode: CVnode<{}>) { +class Comp1 implements ClassComponent { + oninit(vnode: CVnode) { } - oncreate({dom}: CVnodeDOM<{}>) { + oncreate({dom}: CVnodeDOM) { } - view(vnode: CVnode<{}>) { + view(vnode: CVnode) { return m('span', "Test"); } } @@ -130,7 +130,7 @@ export interface Attrs { export default class MyComponent implements ClassComponent { count = 0; - view({attrs}: Vnode) { + view({attrs}: CVnode) { return m('span', `name: ${attrs.name}, count: ${this.count}`); } } diff --git a/types/mithril/test/test-component.ts b/types/mithril/test/test-component.ts index a8fecaa28f..781cdedbe3 100644 --- a/types/mithril/test/test-component.ts +++ b/types/mithril/test/test-component.ts @@ -22,7 +22,7 @@ m.mount(document.getElementById('comp0')!, null); // 1. // Simple example. Vnode type for component methods is inferred. // -const comp1: Component<{}, {}> = { +const comp1: Component = { oncreate({dom}) { // vnode.dom type inferred }, @@ -40,7 +40,7 @@ interface Comp2Attrs { description: string; } -const comp2: Component = { +const comp2: Component = { view({attrs: {title, description}}) { // Comp2Attrs type is inferred return [m('h2', title), m('p', description)]; } @@ -78,7 +78,7 @@ m(comp2, {title: '', description: '', foo: ''}); // Uses comp2 with typed attrs and makes use of `onremove` // lifecycle method. // -const comp3: Component<{pageHead: string}, {}> = { +const comp3: Component<{pageHead: string}> = { oncreate({dom}) { // Can do stuff with dom }, diff --git a/types/mithril/test/test-factory-component.ts b/types/mithril/test/test-factory-component.ts index be3fdb60f1..ba438a3789 100644 --- a/types/mithril/test/test-factory-component.ts +++ b/types/mithril/test/test-factory-component.ts @@ -23,7 +23,7 @@ m.mount(document.getElementById('comp0')!, null); // 1. // Simple example. Vnode type for component methods is inferred. // -function comp1(): Component<{}, {}> { +function comp1(): Component { return { oncreate({dom}) { // vnode.dom type inferred @@ -89,7 +89,7 @@ interface Comp4Attrs { name: string; } -function comp4(): Component { +function comp4(): Component { let count = 0; function add(num: number) { @@ -165,7 +165,7 @@ interface Attrs { name: string; } -export default (): Component => { +export default (): Component => { const count = 0; return { view({attrs}) { diff --git a/types/mithril/test/test-fragment.ts b/types/mithril/test/test-fragment.ts index 097831d3ed..5e60952741 100644 --- a/types/mithril/test/test-fragment.ts +++ b/types/mithril/test/test-fragment.ts @@ -1,5 +1,5 @@ import * as m from 'mithril'; -import { Vnode } from 'mithril/'; +import { Vnode } from 'mithril'; import * as h from 'mithril/hyperscript'; const vnode = m.fragment({id: 'abc'}, ['test']); @@ -9,7 +9,7 @@ m.fragment({}, ['Test', 123]); m.fragment( { id: 'abc', - oninit: (vnode: Vnode) => { + oninit: (vnode) => { console.log('oninit'); } }, diff --git a/types/mithril/test/test-route.ts b/types/mithril/test/test-route.ts index 70428fde88..523780261d 100644 --- a/types/mithril/test/test-route.ts +++ b/types/mithril/test/test-route.ts @@ -8,7 +8,7 @@ const component1 = { } }; -const component2: Component<{title: string}, {}> = { +const component2: Component<{title: string}> = { view({attrs: {title}}) { return h('h1', title); } @@ -34,7 +34,7 @@ const component3: Comp = { }; class Component4 implements ClassComponent { - view({attrs}: Vnode) { + view({attrs}: Vnode) { return h('p', 'id: ' + attrs.id); } } @@ -47,8 +47,12 @@ const component5: FactoryComponent = () => { }; }; -// RouteResolver example using Attrs type and this context -const routeResolver: RouteResolver & {message: string} = { +interface RRState { + message: string; +} + +// Stateful RouteResolver example using Attrs type and this context +const routeResolver: RouteResolver & RRState = { message: "", onmatch(attrs, path) { this.message = "Match"; diff --git a/types/mochaccino/index.d.ts b/types/mochaccino/index.d.ts new file mode 100644 index 0000000000..b230218ee9 --- /dev/null +++ b/types/mochaccino/index.d.ts @@ -0,0 +1,42 @@ +// Type definitions for mochaccino 1.2 +// Project: https://github.com/pawelgalazka/mochaccino#readme +// Definitions by: Thomas-P +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 +import * as Sinon from "sinon"; +export interface Expect { + not: Expect; + toBe(arg: any): void; + toContain(arg: any): void; + toEqual(arg: any): void; + toHaveBeenCalled(): void; + toHaveBeenCalledWith(...arg: any[]): void; + toHaveBeenCalledTimes(callCount: number): void; + toBeDefined(): void; + toBeUndefined(): void; + toBeNull(): void; + toBeTruthy(): void; + toBeFalsy(): void; + toBeLessThan(other: number): void; + toBeGreaterThan(other: number): void; + toThrow(): void; + toThrowError(errType: any): void; + toMatch(matchExpression: any): void; +} +export interface SpyProxy { + and: SpyProxy; + spyProxy: true; + getSubject: () => Sinon.SinonStub; + callThrough: () => void; + returnValue: (obj: any) => void; + callFake: (fake: (...args: any[]) => any) => void; +} +export interface Dom { + exposedProperties: ['window', 'navigator', 'document']; + create: () => void; + destroy: () => void; + clear: () => void; +} +export function expect(value: any): Expect; +export function spy(...config: any[]): (...args: any[]) => SpyProxy; +export const dom: Dom; diff --git a/types/mochaccino/mochaccino-tests.ts b/types/mochaccino/mochaccino-tests.ts new file mode 100644 index 0000000000..c63634e64c --- /dev/null +++ b/types/mochaccino/mochaccino-tests.ts @@ -0,0 +1,66 @@ +import { dom, expect, spy } from 'mochaccino'; +/** + * spy test + * + */ +const obj = { + funcName: (): any => { + } +}; +let s = spy(); +s(1, 2); +expect(s).toHaveBeenCalledWith(1, 2); +spy(obj, 'funcName'); +obj.funcName(); +expect(obj.funcName).toHaveBeenCalled(); +/***********************/ +s = spy(); +s(); +expect(s).toHaveBeenCalled(); +/***********************/ +s(obj, 'funcName').and.callFake(() => { + return 123; +}); +expect(obj.funcName()).toEqual(123); +spy(obj, 'funcName'); + +expect(obj.funcName).toHaveBeenCalled(); +/***********************/ +s(obj, 'funcName').and.callThrough(); +/***********************/ +s(obj, 'funcName').and.returnValue(5); +/***********************/ +/** + * dom test + */ +dom.create(); +dom.destroy(); +dom.clear(); +/** + * expect test + * + */ +const a = 1; +const b = true; +const c = 2; +const f = () => { +}; +const ErrorType = new Error(); +const regexp = /123/; +expect(true).toBeTruthy(); +expect(a).toBe(b); +expect(a).toEqual(b); +expect(a).toBeTruthy(); +expect(a).toBeFalsy(); +expect(a).toBeDefined(); +expect(a).toBeUndefined(); +expect(a).toBeNull(); +expect(a).toBeLessThan(c); +expect(a).toBeGreaterThan(c); +expect([1, 2]).toContain(1); +expect(f).toThrow(); +expect(f).toThrowError(ErrorType); +expect(s).toMatch(regexp); +expect(s).toHaveBeenCalled(); +expect(s).toHaveBeenCalledWith(1, '23'); +expect(s).toHaveBeenCalledTimes(55); diff --git a/types/mochaccino/tsconfig.json b/types/mochaccino/tsconfig.json new file mode 100644 index 0000000000..166b3f4203 --- /dev/null +++ b/types/mochaccino/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mochaccino-tests.ts" + ] +} diff --git a/types/mochaccino/tslint.json b/types/mochaccino/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mochaccino/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mock-require/index.d.ts b/types/mock-require/index.d.ts index da5db1c07c..75076ec739 100644 --- a/types/mock-require/index.d.ts +++ b/types/mock-require/index.d.ts @@ -1,31 +1,21 @@ -// Type definitions for mock-require v1.3.0 +// Type definitions for mock-require 2.0 // Project: https://github.com/boblauer/mock-require -// Definitions by: Daniel Pereira +// Definitions by: Giorgio Delgado // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 /// -/** Simple, intuitive mocking of Node.js modules. */ +type StubFunction = (...params: any[]) => any; +type Stub = object | StubFunction; + interface Mock { - /** - * @param {string} path The module you that you want to mock. - * @param {any} mockExport The function or object you want to be returned from require, instead of the path module's exports, or the module you want to be returned from require, instead of the path module's export. - */ - (path: string, mockExport: any | Function | string): void; - - /** - * @param {string} path The module you that you want to stop mocking. - */ + (path: string, mockExport: string | Stub): void; stop(path: string): void; - - /** This function can be used to remove all registered mocks without the need to remove them individually using mock.stop(). */ stopAll(): void; - - /** - * @param {string} path The file whose cache you want to refresh. - */ - reRequire(path: string): void; + reRequire(path: string): any; } -declare const myModule: Mock; -export = myModule; +declare var mock: Mock; + +export = mock; diff --git a/types/mock-require/mock-require-tests.ts b/types/mock-require/mock-require-tests.ts index 41052e2afc..2131bc56de 100644 --- a/types/mock-require/mock-require-tests.ts +++ b/types/mock-require/mock-require-tests.ts @@ -1,10 +1,12 @@ import mock = require('mock-require'); +const request = () => { + console.log('http.request called'); +}; + function testMock() { mock('http', { - request: function () { - console.log('http.request called'); - } + request }); const http = require('http'); @@ -42,4 +44,4 @@ function testReRequire() { let fileToTest = require('./fileToTest'); mock('fs', {}); // fileToTest is still using the unmocked fs module fileToTest = mock.reRequire('./fileToTest'); // fileToTest is now using your mock -} \ No newline at end of file +} diff --git a/types/mock-require/tsconfig.json b/types/mock-require/tsconfig.json index 2f5ec713da..1f6be404c6 100644 --- a/types/mock-require/tsconfig.json +++ b/types/mock-require/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 7e45ea835a..b819e37ad9 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -516,7 +516,7 @@ declare module "mongoose" { /** defaults to 1 */ parallel?: number; } - + /* * section querycursor.js * http://mongoosejs.com/docs/api.html#querycursor-js @@ -807,7 +807,7 @@ declare module "mongoose" { * Intellisense for Schema definitions */ interface SchemaDefinition { - [path: string]: SchemaTypeOpts; + [path: string]: SchemaTypeOpts | Schema | SchemaType; } /* @@ -2723,7 +2723,7 @@ declare module "mongoose" { passRawResult?: boolean; /** overwrites the schema's strict mode option for this update */ strict?: boolean; - /** + /** * if true, run all setters defined on the associated model's schema for all fields * defined in the query and the update. */ diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index 7216ed73fb..d6f262ebf6 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -368,8 +368,8 @@ new mongoose.Schema({d: {type: Date, min: [ new mongoose.Schema({ integerOnly: { type: Number, - get: v => Math.round(v), - set: v => Math.round(v) + get: (v: number) => Math.round(v), + set: (v: number) => Math.round(v) } }); new mongoose.Schema({ name: { type: String, validate: [ diff --git a/types/multistream/index.d.ts b/types/multistream/index.d.ts new file mode 100644 index 0000000000..7a7d0eb309 --- /dev/null +++ b/types/multistream/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for multistream 2.1 +// Project: https://github.com/feross/multistream +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Stream } from 'stream'; + +declare function multistream(streams: multistream.Streams): NodeJS.ReadableStream; + +declare namespace multistream { + type LazyStream = () => Stream; + type FactoryStream = (cb: (err: Error | null, stream: NodeJS.ReadableStream) => any) => void; + type Streams = Array | FactoryStream; + + function obj(streams: Streams): NodeJS.ReadableStream; +} + +export = multistream; diff --git a/types/multistream/multistream-tests.ts b/types/multistream/multistream-tests.ts new file mode 100644 index 0000000000..99206e0102 --- /dev/null +++ b/types/multistream/multistream-tests.ts @@ -0,0 +1,40 @@ +import fs = require('fs'); +import stream = require('stream'); + +import through = require('through'); +import through2 = require('through2'); +import multistream = require('multistream'); + +const readable = new stream.Readable(); +const writable = new stream.Writable(); +const transform = new stream.Transform(); +const duplex = new stream.Duplex(); +const pass = new stream.PassThrough(); + +const streams = [ + readable, + transform, + duplex, + pass, + through(), + through2(), + fs.createReadStream('.filepath'), + () => fs.createWriteStream('.filepath2') +]; + +const factory: multistream.FactoryStream = (cb) => { + if (1 === 1) return cb(null, fs.createReadStream('.filepath')); + + cb(null, fs.createReadStream('.filepath')); +}; + +// $ExpectType ReadableStream +multistream(streams); +multistream(factory); + +// $ExpectType ReadableStream +multistream.obj(streams); +multistream.obj(factory); + +// $ExpectError +multistream([writable]); diff --git a/types/multistream/tsconfig.json b/types/multistream/tsconfig.json new file mode 100644 index 0000000000..3fa5cc7c47 --- /dev/null +++ b/types/multistream/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "multistream-tests.ts" + ] +} diff --git a/types/multistream/tslint.json b/types/multistream/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/multistream/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/nconf/index.d.ts b/types/nconf/index.d.ts index ff72f3e568..f03eb88b39 100644 --- a/types/nconf/index.d.ts +++ b/types/nconf/index.d.ts @@ -69,7 +69,7 @@ export interface ICallbackFunction { } export declare class Provider { - constructor(options: IOptions); + constructor(options?: IOptions); stores: any; sources: any[]; diff --git a/types/negotiator/index.d.ts b/types/negotiator/index.d.ts index c4d713ac5c..5f665331e3 100644 --- a/types/negotiator/index.d.ts +++ b/types/negotiator/index.d.ts @@ -78,6 +78,6 @@ declare class Negotiator { declare namespace Negotiator { interface Headers { - [key: string]: string | string[]; + [key: string]: string | string[] | undefined; } } diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 188e1315d6..9b075668f5 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -193,8 +193,6 @@ declare var Buffer: { prototype: Buffer; /** * Allocates a new Buffer using an {array} of octets. - * - * @param array */ from(array: any[]): Buffer; /** @@ -204,22 +202,16 @@ declare var Buffer: { * within the {arrayBuffer} that will be shared by the Buffer. * * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - * @param byteOffset - * @param length */ from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; /** * Copies the passed {buffer} data onto a new Buffer instance. - * - * @param buffer */ from(buffer: Buffer): Buffer; /** * Creates a new Buffer containing the given JavaScript string {str}. * If provided, the {encoding} parameter identifies the character encoding. * If not provided, {encoding} defaults to 'utf8'. - * - * @param str */ from(str: string, encoding?: string): Buffer; /** @@ -472,11 +464,15 @@ declare namespace NodeJS { exit(code?: number): never; exitCode: number; getgid(): number; - setgid(id: number): void; - setgid(id: string): void; + setgid(id: number | string): void; getuid(): number; - setuid(id: number): void; - setuid(id: string): void; + setuid(id: number | string): void; + geteuid(): number; + seteuid(id: number | string): void; + getegid(): number; + setegid(id: number | string): void; + getgroups(): number[]; + setgroups(groups: Array): void; version: string; versions: ProcessVersions; config: { @@ -838,7 +834,47 @@ declare module "http" { // incoming headers will never contain number export interface IncomingHttpHeaders { - [header: string]: string | string[]; + 'accept'?: string; + 'access-control-allow-origin'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-headers'?: string; + 'accept-patch'?: string; + 'accept-ranges'?: string; + 'age'?: string; + 'allow'?: string; + 'alt-svc'?: string; + 'cache-control'?: string; + 'connection'?: string; + 'content-disposition'?: string; + 'content-encoding'?: string; + 'content-language'?: string; + 'content-length'?: string; + 'content-location'?: string; + 'content-range'?: string; + 'content-type'?: string; + 'date'?: string; + 'expires'?: string; + 'host'?: string; + 'last-modified'?: string; + 'location'?: string; + 'pragma'?: string; + 'proxy-authenticate'?: string; + 'public-key-pins'?: string; + 'retry-after'?: string; + 'set-cookie'?: string[]; + 'strict-transport-security'?: string; + 'trailer'?: string; + 'transfer-encoding'?: string; + 'tk'?: string; + 'upgrade'?: string; + 'vary'?: string; + 'via'?: string; + 'warning'?: string; + 'www-authenticate'?: string; + [header: string]: string | string[] | undefined; } // outgoing headers allows numbers (as they are converted internally to strings) @@ -4483,9 +4519,6 @@ declare module "path" { /** * Solve the relative path from {from} to {to}. * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. - * - * @param from - * @param to */ export function relative(from: string, to: string): string; /** @@ -4718,7 +4751,7 @@ declare module "tls" { encrypted: boolean; /** * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. - * @returns {CipherNameAndProtocol} - Returns an object representing the cipher name + * @returns Returns an object representing the cipher name * and the SSL/TLS protocol version of the current connection. */ getCipher(): CipherNameAndProtocol; @@ -4728,21 +4761,21 @@ declare module "tls" { * If detailed argument is true the full chain with issuer property will be returned, * if false only the top certificate without issuer property. * If the peer does not provide a certificate, it returns null or an empty object. - * @param {boolean} detailed - If true; the full chain with issuer property will be returned. - * @returns {PeerCertificate | DetailedPeerCertificate} - An object representing the peer's certificate. + * @param detailed - If true; the full chain with issuer property will be returned. + * @returns An object representing the peer's certificate. */ getPeerCertificate(detailed: true): DetailedPeerCertificate; getPeerCertificate(detailed?: false): PeerCertificate; getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; /** * Could be used to speed up handshake establishment when reconnecting to the server. - * @returns {any} - ASN.1 encoded TLS session or undefined if none was negotiated. + * @returns ASN.1 encoded TLS session or undefined if none was negotiated. */ getSession(): any; /** * NOTE: Works only with client TLS sockets. * Useful only for debugging, for session reuse provide session option to tls.connect(). - * @returns {any} - TLS session ticket or undefined if none was negotiated. + * @returns TLS session ticket or undefined if none was negotiated. */ getTLSTicket(): any; /** @@ -4750,9 +4783,9 @@ declare module "tls" { * * NOTE: Can be used to request peer's certificate after the secure connection has been established. * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. - * @param {TlsOptions} options - The options may contain the following fields: rejectUnauthorized, + * @param options - The options may contain the following fields: rejectUnauthorized, * requestCert (See tls.createServer() for details). - * @param {Function} callback - callback(err) will be executed with null as err, once the renegotiation + * @param callback - callback(err) will be executed with null as err, once the renegotiation * is successfully completed. */ renegotiate(options: TlsOptions, callback: (err: Error | null) => void): any; @@ -4763,8 +4796,8 @@ declare module "tls" { * large fragments can span multiple roundtrips, and their processing can be delayed due to packet * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, * which may decrease overall server throughput. - * @param {number} size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). - * @returns {boolean} - Returns true on success, false otherwise. + * @param size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * @returns Returns true on success, false otherwise. */ setMaxSendFragment(size: number): boolean; diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 315ec48d2f..41639e52c6 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -684,6 +684,7 @@ namespace util_tests { assert(typeof util.inspect.custom === 'symbol'); // util.callbackify + // tslint:disable-next-line no-unnecessary-class class callbackifyTest { static fn(): Promise { assert(arguments.length === 0); @@ -1321,9 +1322,24 @@ namespace http_tests { request.abort(); } - const options: http.RequestOptions = { - timeout: 30000 - }; + // http request options + { + const requestOpts: http.RequestOptions = { + timeout: 30000 + }; + + const clientArgs: http.ClientRequestArgs = { + timeout: 30000 + }; + } + + // http headers + { + const headers: http.IncomingHttpHeaders = { + 'content-type': 'application/json', + 'set-cookie': [ 'type=ninja', 'language=javascript' ] + }; + } } ////////////////////////////////////////////////////// diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index d88db82da1..5496da86cd 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -154,8 +154,6 @@ declare var Buffer: { prototype: Buffer; /** * Allocates a new Buffer using an {array} of octets. - * - * @param array */ from(array: any[]): Buffer; /** @@ -165,22 +163,16 @@ declare var Buffer: { * within the {arrayBuffer} that will be shared by the Buffer. * * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - * @param byteOffset - * @param length */ from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?:number): Buffer; /** * Copies the passed {buffer} data onto a new Buffer instance. - * - * @param buffer */ from(buffer: Buffer): Buffer; /** * Creates a new Buffer containing the given JavaScript string {str}. * If provided, the {encoding} parameter identifies the character encoding. * If not provided, {encoding} defaults to 'utf8'. - * - * @param str */ from(str: string, encoding?: string): Buffer; /** @@ -565,21 +557,74 @@ declare module "http" { import * as net from "net"; import * as stream from "stream"; + // incoming headers will never contain number + export interface IncomingHttpHeaders { + 'accept'?: string; + 'access-control-allow-origin'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-headers'?: string; + 'accept-patch'?: string; + 'accept-ranges'?: string; + 'age'?: string; + 'allow'?: string; + 'alt-svc'?: string; + 'cache-control'?: string; + 'connection'?: string; + 'content-disposition'?: string; + 'content-encoding'?: string; + 'content-language'?: string; + 'content-length'?: string; + 'content-location'?: string; + 'content-range'?: string; + 'content-type'?: string; + 'date'?: string; + 'expires'?: string; + 'host'?: string; + 'last-modified'?: string; + 'location'?: string; + 'pragma'?: string; + 'proxy-authenticate'?: string; + 'public-key-pins'?: string; + 'retry-after'?: string; + 'set-cookie'?: string[]; + 'strict-transport-security'?: string; + 'trailer'?: string; + 'transfer-encoding'?: string; + 'tk'?: string; + 'upgrade'?: string; + 'vary'?: string; + 'via'?: string; + 'warning'?: string; + 'www-authenticate'?: string; + [header: string]: string | string[] | undefined; + } + + // outgoing headers allows numbers (as they are converted internally to strings) + export interface OutgoingHttpHeaders { + [header: string]: number | string | string[] | undefined; + } + export interface RequestOptions { protocol?: string; host?: string; hostname?: string; family?: number; - port?: number; + port?: number | string; localAddress?: string; socketPath?: string; method?: string; path?: string; - headers?: { [key: string]: any }; + headers?: OutgoingHttpHeaders; auth?: string; - agent?: Agent|boolean; + agent?: Agent | boolean; + timeout?: number; } + export type ClientRequestArgs = RequestOptions + export interface Server extends net.Server { setTimeout(msecs: number, callback: Function): void; maxHeadersCount: number; @@ -600,8 +645,8 @@ declare module "http" { write(str: string, encoding?: string, fd?: string): boolean; writeContinue(): void; - writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; - writeHead(statusCode: number, headers?: any): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): void; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; statusCode: number; statusMessage: string; headersSent: boolean; @@ -610,7 +655,7 @@ declare module "http" { getHeader(name: string): string; removeHeader(name: string): void; write(chunk: any, encoding?: string): any; - addTrailers(headers: any): void; + addTrailers(headers: OutgoingHttpHeaders): void; // Extended base methods end(): void; @@ -636,7 +681,7 @@ declare module "http" { setHeader(name: string, value: string | string[]): void; getHeader(name: string): string; removeHeader(name: string): void; - addTrailers(headers: any): void; + addTrailers(headers: OutgoingHttpHeaders): void; // Extended base methods end(): void; @@ -647,10 +692,10 @@ declare module "http" { } export interface IncomingMessage extends events.EventEmitter, stream.Readable { httpVersion: string; - headers: any; + headers: IncomingHttpHeaders; rawHeaders: string[]; - trailers: any; - rawTrailers: any; + trailers: OutgoingHttpHeaders; + rawTrailers: string[]; setTimeout(msecs: number, callback: Function): NodeJS.Timer; /** * Only valid for request obtained from http.Server. @@ -1576,15 +1621,11 @@ declare module "fs" { /** * Asynchronous rename. - * @param oldPath - * @param newPath * @param callback No arguments other than a possible exception are given to the completion callback. */ export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous rename - * @param oldPath - * @param newPath */ export function renameSync(oldPath: string, newPath: string): void; export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; @@ -1629,79 +1670,62 @@ declare module "fs" { /** * Asynchronous unlink - deletes the file specified in {path} * - * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous unlink - deletes the file specified in {path} - * - * @param path */ export function unlinkSync(path: string): void; /** * Asynchronous rmdir - removes the directory specified in {path} * - * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous rmdir - removes the directory specified in {path} - * - * @param path */ export function rmdirSync(path: string): void; /** * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdir(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdir(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdirSync(path: string, mode?: number): void; /** * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdirSync(path: string, mode?: string): void; /** * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * - * @param prefix * @param callback The created folder path is passed as a string to the callback's second parameter. */ export function mkdtemp(prefix: string, callback?: (err: NodeJS.ErrnoException, folder: string) => void): void; /** * Synchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * - * @param prefix * @returns Returns the created folder path. */ export function mkdtempSync(prefix: string): string; @@ -1736,8 +1760,6 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName - * @param encoding * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ export function readFile(filename: string, encoding: null, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; @@ -1746,7 +1768,6 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ @@ -1756,7 +1777,6 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ @@ -1764,15 +1784,11 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; /** * Synchronous readFile - Synchronously reads the entire contents of a file. - * - * @param fileName - * @param encoding */ export function readFileSync(filename: string, encoding: null): Buffer; export function readFileSync(filename: string, encoding: string): string; @@ -1780,7 +1796,6 @@ declare module "fs" { /** * Synchronous readFile - Synchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. */ export function readFileSync(filename: string, options: { encoding: null; flag?: string; }): Buffer; @@ -1789,7 +1804,6 @@ declare module "fs" { /** * Synchronous readFile - Synchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. */ export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; @@ -1910,9 +1924,6 @@ declare module "path" { /** * Solve the relative path from {from} to {to}. * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. - * - * @param from - * @param to */ export function relative(from: string, to: string): string; /** diff --git a/types/node/v4/node-tests.ts b/types/node/v4/node-tests.ts index 05b20806cd..8f005da455 100644 --- a/types/node/v4/node-tests.ts +++ b/types/node/v4/node-tests.ts @@ -499,6 +499,25 @@ namespace http_tests { request.setNoDelay(true); request.abort(); } + + // http request options + { + const requestOpts: http.RequestOptions = { + timeout: 30000 + }; + + const clientArgs: http.ClientRequestArgs = { + timeout: 30000 + }; + } + + // http headers + { + const headers: http.IncomingHttpHeaders = { + 'content-type': 'application/json', + 'set-cookie': [ 'type=ninja', 'language=javascript' ] + }; + } } ////////////////////////////////////////////////////// diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 8f73bab752..ef2208af0b 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -150,8 +150,6 @@ declare var Buffer: { prototype: Buffer; /** * Allocates a new Buffer using an {array} of octets. - * - * @param array */ from(array: any[]): Buffer; /** @@ -161,22 +159,16 @@ declare var Buffer: { * within the {arrayBuffer} that will be shared by the Buffer. * * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - * @param byteOffset - * @param length */ from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; /** * Copies the passed {buffer} data onto a new Buffer instance. - * - * @param buffer */ from(buffer: Buffer): Buffer; /** * Creates a new Buffer containing the given JavaScript string {str}. * If provided, the {encoding} parameter identifies the character encoding. * If not provided, {encoding} defaults to 'utf8'. - * - * @param str */ from(str: string, encoding?: string): Buffer; /** @@ -637,21 +629,74 @@ declare module "http" { import * as net from "net"; import * as stream from "stream"; + // incoming headers will never contain number + export interface IncomingHttpHeaders { + 'accept'?: string; + 'access-control-allow-origin'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-headers'?: string; + 'accept-patch'?: string; + 'accept-ranges'?: string; + 'age'?: string; + 'allow'?: string; + 'alt-svc'?: string; + 'cache-control'?: string; + 'connection'?: string; + 'content-disposition'?: string; + 'content-encoding'?: string; + 'content-language'?: string; + 'content-length'?: string; + 'content-location'?: string; + 'content-range'?: string; + 'content-type'?: string; + 'date'?: string; + 'expires'?: string; + 'host'?: string; + 'last-modified'?: string; + 'location'?: string; + 'pragma'?: string; + 'proxy-authenticate'?: string; + 'public-key-pins'?: string; + 'retry-after'?: string; + 'set-cookie'?: string[]; + 'strict-transport-security'?: string; + 'trailer'?: string; + 'transfer-encoding'?: string; + 'tk'?: string; + 'upgrade'?: string; + 'vary'?: string; + 'via'?: string; + 'warning'?: string; + 'www-authenticate'?: string; + [header: string]: string | string[] | undefined; + } + + // outgoing headers allows numbers (as they are converted internally to strings) + export interface OutgoingHttpHeaders { + [header: string]: number | string | string[] | undefined; + } + export interface RequestOptions { protocol?: string; host?: string; hostname?: string; family?: number; - port?: number; + port?: number | string; localAddress?: string; socketPath?: string; method?: string; path?: string; - headers?: { [key: string]: any }; + headers?: OutgoingHttpHeaders; auth?: string; agent?: Agent | boolean; + timeout?: number; } + export type ClientRequestArgs = RequestOptions + export interface Server extends net.Server { setTimeout(msecs: number, callback: Function): void; maxHeadersCount: number; @@ -673,8 +718,8 @@ declare module "http" { write(str: string, encoding?: string, fd?: string): boolean; writeContinue(): void; - writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; - writeHead(statusCode: number, headers?: any): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): void; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; statusCode: number; statusMessage: string; headersSent: boolean; @@ -684,7 +729,7 @@ declare module "http" { getHeader(name: string): string; removeHeader(name: string): void; write(chunk: any, encoding?: string): any; - addTrailers(headers: any): void; + addTrailers(headers: OutgoingHttpHeaders): void; finished: boolean; // Extended base methods @@ -711,7 +756,7 @@ declare module "http" { setHeader(name: string, value: string | string[]): void; getHeader(name: string): string; removeHeader(name: string): void; - addTrailers(headers: any): void; + addTrailers(headers: OutgoingHttpHeaders): void; // Extended base methods end(): void; @@ -725,10 +770,10 @@ declare module "http" { httpVersionMajor: number; httpVersionMinor: number; connection: net.Socket; - headers: any; + headers: IncomingHttpHeaders; rawHeaders: string[]; - trailers: any; - rawTrailers: any; + trailers: OutgoingHttpHeaders; + rawTrailers: string[]; setTimeout(msecs: number, callback: Function): NodeJS.Timer; /** * Only valid for request obtained from http.Server. @@ -2354,15 +2399,11 @@ declare module "fs" { /** * Asynchronous rename. - * @param oldPath - * @param newPath * @param callback No arguments other than a possible exception are given to the completion callback. */ export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous rename - * @param oldPath - * @param newPath */ export function renameSync(oldPath: string, newPath: string): void; export function truncate(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; @@ -2407,79 +2448,62 @@ declare module "fs" { /** * Asynchronous unlink - deletes the file specified in {path} * - * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ export function unlink(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous unlink - deletes the file specified in {path} - * - * @param path */ export function unlinkSync(path: string | Buffer): void; /** * Asynchronous rmdir - removes the directory specified in {path} * - * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ export function rmdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous rmdir - removes the directory specified in {path} - * - * @param path */ export function rmdirSync(path: string | Buffer): void; /** * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdir(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdir(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdirSync(path: string | Buffer, mode?: number): void; /** * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdirSync(path: string | Buffer, mode?: string): void; /** * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * - * @param prefix * @param callback The created folder path is passed as a string to the callback's second parameter. */ export function mkdtemp(prefix: string, callback?: (err: NodeJS.ErrnoException, folder: string) => void): void; /** * Synchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * - * @param prefix * @returns Returns the created folder path. */ export function mkdtempSync(prefix: string): string; @@ -2512,8 +2536,6 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName - * @param encoding * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ export function readFile(filename: string, encoding: null, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; @@ -2522,7 +2544,6 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ @@ -2532,7 +2553,6 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ @@ -2540,15 +2560,11 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; /** * Synchronous readFile - Synchronously reads the entire contents of a file. - * - * @param fileName - * @param encoding */ export function readFileSync(filename: string, encoding: null): Buffer; export function readFileSync(filename: string, encoding: string): string; @@ -2556,7 +2572,6 @@ declare module "fs" { /** * Synchronous readFile - Synchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. */ export function readFileSync(filename: string, options: { encoding: null; flag?: string; }): Buffer; @@ -2565,7 +2580,6 @@ declare module "fs" { /** * Synchronous readFile - Synchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. */ export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; @@ -2806,9 +2820,6 @@ declare module "path" { /** * Solve the relative path from {from} to {to}. * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. - * - * @param from - * @param to */ export function relative(from: string, to: string): string; /** @@ -3007,7 +3018,7 @@ declare module "tls" { /** * Returns the bound address, the address family name and port of the underlying socket as reported by * the operating system. - * @returns {any} - An object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }. + * @returns An object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }. */ address(): { port: number; family: string; address: string }; /** @@ -3026,8 +3037,8 @@ declare module "tls" { encrypted: boolean; /** * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. - * @returns {CipherNameAndProtocol} - Returns an object representing the cipher name - * and the SSL/TLS protocol version of the current connection. + * @returns Returns an object representing the cipher name and the SSL/TLS protocol version of the current + * connection. */ getCipher(): CipherNameAndProtocol; /** @@ -3036,8 +3047,8 @@ declare module "tls" { * If detailed argument is true the full chain with issuer property will be returned, * if false only the top certificate without issuer property. * If the peer does not provide a certificate, it returns null or an empty object. - * @param {boolean} detailed - If true; the full chain with issuer property will be returned. - * @returns {any} - An object representing the peer's certificate. + * @param detailed - If true; the full chain with issuer property will be returned. + * @returns An object representing the peer's certificate. */ getPeerCertificate(detailed?: boolean): { subject: Certificate; @@ -3051,13 +3062,13 @@ declare module "tls" { }; /** * Could be used to speed up handshake establishment when reconnecting to the server. - * @returns {any} - ASN.1 encoded TLS session or undefined if none was negotiated. + * @returns ASN.1 encoded TLS session or undefined if none was negotiated. */ getSession(): any; /** * NOTE: Works only with client TLS sockets. * Useful only for debugging, for session reuse provide session option to tls.connect(). - * @returns {any} - TLS session ticket or undefined if none was negotiated. + * @returns TLS session ticket or undefined if none was negotiated. */ getTLSTicket(): any; /** @@ -3086,9 +3097,9 @@ declare module "tls" { * * NOTE: Can be used to request peer's certificate after the secure connection has been established. * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. - * @param {TlsOptions} options - The options may contain the following fields: rejectUnauthorized, + * @param options - The options may contain the following fields: rejectUnauthorized, * requestCert (See tls.createServer() for details). - * @param {Function} callback - callback(err) will be executed with null as err, once the renegotiation + * @param callback - callback(err) will be executed with null as err, once the renegotiation * is successfully completed. */ renegotiate(options: TlsOptions, callback: (err: Error) => any): any; @@ -3099,8 +3110,8 @@ declare module "tls" { * large fragments can span multiple roundtrips, and their processing can be delayed due to packet * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, * which may decrease overall server throughput. - * @param {number} size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). - * @returns {boolean} - Returns true on success, false otherwise. + * @param size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * @returns Returns true on success, false otherwise. */ setMaxSendFragment(size: number): boolean; diff --git a/types/node/v6/node-tests.ts b/types/node/v6/node-tests.ts index 15c36ef058..1a6b87db05 100644 --- a/types/node/v6/node-tests.ts +++ b/types/node/v6/node-tests.ts @@ -935,6 +935,25 @@ namespace http_tests { request.setNoDelay(true); request.abort(); } + + // http request options + { + const requestOpts: http.RequestOptions = { + timeout: 30000 + }; + + const clientArgs: http.ClientRequestArgs = { + timeout: 30000 + }; + } + + // http headers + { + const headers: http.IncomingHttpHeaders = { + 'content-type': 'application/json', + 'set-cookie': [ 'type=ninja', 'language=javascript' ] + }; + } } ////////////////////////////////////////////////////// diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index fc6cd33091..9f4208a7cb 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -165,8 +165,6 @@ declare var Buffer: { prototype: Buffer; /** * Allocates a new Buffer using an {array} of octets. - * - * @param array */ from(array: any[]): Buffer; /** @@ -176,22 +174,16 @@ declare var Buffer: { * within the {arrayBuffer} that will be shared by the Buffer. * * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - * @param byteOffset - * @param length */ from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; /** * Copies the passed {buffer} data onto a new Buffer instance. - * - * @param buffer */ from(buffer: Buffer): Buffer; /** * Creates a new Buffer containing the given JavaScript string {str}. * If provided, the {encoding} parameter identifies the character encoding. * If not provided, {encoding} defaults to 'utf8'. - * - * @param str */ from(str: string, encoding?: string): Buffer; /** @@ -653,22 +645,74 @@ declare module "http" { import * as net from "net"; import * as stream from "stream"; + // incoming headers will never contain number + export interface IncomingHttpHeaders { + 'accept'?: string; + 'access-control-allow-origin'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-headers'?: string; + 'accept-patch'?: string; + 'accept-ranges'?: string; + 'age'?: string; + 'allow'?: string; + 'alt-svc'?: string; + 'cache-control'?: string; + 'connection'?: string; + 'content-disposition'?: string; + 'content-encoding'?: string; + 'content-language'?: string; + 'content-length'?: string; + 'content-location'?: string; + 'content-range'?: string; + 'content-type'?: string; + 'date'?: string; + 'expires'?: string; + 'host'?: string; + 'last-modified'?: string; + 'location'?: string; + 'pragma'?: string; + 'proxy-authenticate'?: string; + 'public-key-pins'?: string; + 'retry-after'?: string; + 'set-cookie'?: string[]; + 'strict-transport-security'?: string; + 'trailer'?: string; + 'transfer-encoding'?: string; + 'tk'?: string; + 'upgrade'?: string; + 'vary'?: string; + 'via'?: string; + 'warning'?: string; + 'www-authenticate'?: string; + [header: string]: string | string[] | undefined; + } + + // outgoing headers allows numbers (as they are converted internally to strings) + export interface OutgoingHttpHeaders { + [header: string]: number | string | string[] | undefined; + } + export interface RequestOptions { protocol?: string; host?: string; hostname?: string; family?: number; - port?: number; + port?: number | string; localAddress?: string; socketPath?: string; method?: string; path?: string; - headers?: { [key: string]: any }; + headers?: OutgoingHttpHeaders; auth?: string; agent?: Agent | boolean; timeout?: number; } + export type ClientRequestArgs = RequestOptions + export interface Server extends net.Server { setTimeout(msecs: number, callback: Function): void; maxHeadersCount: number; @@ -690,8 +734,8 @@ declare module "http" { write(str: string, encoding?: string, fd?: string): boolean; writeContinue(): void; - writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; - writeHead(statusCode: number, headers?: any): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): void; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; statusCode: number; statusMessage: string; headersSent: boolean; @@ -701,7 +745,7 @@ declare module "http" { getHeader(name: string): string; removeHeader(name: string): void; write(chunk: any, encoding?: string): any; - addTrailers(headers: any): void; + addTrailers(headers: OutgoingHttpHeaders): void; finished: boolean; // Extended base methods @@ -728,7 +772,7 @@ declare module "http" { setHeader(name: string, value: string | string[]): void; getHeader(name: string): string; removeHeader(name: string): void; - addTrailers(headers: any): void; + addTrailers(headers: OutgoingHttpHeaders): void; // Extended base methods end(): void; @@ -742,10 +786,10 @@ declare module "http" { httpVersionMajor: number; httpVersionMinor: number; connection: net.Socket; - headers: any; + headers: IncomingHttpHeaders; rawHeaders: string[]; - trailers: any; - rawTrailers: any; + trailers: OutgoingHttpHeaders; + rawTrailers: string[]; setTimeout(msecs: number, callback: Function): NodeJS.Timer; /** * Only valid for request obtained from http.Server. @@ -2487,15 +2531,11 @@ declare module "fs" { /** * Asynchronous rename. - * @param oldPath - * @param newPath * @param callback No arguments other than a possible exception are given to the completion callback. */ export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous rename - * @param oldPath - * @param newPath */ export function renameSync(oldPath: string, newPath: string): void; export function truncate(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; @@ -2540,79 +2580,62 @@ declare module "fs" { /** * Asynchronous unlink - deletes the file specified in {path} * - * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ export function unlink(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous unlink - deletes the file specified in {path} - * - * @param path */ export function unlinkSync(path: string | Buffer): void; /** * Asynchronous rmdir - removes the directory specified in {path} * - * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ export function rmdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous rmdir - removes the directory specified in {path} - * - * @param path */ export function rmdirSync(path: string | Buffer): void; /** * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdir(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdir(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdirSync(path: string | Buffer, mode?: number): void; /** * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * - * @param path - * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ export function mkdirSync(path: string | Buffer, mode?: string): void; /** * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * - * @param prefix * @param callback The created folder path is passed as a string to the callback's second parameter. */ export function mkdtemp(prefix: string, callback?: (err: NodeJS.ErrnoException, folder: string) => void): void; /** * Synchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * - * @param prefix * @returns Returns the created folder path. */ export function mkdtempSync(prefix: string): string; @@ -2646,8 +2669,6 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName - * @param encoding * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ export function readFile(filename: string, encoding: null, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; @@ -2656,7 +2677,6 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ @@ -2666,7 +2686,6 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ @@ -2674,15 +2693,11 @@ declare module "fs" { /** * Asynchronous readFile - Asynchronously reads the entire contents of a file. * - * @param fileName * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; /** * Synchronous readFile - Synchronously reads the entire contents of a file. - * - * @param fileName - * @param encoding */ export function readFileSync(filename: string, encoding: null): Buffer; export function readFileSync(filename: string, encoding: string): string; @@ -2690,7 +2705,6 @@ declare module "fs" { /** * Synchronous readFile - Synchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. */ export function readFileSync(filename: string, options: { encoding: null; flag?: string; }): Buffer; @@ -2699,7 +2713,6 @@ declare module "fs" { /** * Synchronous readFile - Synchronously reads the entire contents of a file. * - * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. */ export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; @@ -2940,9 +2953,6 @@ declare module "path" { /** * Solve the relative path from {from} to {to}. * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. - * - * @param from - * @param to */ export function relative(from: string, to: string): string; /** @@ -3160,7 +3170,7 @@ declare module "tls" { /** * Returns the bound address, the address family name and port of the underlying socket as reported by * the operating system. - * @returns {any} - An object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }. + * @returns An object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }. */ address(): { port: number; family: string; address: string }; /** @@ -3179,7 +3189,7 @@ declare module "tls" { encrypted: boolean; /** * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. - * @returns {CipherNameAndProtocol} - Returns an object representing the cipher name + * @returns Returns an object representing the cipher name * and the SSL/TLS protocol version of the current connection. */ getCipher(): CipherNameAndProtocol; @@ -3189,15 +3199,15 @@ declare module "tls" { * If detailed argument is true the full chain with issuer property will be returned, * if false only the top certificate without issuer property. * If the peer does not provide a certificate, it returns null or an empty object. - * @param {boolean} detailed - If true; the full chain with issuer property will be returned. - * @returns {PeerCertificate | DetailedPeerCertificate} - An object representing the peer's certificate. + * @param detailed - If true; the full chain with issuer property will be returned. + * @returns An object representing the peer's certificate. */ getPeerCertificate(detailed: true): DetailedPeerCertificate; getPeerCertificate(detailed?: false): PeerCertificate; getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; /** * Could be used to speed up handshake establishment when reconnecting to the server. - * @returns {any} - ASN.1 encoded TLS session or undefined if none was negotiated. + * @returns ASN.1 encoded TLS session or undefined if none was negotiated. */ getSession(): any; /** @@ -3232,9 +3242,9 @@ declare module "tls" { * * NOTE: Can be used to request peer's certificate after the secure connection has been established. * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. - * @param {TlsOptions} options - The options may contain the following fields: rejectUnauthorized, + * @param options - The options may contain the following fields: rejectUnauthorized, * requestCert (See tls.createServer() for details). - * @param {Function} callback - callback(err) will be executed with null as err, once the renegotiation + * @param callback - callback(err) will be executed with null as err, once the renegotiation * is successfully completed. */ renegotiate(options: TlsOptions, callback: (err: Error) => any): any; @@ -3245,8 +3255,8 @@ declare module "tls" { * large fragments can span multiple roundtrips, and their processing can be delayed due to packet * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, * which may decrease overall server throughput. - * @param {number} size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). - * @returns {boolean} - Returns true on success, false otherwise. + * @param size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * @returns Returns true on success, false otherwise. */ setMaxSendFragment(size: number): boolean; diff --git a/types/node/v7/node-tests.ts b/types/node/v7/node-tests.ts index f439a83213..9bbf6a9300 100644 --- a/types/node/v7/node-tests.ts +++ b/types/node/v7/node-tests.ts @@ -1033,9 +1033,24 @@ namespace http_tests { request.abort(); } - const options: http.RequestOptions = { - timeout: 30000 - }; + // http request options + { + const requestOpts: http.RequestOptions = { + timeout: 30000 + }; + + const clientArgs: http.ClientRequestArgs = { + timeout: 30000 + }; + } + + // http headers + { + const headers: http.IncomingHttpHeaders = { + 'content-type': 'application/json', + 'set-cookie': [ 'type=ninja', 'language=javascript' ] + }; + } } ////////////////////////////////////////////////////// diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index fef494614f..e24b6c4a2c 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -181,11 +181,16 @@ declare namespace Office { messageParent(messageObject: any): void; /** * Closes the UI container where the JavaScript is executing. - * The behavior of this method is specified by the following table. - * When called from Behavior - * A UI-less command button No effect. Any dialogs opened by displayDialogAsync will remain open. - * A taskpane The taskpane will close. Any dialogs opened by displayDialogAsync will also close. If the taskpane supports pinning and was pinned by the user, it will be un-pinned. - * A module extension No effect. + * + * Supported hosts: Outlook - Minimum requirement set: Mailbox 1.5 + * + * The behavior of this method is specified by the following: + * + * Called from a UI-less command button: No effect. Any dialog opened by displayDialogAsync will remain open. + * + * Called from a taskpane: The taskpane will close. Any dialog opened by displayDialogAsync will also close. If the taskpane supports pinning and was pinned by the user, it will be un-pinned. + * + * Called from a module extension: No effect. */ closeContainer(): void; } diff --git a/types/opn/index.d.ts b/types/opn/index.d.ts index 78a1043442..2a7c5afe25 100644 --- a/types/opn/index.d.ts +++ b/types/opn/index.d.ts @@ -1,80 +1,52 @@ -// Type definitions for opn 3.0.2 +// Type definitions for opn 5.1 // Project: https://github.com/sindresorhus/opn // Definitions by: Shinnosuke Watanabe , -// Maxime LUCE +// Maxime LUCE , +// Tommy Lent // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -import * as cp from "child_process"; +import * as cp from 'child_process'; -interface DefaultFunction { - /** - * Uses the command open on OS X, start on Windows and xdg-open on other platforms. - * - * Returns the spawned child process. - * You'd normally not need to use this for anything, but it can be useful if you'd like - * to attach custom event listeners or perform other operations directly on the spawned process. - * -* @param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. Eg. URLs opens in your default browser. - */ - (target: string): cp.ChildProcess; - - /** - * Uses the command open on OS X, start on Windows and xdg-open on other platforms. - * - * Returns the spawned child process. - * You'd normally not need to use this for anything, but it can be useful if you'd like - * to attach custom event listeners or perform other operations directly on the spawned process. - * - * @param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. Eg. URLs opens in your default browser. - * @param callback- Called when the opened app exits, or if `wait: false`, immediately when opening. - */ - (target: string, callback: (err: Error) => void): cp.ChildProcess; - - /** - * Uses the command open on OS X, start on Windows and xdg-open on other platforms. - * - * Returns the spawned child process. - * You'd normally not need to use this for anything, but it can be useful if you'd like - * to attach custom event listeners or perform other operations directly on the spawned process. - * - * @param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. Eg. URLs opens in your default browser. - * @param options - Options to be passed to opn. - */ - (target: string, options: Opn.Options): cp.ChildProcess; - - /** - * Uses the command open on OS X, start on Windows and xdg-open on other platforms. - * - * Returns the spawned child process. - * You'd normally not need to use this for anything, but it can be useful if you'd like - * to attach custom event listeners or perform other operations directly on the spawned process. - * - * @param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. Eg. URLs opens in your default browser. - * @param options - Options to be passed to opn. - * @param callback- Called when the opened app exits, or if `wait: false`, immediately when opening. - */ - (target: string, options: Opn.Options, callback: (err: Error) => void): cp.ChildProcess; -} - -declare var opn: DefaultFunction; +/* Note that ES6 modules cannot directly export callable functions. + * This file should be imported using the CommonJS-style: + * import x = require('opn'); + */ export = opn; +/** + * Uses the command `open` on OS X, `start` on Windows and `xdg-open` on other platforms. + * + * Returns a promise for the spawned child process. You would normally not need to use this for + * anything, but it can be useful if you'd like to attach custom event listeners or perform + * other operations directly on the spawned process. + * + * @param target The thing you want to open. Can be a URL, file, or executable. + * Opens in the default app for the file type. For example, URLs open in your default + * browser. + * @param options Options to be passed to opn. + */ +declare function opn( + target: string, + options?: Opn.Options +): Promise; + declare namespace Opn { - export interface Options { + interface Options { /** - * Wait for the opened app to exit before calling the `callback`. - * If `false` it's called immediately when opening the app. + * Wait for the opened app to exit before fulfilling the promise. + * If `false` it's fulfilled immediately when opening the app. * On Windows you have to explicitly specify an app for it to be able to wait. + * Defaults to `true`. */ wait?: boolean; - + /** - * Specify the app to open the target with, or an array with the app and app arguments. - * The app name is platform dependent. Don't hard code it in reusable modules. + * Specify the app to open the `target` with, or an array with the app and app arguments. + * The app name is platform dependent. Don't hard code it in reusable modules. * Eg. Chrome is `google chrome` on OS X, `google-chrome` on Linux and `chrome` on Windows. */ - app?: string | string[]; + app?: string | ReadonlyArray; } } diff --git a/types/opn/opn-tests.ts b/types/opn/opn-tests.ts index 33a043de9f..c2956f2546 100644 --- a/types/opn/opn-tests.ts +++ b/types/opn/opn-tests.ts @@ -1,18 +1,8 @@ +import opn = require('opn'); +opn('foo'); // $ExpectType Promise -import * as opn from "opn"; - -var errorCallback: (err: Error) => void; - -opn("foo"); -opn("foo", errorCallback); - -opn("foo", { app: "bar" }); -opn("foo", { app: ["bar", "--arg"] }); -opn("foo", { app: "bar", wait: false }); -opn("foo", { app: ["bar", "--arg"] , wait: false}); - -opn("foo", { app: "bar" }, errorCallback); -opn("foo", { app: ["bar", "--arg"] }, errorCallback); -opn("foo", { app: "bar", wait: false }, errorCallback); -opn("foo", { app: ["bar", "--arg"], wait: false }, errorCallback); +opn('foo', { app: 'bar' }); // $ExpectType Promise +opn('foo', { app: ['bar', '--arg'] }); // $ExpectType Promise +opn('foo', { app: 'bar', wait: false }); // $ExpectType Promise +opn('foo', { app: ['bar', '--arg'], wait: false }); // $ExpectType Promise diff --git a/types/opn/tsconfig.json b/types/opn/tsconfig.json index 9c2829989d..2a51fff8ca 100644 --- a/types/opn/tsconfig.json +++ b/types/opn/tsconfig.json @@ -1,23 +1,16 @@ { "compilerOptions": { "module": "commonjs", - "lib": [ - "es6" - ], + "lib": ["es6"], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", - "typeRoots": [ - "../" - ], + "typeRoots": ["../"], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, - "files": [ - "index.d.ts", - "opn-tests.ts" - ] -} \ No newline at end of file + "files": ["index.d.ts", "opn-tests.ts"] +} diff --git a/types/opn/tslint.json b/types/opn/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/opn/tslint.json +++ b/types/opn/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/parse-json/index.d.ts b/types/parse-json/index.d.ts new file mode 100644 index 0000000000..638933ec40 --- /dev/null +++ b/types/parse-json/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for parse-json 4.0 +// Project: https://github.com/sindresorhus/parse-json +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function parseJson(input: string | null, filepath?: string): any; +declare function parseJson(input: string | null, reviver: (key: any, value: any) => any, filepath?: string): any; + +export = parseJson; diff --git a/types/parse-json/parse-json-tests.ts b/types/parse-json/parse-json-tests.ts new file mode 100644 index 0000000000..6bd0a55b32 --- /dev/null +++ b/types/parse-json/parse-json-tests.ts @@ -0,0 +1,10 @@ +import parse = require('parse-json'); + +parse(null); +parse('{}'); +parse('{}', 'filepath'); +parse('{}', () => null); +parse('{}', () => null, 'filepath'); + +// $ExpectError +parse(1); diff --git a/types/parse-json/tsconfig.json b/types/parse-json/tsconfig.json new file mode 100644 index 0000000000..448f6787ba --- /dev/null +++ b/types/parse-json/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "parse-json-tests.ts" + ] +} diff --git a/types/parse-json/tslint.json b/types/parse-json/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/parse-json/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/parsimmon/index.d.ts b/types/parsimmon/index.d.ts index 6bc93ae84a..dfbae05e23 100644 --- a/types/parsimmon/index.d.ts +++ b/types/parsimmon/index.d.ts @@ -41,7 +41,7 @@ * //=> {status: true, value: ['a', ['c', 'c', 'c', 'c', 'c']]} * ``` */ -declare function Parsimmon(fn: (input: string, i: number) => Parsimmon.Result): Parsimmon.Parser; +declare function Parsimmon(fn: (input: string, i: number) => Parsimmon.Reply): Parsimmon.Parser; declare namespace Parsimmon { type StreamType = string; @@ -169,21 +169,21 @@ declare namespace Parsimmon { /** * Alias of `Parsimmon(fn)` for backwards compatibility. */ - function Parser(fn: (input: string, i: number) => Parsimmon.Result): Parser; + function Parser(fn: (input: string, i: number) => Parsimmon.Reply): Parser; /** * To be used inside of Parsimmon(fn). Generates an object describing how * far the successful parse went (index), and what value it created doing * so. See documentation for Parsimmon(fn). */ - function makeSuccess(index: number, value: T): Success; + function makeSuccess(index: number, value: T): SuccessReply; /** * To be used inside of Parsimmon(fn). Generates an object describing how * far the unsuccessful parse went (index), and what kind of syntax it * expected to see (expectation). See documentation for Parsimmon(fn). */ - function makeFailure(furthest: number, expectation: string): Failure; + function makeFailure(furthest: number, expectation: string): FailureReply; /** * Returns true if obj is a Parsimmon parser, otherwise false. @@ -276,9 +276,27 @@ declare namespace Parsimmon { p1: Parser, p2: Parser, p3: Parser, p4: Parser, p5: Parser, p6: Parser, p7: Parser, p8: Parser, cb: (a1: T, a2: U, a3: V, a4: W, a5: X, a6: Y, a7: Z, a8: A) => B): Parser; - type SuccessFunctionType = (index: number, result: U) => Result; - type FailureFunctionType = (index: number, msg: string) => Result; - type ParseFunctionType = (stream: StreamType, index: number) => Result; + interface SuccessReply { + status: true; + index: number; + value: T; + furthest: -1; + expected: string[]; + } + + interface FailureReply { + status: false; + index: -1; + value: null; + furthest: number; + expected: string[]; + } + + type Reply = SuccessReply | FailureReply; + + type SuccessFunctionType = (index: number, result: U) => Reply; + type FailureFunctionType = (index: number, msg: string) => Reply; + type ParseFunctionType = (stream: StreamType, index: number) => Reply; /** * allows to add custom primitive parsers. */ diff --git a/types/parsimmon/parsimmon-tests.ts b/types/parsimmon/parsimmon-tests.ts index 4c8780f5fc..f89d2fda2f 100644 --- a/types/parsimmon/parsimmon-tests.ts +++ b/types/parsimmon/parsimmon-tests.ts @@ -1,5 +1,5 @@ import P = require('parsimmon'); -import { Parser, Mark, Result, Index } from "parsimmon"; +import { Parser, Mark, Result, Index, Reply } from "parsimmon"; // -- -- -- -- -- -- -- -- -- -- -- -- -- @@ -65,9 +65,10 @@ if (fooResult.status === true) { } // -- -- -- -- -- -- -- -- -- -- -- -- -- +let fooReply: Reply; -fooResult = P.makeSuccess(0, foo); -fooResult = P.makeFailure(0, ''); +fooReply = P.makeSuccess(0, foo); +fooReply = P.makeFailure(0, ''); fooPar = P((input: string, i: number) => P.makeSuccess(0, foo)); fooPar = P.Parser((input: string, i: number) => P.makeSuccess(0, foo)); diff --git a/types/pixi.js/index.d.ts b/types/pixi.js/index.d.ts index f33f0d502c..48b9583c0b 100644 --- a/types/pixi.js/index.d.ts +++ b/types/pixi.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Pixi.js 4.5 +// Type definitions for Pixi.js 4.6 // Project: https://github.com/pixijs/pixi.js/tree/dev // Definitions by: clark-stevenson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -372,7 +372,7 @@ declare namespace PIXI { on(event: interaction.InteractionEventTypes, fn: (event: interaction.InteractionEvent) => void, context?: any): this; once(event: interaction.InteractionEventTypes, fn: (event: interaction.InteractionEvent) => void, context?: any): this; removeListener(event: interaction.InteractionEventTypes, fn?: (event: interaction.InteractionEvent) => void, context?: any): this; - removeAllListeners(event: interaction.InteractionEventTypes): this; + removeAllListeners(event?: interaction.InteractionEventTypes): this; off(event: interaction.InteractionEventTypes, fn?: (event: interaction.InteractionEvent) => void, context?: any): this; addListener(event: interaction.InteractionEventTypes, fn: (event: interaction.InteractionEvent) => void, context?: any): this; } @@ -875,7 +875,7 @@ declare namespace PIXI { on(event: "prerender" | "postrender", fn: () => void, context?: any): this; once(event: "prerender" | "postrender", fn: () => void, context?: any): this; removeListener(event: "prerender" | "postrender", fn?: () => void, context?: any): this; - removeAllListeners(event: "prerender" | "postrender"): this; + removeAllListeners(event?: "prerender" | "postrender"): this; off(event: "prerender" | "postrender", fn?: () => void, context?: any): this; addListener(event: "prerender" | "postrender", fn: () => void, context?: any): this; } @@ -977,7 +977,7 @@ declare namespace PIXI { once(event: "context", fn: (gl: WebGLRenderingContext) => void, context?: any): this; removeListener(event: "prerender" | "postrender", fn?: () => void, context?: any): this; removeListener(event: "context", fn?: (gl: WebGLRenderingContext) => void, context?: any): this; - removeAllListeners(event: "prerender" | "postrender" | "context"): this; + removeAllListeners(event?: "prerender" | "postrender" | "context"): this; off(event: "prerender" | "postrender", fn?: () => void, context?: any): this; off(event: "context", fn?: (gl: WebGLRenderingContext) => void, context?: any): this; addListener(event: "prerender" | "postrender", fn: () => void, context?: any): this; @@ -1485,7 +1485,7 @@ declare namespace PIXI { on(event: "update", fn: (baseRenderTexture: BaseRenderTexture) => void, context?: any): this; once(event: "update", fn: (baseRenderTexture: BaseRenderTexture) => void, context?: any): this; removeListener(event: "update", fn?: (baseRenderTexture: BaseRenderTexture) => void, context?: any): this; - removeAllListeners(event: "update"): this; + removeAllListeners(event?: "update"): this; off(event: "update", fn?: (baseRenderTexture: BaseRenderTexture) => void, context?: any): this; addListener(event: "update", fn: (baseRenderTexture: BaseRenderTexture) => void, context?: any): this; } @@ -1542,7 +1542,7 @@ declare namespace PIXI { on(event: "update" | "loaded" | "error" | "dispose", fn: (baseTexture: BaseTexture) => void, context?: any): this; once(event: "update" | "loaded" | "error" | "dispose", fn: (baseTexture: BaseTexture) => void, context?: any): this; removeListener(event: "update" | "loaded" | "error" | "dispose", fn?: (baseTexture: BaseTexture) => void, context?: any): this; - removeAllListeners(event: "update" | "loaded" | "error" | "dispose"): this; + removeAllListeners(event?: "update" | "loaded" | "error" | "dispose"): this; off(event: "update" | "loaded" | "error" | "dispose", fn?: (baseTexture: BaseTexture) => void, context?: any): this; addListener(event: "update" | "loaded" | "error" | "dispose", fn: (baseTexture: BaseTexture) => void, context?: any): this; } @@ -1568,7 +1568,7 @@ declare namespace PIXI { protected _uvs: TextureUvs; orig: Rectangle; protected _updateID: number; - transform: any; + transform: TextureMatrix; textureCacheIds: string[]; update(): void; @@ -1576,7 +1576,7 @@ declare namespace PIXI { protected onBaseTextureUpdated(baseTexture: BaseTexture): void; destroy(destroyBase?: boolean): void; clone(): Texture; - protected _updateUvs(): void; + _updateUvs(): void; static fromImage(imageUrl: string, crossOrigin?: boolean, scaleMode?: number, sourceScale?: number): Texture; static fromFrame(frameId: string): Texture; @@ -1604,10 +1604,27 @@ declare namespace PIXI { on(event: "update", fn: (texture: Texture) => void, context?: any): this; once(event: "update", fn: (texture: Texture) => void, context?: any): this; removeListener(event: "update", fn?: (texture: Texture) => void, context?: any): this; - removeAllListeners(event: "update"): this; + removeAllListeners(event?: "update"): this; off(event: "update", fn?: (texture: Texture) => void, context?: any): this; addListener(event: "update", fn: (texture: Texture) => void, context?: any): this; } + class TextureMatrix { + constructor(texture: Texture, clampMargin?: number); + + protected _texture: Texture; + mapCoord: Matrix; + uClampFrame: Float32Array; + uClampOffset: Float32Array; + protected _lastTextureID: number; + + clampOffset: number; + clampMargin: number; + + texture: Texture; + + update(forceUpdate?: boolean): boolean; + multiplyUvs(uvs: Float32Array, out?: Float32Array): Float32Array; + } class TextureUvs { x0: number; y0: number; @@ -1833,7 +1850,7 @@ declare namespace PIXI { static fromFrames(frame: string[]): AnimatedSprite; static fromImages(images: string[]): AnimatedSprite; } - class TextureTransform { + class TextureMatrix { constructor(texture: Texture, clampMargin?: number); protected _texture: Texture; @@ -1857,7 +1874,7 @@ declare namespace PIXI { protected _width: number; protected _height: number; protected _canvasPattern: CanvasPattern; - uvTransform: TextureTransform; + uvTransform: TextureMatrix; uvRespectAnchor: boolean; clampMargin: number; @@ -1986,6 +2003,8 @@ declare namespace PIXI { map: Texture; } class AlphaFilter extends Filter<{}> { + constructor(alpha?: number); + alpha: number; glShaderKey: number; } @@ -2409,7 +2428,7 @@ declare namespace PIXI { texture: Texture; tintRgb: Float32Array; protected _glDatas: { [n: number]: any; }; - protected _uvTransform: extras.TextureTransform; + protected _uvTransform: extras.TextureMatrix; uploadUvTransform: boolean; multiplyUvs(): void; refresh(forceUpdate?: boolean): void; @@ -2642,7 +2661,7 @@ declare namespace PIXI { ////////////////////////////////////////////////////////////////////////////// /////////////////////////////pixi-gl-core///////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// - // pixi-gl-core https://github.com/pixijs/pixi-gl-core + // pixi-gl-core 1.1.2 https://github.com/pixijs/pixi-gl-core // sharedArrayBuffer as a type is not available yet. // need to fully define what an `Attrib` is. namespace glCore { @@ -2727,7 +2746,7 @@ declare namespace PIXI { uniforms: any; attributes: any; - bind(): void; + bind(): this; destroy(): void; } class GLTexture { @@ -3203,6 +3222,15 @@ declare namespace PIXI { type PRECISION = string; } + namespace GroupD8 { + /** + * @name PIXI.GroupD8.isSwapWidthHeight + * @see PIXI.GroupD8.isVertical + * @deprecated since version 4.6.0 + */ + function isSwapWidthHeight(rotation: number): boolean; + } + namespace extras { /** * @class @@ -3212,6 +3240,15 @@ declare namespace PIXI { * @deprecated since version 4.2.0 */ type MovieClip = extras.AnimatedSprite; + + /** + * @class + * @name TextureTransform + * @memberof PIXI.extras + * @see PIXI.TextureMatrix + * @deprecated since version 4.6.0 + */ + type TextureTranform = TextureMatrix; } namespace filters { diff --git a/types/pixi.js/pixi.js-tests.ts b/types/pixi.js/pixi.js-tests.ts index 53eaff46a3..48581e67fe 100644 --- a/types/pixi.js/pixi.js-tests.ts +++ b/types/pixi.js/pixi.js-tests.ts @@ -1235,6 +1235,67 @@ function demos() { } } + class TextureRotate { + private app: PIXI.Application; + private bol: boolean; + private texture: PIXI.Texture; + private secondTexture: PIXI.Texture; + private dude: PIXI.Sprite; + + constructor() { + this.app = new PIXI.Application(); + document.body.appendChild(this.app.view); + + this.bol = false; + + PIXI.loader.add("flowerTop", "required/assets/flowerTop.png"); + PIXI.loader.load((loader: PIXI.loaders.Loader, resources: any) => { + this.texture = resources.flowerTop.texture; + this.init(); + }); + } + + private init(): void { + const textures = [this.texture]; + const D8 = PIXI.GroupD8; + for (let rotate = 1; rotate < 16; rotate++) { + const h = D8.isVertical(rotate) ? this.texture.frame.width : this.texture.frame.height; + const w = D8.isVertical(rotate) ? this.texture.frame.height : this.texture.frame.width; + + const frame = this.texture.frame; + const crop = new PIXI.Rectangle(this.texture.frame.x, this.texture.frame.y, w, h); + const trim = crop; + let rotatedTexture: PIXI.Texture; + if (rotate % 2 === 0) { + rotatedTexture = new PIXI.Texture(this.texture.baseTexture, frame, crop, trim, rotate); + } else { + rotatedTexture = new PIXI.Texture(this.texture.baseTexture, frame, crop, trim, rotate - 1); + rotatedTexture.rotate++; + } + textures.push(rotatedTexture); + } + + const offsetX = this.app.renderer.width / 16 | 0; + const offsetY = this.app.renderer.height / 8 | 0; + const gridW = this.app.renderer.width / 4 | 0; + const gridH = this.app.renderer.height / 5 | 0; + + for (let i = 0; i < 16; i++) { + const dude = new PIXI.Sprite(textures[i < 8 ? i * 2 : (i - 8) * 2 + 1]); + dude.scale.x = 0.5; + dude.scale.y = 0.5; + dude.x = offsetX + gridW * (i % 4); + dude.y = offsetY + gridH * (i / 4 | 0); + this.app.stage.addChild(dude); + + const text = new PIXI.Text("rotate = " + dude.texture.rotate, { fontFamily: "Courier New", fontSize: "12px", fill: "white", align: "left" }); + text.x = dude.x; + text.y = dude.y - 20; + this.app.stage.addChild(text); + } + } + } + class TextureSwap { private app: PIXI.Application; private bol: boolean; diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index 8479c100a1..f92bedd135 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for puppeteer 0.12 +// Type definitions for puppeteer 0.13 // Project: https://github.com/GoogleChrome/puppeteer#readme // Definitions by: Marvin Hagemeister // Christopher Deutsch @@ -7,49 +7,122 @@ /// +/** Keyboard provides an api for managing a virtual keyboard. */ export interface Keyboard { + /** + * Dispatches a keydown event. + * @param key Name of key to press, such as ArrowLeft. + * @param options Specifies a input text event. + */ down(key: string, options?: { text?: string }): Promise; + + /** Shortcut for `keyboard.down` and `keyboard.up`. */ press(key: string, options?: { text?: string, delay?: number }): Promise; + + /** Dispatches a `keypress` and `input` event. This does not send a `keydown` or keyup `event`. */ sendCharacter(char: string): Promise; + + /** + * Sends a keydown, keypress/input, and keyup event for each character in the text. + * @param text A text to type into a focused element. + * @param options Specifies the typing options. + */ type(text: string, options?: { delay?: number }): Promise; + + /** + * Dispatches a keyup event. + * @param key Name of key to release, such as ArrowLeft. + */ up(key: string): Promise; } export interface MousePressOptions { + /** + * left, right, or middle. + * @default left + */ button?: MouseButtons; + /** + * The number of clicks. + * @default 1 + */ clickCount?: number; } export interface Mouse { + /** + * Shortcut for `mouse.move`, `mouse.down` and `mouse.up`. + * @param x The x position. + * @param y The y position. + * @param options The click options. + */ click(x: number, y: number, options: ClickOptions): Promise; + /** + * Dispatches a `mousedown` event. + * @param options The mouse press options. + */ down(options?: MousePressOptions): Promise; + + /** + * Dispatches a `mousemove` event. + * @param x The x position. + * @param y The y position. + * @param options The mouse move options. + */ move(x: number, y: number, options?: { steps: number }): Promise; + /** + * Dispatches a `mouseup` event. + * @param options The mouse press options. + */ up(options?: MousePressOptions): Promise; } export interface Touchscreen { + /** + * Dispatches a touchstart and touchend event. + * @param x The x position. + * @param y The y position. + */ tap(x: number, y: number): Promise; } - +/** + * You can use `tracing.start` and `tracing.stop` to create a trace file which can be opened in Chrome DevTools or timeline viewer. + */ export interface Tracing { start(options: { path: string; screenshots?: boolean }): Promise; stop(): Promise; } +/** Dialog objects are dispatched by page via the 'dialog' event. */ export interface Dialog { + /** + * Accepts the dialog. + * @param promptText A text to enter in prompt. Does not cause any effects if the dialog's type is not prompt. + */ accept(promptText?: string): Promise; + + /** If dialog is prompt, returns default prompt value. Otherwise, returns empty string. */ defaultValue(): string; + + /** Dismiss the dialog */ dismiss(): Promise; + + /** Returns the message displayed in the dialog. */ message(): string; + + /** The dialog type. Dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`. */ type: "alert" | "beforeunload" | "confirm" | "prompt"; } +/** ConsoleMessage objects are dispatched by page via the 'console' event. */ export interface ConsoleMessage { + /** The message arguments. */ args: JSHandle[]; + /** The message text. */ text: string; type: 'log' | 'debug' | 'info' | 'error' | 'warning' | 'dir' | 'dirxml' | 'table' | - 'trace' | 'clear' | 'startGroup' | 'startGroupCollapsed' | 'endGroup' | 'assert' | - 'profile' | 'profileEnd' | 'count' | 'timeEnd'; + 'trace' | 'clear' | 'startGroup' | 'startGroupCollapsed' | 'endGroup' | 'assert' | + 'profile' | 'profileEnd' | 'count' | 'timeEnd'; } export type PageEvents = @@ -66,6 +139,12 @@ export type PageEvents = | "requestfinished" | "response"; +export type BrowserEvents = + | "disconnected" + | "targetchanged" + | "targetcreated" + | "targetdestroyed"; + export interface AuthOptions { username: string; password: string; @@ -85,18 +164,28 @@ export interface ClickOptions { delay?: number; } +/** Represents a browser cookie. */ export interface Cookie { + /** The cookie name. */ name: string; + /** The cookie value. */ value: string; + /** The cookie domain. */ domain: string; + /** The cookie path. */ path: string; + /** The cookie Unix expiration time in seconds. */ expires: number; + /** The cookie http only flag. */ httpOnly: boolean; + /** The cookie secure flag. */ secure: boolean; + /** The cookie same site definition. */ sameSite: "Strict" | "Lax"; } export interface DeleteCookie { + /** The cookie name. */ name: string; url?: string; domain?: string; @@ -105,37 +194,73 @@ export interface DeleteCookie { } export interface SetCookie { + /** The cookie name. */ name: string; + /** The cookie value. */ value: string; + /** The cookie domain. */ domain?: string; + /** The cookie path. */ path?: string; + /** The cookie Unix expiration time in seconds. */ expires?: number; + /** The cookie http only flag. */ httpOnly?: boolean; + /** The cookie secure flag. */ secure?: boolean; + /** The cookie same site definition. */ sameSite?: "Strict" | "Lax"; } export interface Viewport { + /** The page width in pixels. */ width: number; + /** The page height in pixels. */ height: number; + /** + * Specify device scale factor (can be thought of as dpr). + * @default 1 + */ deviceScaleFactor?: number; + /** + * Whether the `meta viewport` tag is taken into account. + * @default false + */ isMobile?: boolean; + /** + * Specifies if viewport supports touch events. + * @default false + */ hasTouch?: boolean; + /** + * Specifies if viewport is in landscape mode. + * @default false + */ isLandscape?: boolean; } +/** Page emulation options. */ export interface EmulateOptions { + /** The viewport emulation options. */ viewport?: Viewport; + /** The emulated user-agent. */ userAgent?: string; } export type EvaluateFn = string | ((...args: any[]) => any); +/** The navigation options. */ export interface NavigationOptions { + /** + * Maximum navigation time in milliseconds, pass 0 to disable timeout. + * @default 30000 + */ timeout?: number; - waitUntil?: "load" | "networkidle" | "networkIdleTimeout"; - networkIdleInflight?: number; - networkIdleTimeout?: number; + /** + * When to consider navigation succeeded. + * @default load Navigation is consider when the `load` event is fired. + */ + waitUntil?: "load" | "domcontentloaded" | "networkidle0" | "networkidle2"; } export type PDFFormat = @@ -151,41 +276,103 @@ export type PDFFormat = | "A5"; export interface PDFOptions { - /** If no path is provided, the PDF won't be saved to the disk. */ + /** + * The file path to save the PDF to. + * If `path` is a relative path, then it is resolved relative to current working directory. + * If no path is provided, the PDF won't be saved to the disk. + */ path?: string; + /** + * Scale of the webpage rendering. + * @default 1 + */ scale?: number; + /** + * Display header and footer. + * @default false + */ displayHeaderFooter?: boolean; + /** + * Print background graphics. + * @default false + */ printBackground?: boolean; + /** + * Paper orientation. + * @default false + */ landscape?: boolean; /** * Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty * string, which means print all pages. */ pageRanges?: string; + /** Paper format. If set, takes priority over width or height options. Defaults to 'Letter'. */ format?: PDFFormat; + /** Paper width, accepts values labeled with units. */ width?: string; + /** Paper height, accepts values labeled with units. */ height?: string; + /** Paper margins, defaults to none. */ margin?: { + /** Top margin, accepts values labeled with units. */ top?: string; + /** Right margin, accepts values labeled with units. */ right?: string; + /** Bottom margin, accepts values labeled with units. */ bottom?: string; + /** Left margin, accepts values labeled with units. */ left?: string; }; } +/** Defines the screenshot options. */ export interface ScreenshotOptions { + /** + * The file path to save the image to. The screenshot type will be inferred from file extension. + * If `path` is a relative path, then it is resolved relative to current working directory. + * If no path is provided, the image won't be saved to the disk. + */ path?: string; + /** + * The screenshot type. + * @default png + */ type?: "jpeg" | "png"; /** The quality of the image, between 0-100. Not applicable to png images. */ quality?: number; + /** + * When true, takes a screenshot of the full scrollable page. + * @default false + */ fullPage?: boolean; + /** + * An object which specifies clipping region of the page. + */ clip?: BoundingBox; + /** + * Hides default white background and allows capturing screenshots with transparency. + * @default false + */ omitBackground?: boolean; } -export interface TagOptions { +/** Options for `addStyleTag` */ +export interface StyleTagOptions { + /** Url of the tag. */ url?: string; + /** Path to the CSS file to be injected into frame. If `path` is a relative path, then it is resolved relative to current working directory. */ path?: string; + /** Raw CSS content to be injected into frame. */ + content?: string; +} +/** Options for `addScriptTag` */ +export interface ScriptTagOptions { + /** Url of a script to be added. */ + url?: string; + /** Path to the JavaScript file to be injected into frame. If `path` is a relative path, then it is resolved relative to current working directory. */ + path?: string; + /** Raw JavaScript content to be injected into frame. */ content?: string; } @@ -195,25 +382,84 @@ export interface PageFnOptions { } export interface BoundingBox { + /** The x-coordinate of top-left corner. */ x: number; + /** The y-coordinate of top-left corner. */ y: number; + /** The width. */ width: number; + /** The height. */ height: number; } +/** + * Represents an in-page DOM element. ElementHandles can be created with the page.$ method. + */ export interface ElementHandle extends JSHandle { - boundingBox(): BoundingBox; + /** + * The method runs element.querySelector within the page. If no element matches the selector, the return value resolve to null. + * @param selector A selector to query element for + * @since 0.13.0 + */ + $(selector: string): Promise; + /** + * The method runs element.querySelectorAll within the page. If no elements match the selector, the return value resolve to []. + * @param selector A selector to query element for + * @since 0.13.0 + */ + $$(selector: string): Promise; + /** + * This method returns the bounding box of the element (relative to the main frame), or null if the element is not visible. + */ + boundingBox(): BoundingBox | null; + /** + * This method scrolls element into view if needed, and then uses page.mouse to click in the center of the element. + * If the element is detached from DOM, the method throws an error. + * @param options Specifies the options. + * @since 0.9.0 + */ click(options?: ClickOptions): Promise; + /** + * Calls focus on the element. + */ focus(): Promise; + /** + * This method scrolls element into view if needed, and then uses page.mouse to hover over the center of the element. + * If the element is detached from DOM, the method throws an error. + */ hover(): Promise; + /** + * Focuses the element, and then uses keyboard.down and keyboard.up. + * @param key Name of key to press, such as ArrowLeft. See USKeyboardLayout for a list of all key names. + * @param options The text and delay options. + */ press(key: string, options?: { text?: string, delay?: number }): Promise; + /** + * This method scrolls element into view if needed, and then uses page.screenshot to take a screenshot of the element. + * If the element is detached from DOM, the method throws an error. + * @param options Same options as in page.screenshot. + */ screenshot(options?: ScreenshotOptions): Promise; + /** + * This method scrolls element into view if needed, and then uses touchscreen.tap to tap in the center of the element. + * If the element is detached from DOM, the method throws an error. + */ tap(): Promise; toString(): string; + /** + * Focuses the element, and then sends a keydown, keypress/input, and keyup event for each character in the text. + * @param text A text to type into a focused element. + * @param options The typing options. + */ type(text: string, options?: { delay: number }): Promise; + /** + * This method expects elementHandle to point to an input element. + * @param filePaths Sets the value of the file input these paths. If some of the filePaths are relative paths, then they are resolved relative to current working directory. + */ uploadFile(...filePaths: string[]): Promise; } +/** The class represents a context for JavaScript execution. */ export interface ExecutionContext { evaluate( fn: EvaluateFn, @@ -226,28 +472,64 @@ export interface ExecutionContext { queryObjects(prototypeHandle: JSHandle): JSHandle; } +/** JSHandle represents an in-page JavaScript object. */ export interface JSHandle { - asElement(): ElementHandle; + /** + * Returns a ElementHandle + */ + asElement(): ElementHandle | null; + /** + * Stops referencing the element handle. + */ dispose(): Promise; + /** + * Gets the execution context. + */ executionContext(): ExecutionContext; + /** + * Returns a map with property names as keys and JSHandle instances for the property values. + */ getProperties(): Promise>; + /** + * Fetches a single property from the objectHandle. + * @param propertyName The property to get. + */ getProperty(propertyName: string): Promise; + + /** + * Returns a JSON representation of the object. + * The JSON is generated by running JSON.stringify on the object in page and consequent JSON.parse in puppeteer. + * @throws The method will throw if the referenced object is not stringifiable. + */ jsonValue(): Promise; } export interface Metrics { + /** The timestamp when the metrics sample was taken. */ Timestamp: number; + /** Number of documents in the page. */ Documents: number; + /** Number of frames in the page. */ Frames: number; + /** Number of events in the page. */ JSEventListeners: number; + /** Number of DOM nodes in the page. */ Nodes: number; + /** Total number of full or partial page layout. */ LayoutCount: number; + /** Total number of page style recalculations. */ RecalcStyleCount: number; + /** Combined durations of all page layouts. */ LayoutDuration: number; + /** Combined duration of all page style recalculations. */ RecalcStyleDuration: number; + /** Combined duration of JavaScript execution. */ ScriptDuration: number; + /** Combined duration of all tasks performed by the browser. */ TaskDuration: number; + /** Used JavaScript heap size. */ JSHeapUsedSize: number; + /** Total JavaScript heap size. */ JSHeapTotalSize: number; } @@ -282,48 +564,148 @@ export interface Overrides { headers?: Headers; } +/** Represents a page request. */ export interface Request { + /** + * Aborts request. + * To use this, request interception should be enabled with `page.setRequestInterception`. + * @throws An exception is immediately thrown if the request interception is not enabled. + */ abort(): Promise; + + /** + * Continues request with optional request overrides. + * To use this, request interception should be enabled with `page.setRequestInterception`. + * @throws An exception is immediately thrown if the request interception is not enabled. + */ continue(overrides?: Overrides): Promise; + + /** + * An object with HTTP headers associated with the request. + * All header names are lower-case. + */ headers: Headers; + /** Returns the request's method (GET, POST, etc.) */ + method: HttpMethod; + + /** Contains the request's post body, if any. */ postData: string | undefined; + + /** Contains the request's resource type as it was perceived by the rendering engine. */ resourceType: ResourceType; + + /** + * Fulfills request with given response. + * To use this, request interception should be enabled with `page.setRequestInterception`. + * @throws An exception is immediately thrown if the request interception is not enabled. + * @param response The response options that will fulfill this request. + */ + respond(response: RespondOptions): Promise; + + /** A matching `Response` object, or `null` if the response has not been received yet. */ response(): Response | null; + + /** Contains the URL of the request. */ url: string; } +/** Options for `Request.respond` method */ +export interface RespondOptions { + /** + * Specifies the response status code. + * @default 200 + */ + status?: number; + /** Specifies the response headers. */ + headers?: Headers; + /** Specifies the Content-Type response header. */ + contentType?: string; + /** Specifies the response body. */ + body?: Buffer | string; +} +/** Response class represents responses which are received by page. */ export interface Response { + /** Promise which resolves to a buffer with response body. */ buffer(): Promise; + /** An object with HTTP headers associated with the response. All header names are lower-case. */ headers: Headers; + /** + * Promise which resolves to a JSON representation of response body. + * @throws This method will throw if the response body is not parsable via `JSON.parse`. + */ json(): Promise; + /** Contains a boolean stating whether the response was successful (status in the range 200-299) or not. */ ok: boolean; + /** A matching Request object. */ request(): Request; + /** Contains the status code of the response (e.g., 200 for a success). */ status: number; + /** Promise which resolves to a text representation of response body. */ text(): Promise; + /** Contains the URL of the response. */ url: string; } export interface FrameBase { - $(selector: string): Promise; + /** + * The method runs document.querySelector within the page. + * If no element matches the selector, the return value resolve to null. + */ + $(selector: string): Promise; + /** + * The method runs document.querySelectorAll within the page. If no elements match the selector, the return value resolve to []. + */ $$(selector: string): Promise; - $$eval( - selector: string, - fn: (...args: any[]) => void - ): Promise; + + /** + * This method runs document.querySelector within the page and passes it as the first argument to `fn`. + * If there's no element matching selector, the method throws an error. + * If `fn` returns a Promise, then $eval would wait for the promise to resolve and return its value. + */ $eval( selector: string, fn: (...args: any[]) => void ): Promise; - addScriptTag(options: TagOptions): Promise; - addStyleTag(options: TagOptions): Promise; - injectFile(filePath: string): Promise; + + /** + * This method runs document.querySelectorAll within the page and passes it as the first argument to `fn`. + * If `fn` returns a Promise, then $$eval would wait for the promise to resolve and return its value. + * @param selector A selector to query frame for + * @param fn Function to be evaluated in browser context + * @param args Arguments to pass to pageFunction + * @returns Promise which resolves to the return value of pageFunction + */ + $$eval( + selector: string, + fn: (...args: any[]) => void, + ...args: any[] + ): Promise; + + /** Adds a `