From a820963086c363274c111ac0df027762c61c1cf3 Mon Sep 17 00:00:00 2001 From: David Newell Date: Fri, 30 Jun 2017 11:12:58 -0400 Subject: [PATCH 001/495] Updating dagre Cleaning up white space --- types/dagre/index.d.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/types/dagre/index.d.ts b/types/dagre/index.d.ts index 7408d145cf..ebc53a090d 100644 --- a/types/dagre/index.d.ts +++ b/types/dagre/index.d.ts @@ -12,15 +12,27 @@ export namespace graphlib { nodes(): string[]; node(id: any): any; setDefaultEdgeLabel(callback: () => void): Graph; - setEdge(sourceId: string, targetId: string, options?: { [key: string]: any }): Graph; + setDefaultNodeLabel(callback: () => void): Graph; + setEdge(sourceId: string, targetId: string, options?: { [key: string]: any }, value?: string): Graph; setGraph(options: { [key: string]: any }): Graph; setNode(id: string, node: { [key: string]: any }): Graph; + graph(): GraphOptions; + + constructor(opt?: {}); + setParent(name: string, parentName: string): void; + hasNode(name: string): boolean; } } +export interface GraphOptions { + width: number; + height: number; +} + export function layout(graph: graphlib.Graph): void; export interface Edge { v: string; w: string; + name?: string; } From 101ffe819477461f8209ceab517e91ea68c66037 Mon Sep 17 00:00:00 2001 From: David Newell Date: Wed, 5 Jul 2017 12:07:33 -0400 Subject: [PATCH 002/495] Updates based on feedback --- types/dagre/index.d.ts | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/types/dagre/index.d.ts b/types/dagre/index.d.ts index ebc53a090d..c66709ca29 100644 --- a/types/dagre/index.d.ts +++ b/types/dagre/index.d.ts @@ -11,22 +11,27 @@ export namespace graphlib { edge(id: any): any; nodes(): string[]; node(id: any): any; - setDefaultEdgeLabel(callback: () => void): Graph; - setDefaultNodeLabel(callback: () => void): Graph; + setDefaultEdgeLabel(callback: string|(() => string)): Graph; + setDefaultNodeLabel(callback: string|(() => string)): Graph; setEdge(sourceId: string, targetId: string, options?: { [key: string]: any }, value?: string): Graph; - setGraph(options: { [key: string]: any }): Graph; + setEdge(params: {v: string, w: string, name?: string}, value?: string): Graph; + setGraph(label: GraphLabel): Graph; setNode(id: string, node: { [key: string]: any }): Graph; - graph(): GraphOptions; + graph(): GraphLabel; - constructor(opt?: {}); + constructor(opt?: {directed?: boolean, multigraph?: boolean, compound?: boolean}); setParent(name: string, parentName: string): void; hasNode(name: string): boolean; } } -export interface GraphOptions { - width: number; - height: number; +export interface GraphLabel { + width?: number; + height?: number; + compound: boolean; + rankdir: string; + nodesep: number; + edgesep: number; } export function layout(graph: graphlib.Graph): void; From 6f5e9a281407a1d261ac831c59cd92a3c2057316 Mon Sep 17 00:00:00 2001 From: David Newell Date: Mon, 24 Jul 2017 15:39:35 -0400 Subject: [PATCH 003/495] Fixing tests --- types/dagre/index.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/types/dagre/index.d.ts b/types/dagre/index.d.ts index c66709ca29..2c6c6e38ab 100644 --- a/types/dagre/index.d.ts +++ b/types/dagre/index.d.ts @@ -11,8 +11,8 @@ export namespace graphlib { edge(id: any): any; nodes(): string[]; node(id: any): any; - setDefaultEdgeLabel(callback: string|(() => string)): Graph; - setDefaultNodeLabel(callback: string|(() => string)): Graph; + setDefaultEdgeLabel(callback: string|(() => string|void)): Graph; + setDefaultNodeLabel(callback: string|(() => string|void)): Graph; setEdge(sourceId: string, targetId: string, options?: { [key: string]: any }, value?: string): Graph; setEdge(params: {v: string, w: string, name?: string}, value?: string): Graph; setGraph(label: GraphLabel): Graph; @@ -28,10 +28,10 @@ export namespace graphlib { export interface GraphLabel { width?: number; height?: number; - compound: boolean; - rankdir: string; - nodesep: number; - edgesep: number; + compound?: boolean; + rankdir?: string; + nodesep?: number; + edgesep?: number; } export function layout(graph: graphlib.Graph): void; From c9339867922368fb70048647bf2a13e461ebeb22 Mon Sep 17 00:00:00 2001 From: Steven Masala Date: Tue, 8 Aug 2017 15:40:39 +0200 Subject: [PATCH 004/495] add missing setStartDate and setEndDate methods (http://www.daterangepicker.com/#methods) --- types/daterangepicker/index.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/types/daterangepicker/index.d.ts b/types/daterangepicker/index.d.ts index 3846ea2472..5a4ff4534b 100644 --- a/types/daterangepicker/index.d.ts +++ b/types/daterangepicker/index.d.ts @@ -24,6 +24,9 @@ declare namespace daterangepicker { startDate: moment.Moment; endDate: moment.Moment; + + setStartDate(date: Date | moment.Moment | string): void; + setEndDate(date: Date | moment.Moment | string): void; } interface DatepickerEventObject extends JQueryEventObject { From 90a550565f61690aee3e6ca644d90b554b50dd69 Mon Sep 17 00:00:00 2001 From: Steven Masala Date: Tue, 8 Aug 2017 15:49:35 +0200 Subject: [PATCH 005/495] add name --- types/daterangepicker/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/daterangepicker/index.d.ts b/types/daterangepicker/index.d.ts index 5a4ff4534b..98c39ca85e 100644 --- a/types/daterangepicker/index.d.ts +++ b/types/daterangepicker/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for Date Range Picker v2.1.19 // Project: http://www.daterangepicker.com/ // Definitions by: SirMartin +// Steven Masala // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 From a121c465caf230faaf08e06fa3bd46890796d6b5 Mon Sep 17 00:00:00 2001 From: Steven Masala Date: Tue, 8 Aug 2017 16:00:19 +0200 Subject: [PATCH 006/495] version update --- types/daterangepicker/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/daterangepicker/index.d.ts b/types/daterangepicker/index.d.ts index 98c39ca85e..2555be11bb 100644 --- a/types/daterangepicker/index.d.ts +++ b/types/daterangepicker/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Date Range Picker v2.1.19 +// Type definitions for Date Range Picker v2.1.25 // Project: http://www.daterangepicker.com/ // Definitions by: SirMartin // Steven Masala From e99db006334eb933ebc464ed0f8f7a32a967032f Mon Sep 17 00:00:00 2001 From: Steven Masala Date: Thu, 10 Aug 2017 11:44:42 +0200 Subject: [PATCH 007/495] remove method --- types/daterangepicker/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/daterangepicker/index.d.ts b/types/daterangepicker/index.d.ts index 2555be11bb..f31f9fee6e 100644 --- a/types/daterangepicker/index.d.ts +++ b/types/daterangepicker/index.d.ts @@ -28,6 +28,7 @@ declare namespace daterangepicker { setStartDate(date: Date | moment.Moment | string): void; setEndDate(date: Date | moment.Moment | string): void; + remove(): void; } interface DatepickerEventObject extends JQueryEventObject { From 5b018e667bec1b1fcca6ad83822a9acc47c41f24 Mon Sep 17 00:00:00 2001 From: ChenX Date: Mon, 18 Sep 2017 10:32:21 +0800 Subject: [PATCH 008/495] Clean code --- types/three/three-core.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index b2fa482639..cf45c757ca 100644 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -4820,8 +4820,7 @@ export class LineSegments extends Line { } export class Mesh extends Object3D { - constructor(geometry?: Geometry, material?: Material | Material []); - constructor(geometry?: BufferGeometry, material?: Material | Material []); + constructor(geometry?: Geometry | BufferGeometry, material?: Material | Material []); geometry: Geometry|BufferGeometry; material: Material | Material[]; From ee8134843ae673269dbfcb73fefdf73a91a47f94 Mon Sep 17 00:00:00 2001 From: Cyril Gandon Date: Mon, 16 Oct 2017 10:35:26 +0200 Subject: [PATCH 009/495] angular-hotkeys: add linter, docs and tests --- types/angular-hotkeys/README.md | 4 +- .../angular-hotkeys/angular-hotkeys-tests.ts | 91 +++++++++---- types/angular-hotkeys/index.d.ts | 124 ++++++++++++++---- types/angular-hotkeys/tsconfig.json | 4 +- types/angular-hotkeys/tslint.json | 1 + 5 files changed, 169 insertions(+), 55 deletions(-) create mode 100644 types/angular-hotkeys/tslint.json diff --git a/types/angular-hotkeys/README.md b/types/angular-hotkeys/README.md index a31ed8a936..cade36b0dd 100644 --- a/types/angular-hotkeys/README.md +++ b/types/angular-hotkeys/README.md @@ -37,7 +37,7 @@ After installing a package you can import the definition file and begin using it ```ts -import * as hotkeys from '../../node_modules/@types/angular-hotkeys' +import { HotkeysProvider } from 'angular-hotkeys'; class FooController { static $inject = [ @@ -45,7 +45,7 @@ class FooController { ]; constructor( - private hotkeys: ng.hotkeys.HotkeysProvider + private hotkeys: HotkeysProvider ) { } } 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..c3dbbf3651 100644 --- a/types/angular-hotkeys/index.d.ts +++ b/types/angular-hotkeys/index.d.ts @@ -1,12 +1,11 @@ -// 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 - - -/// +// Readme written by David Valentine import * as ng from 'angular'; @@ -15,46 +14,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 new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/angular-hotkeys/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From ad69281f23ecd623b258572c4e8104d9a918bdaf Mon Sep 17 00:00:00 2001 From: Randy Patterson Jr Date: Mon, 16 Oct 2017 09:14:16 -0400 Subject: [PATCH 010/495] Add correct options for Collection.set method. Issue #18593. --- types/backbone/backbone-tests.ts | 6 ++++++ types/backbone/index.d.ts | 20 +++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/types/backbone/backbone-tests.ts b/types/backbone/backbone-tests.ts index c074ac57e5..ceb74da264 100644 --- a/types/backbone/backbone-tests.ts +++ b/types/backbone/backbone-tests.ts @@ -401,6 +401,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 { diff --git a/types/backbone/index.d.ts b/types/backbone/index.d.ts index 42a322e4c2..d278cd4716 100644 --- a/types/backbone/index.d.ts +++ b/types/backbone/index.d.ts @@ -18,6 +18,12 @@ declare namespace Backbone { merge?: boolean; } + interface CollectionSetOptions extends Silenceable { + add?: boolean; + remove?: boolean; + merge?: boolean; + } + interface HistoryOptions extends Silenceable { pushState?: boolean; root?: string; @@ -236,7 +242,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; From c30aa15761141c44f0011267bcf89b8a894adfa7 Mon Sep 17 00:00:00 2001 From: Randy Patterson Jr Date: Mon, 16 Oct 2017 09:31:50 -0400 Subject: [PATCH 011/495] Make Collection.slice method min parameter optional to match documentation. Issue #18593. --- types/backbone/backbone-tests.ts | 1 + types/backbone/index.d.ts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/types/backbone/backbone-tests.ts b/types/backbone/backbone-tests.ts index ceb74da264..659dcfefb2 100644 --- a/types/backbone/backbone-tests.ts +++ b/types/backbone/backbone-tests.ts @@ -186,6 +186,7 @@ function test_collection() { let modelsDict: _.Dictionary; let num: number; + models = books.slice(); models = books.slice(1); models = books.slice(1, 3); diff --git a/types/backbone/index.d.ts b/types/backbone/index.d.ts index d278cd4716..9bad81d0ba 100644 --- a/types/backbone/index.d.ts +++ b/types/backbone/index.d.ts @@ -270,7 +270,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 From 85fdbd170e61a0b046c87734d3f6e008ee5d479b Mon Sep 17 00:00:00 2001 From: Randy Patterson Jr Date: Mon, 16 Oct 2017 10:36:10 -0400 Subject: [PATCH 012/495] Allow sync to accept a collection as it's second argument. --- types/backbone/backbone-tests.ts | 6 ++++++ types/backbone/index.d.ts | 1 + 2 files changed, 7 insertions(+) diff --git a/types/backbone/backbone-tests.ts b/types/backbone/backbone-tests.ts index 659dcfefb2..89928dc5ed 100644 --- a/types/backbone/backbone-tests.ts +++ b/types/backbone/backbone-tests.ts @@ -418,4 +418,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 9bad81d0ba..a880b27ff8 100644 --- a/types/backbone/index.d.ts +++ b/types/backbone/index.d.ts @@ -445,6 +445,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; From cbb468143efd0ada60a7e32ca647a42f5e38f595 Mon Sep 17 00:00:00 2001 From: Randy Patterson Jr Date: Mon, 16 Oct 2017 10:44:21 -0400 Subject: [PATCH 013/495] Allow sort option for Backbone Collection.add and push. Issue #18593. --- types/backbone/backbone-tests.ts | 3 +++ types/backbone/index.d.ts | 1 + 2 files changed, 4 insertions(+) diff --git a/types/backbone/backbone-tests.ts b/types/backbone/backbone-tests.ts index 89928dc5ed..ab3a1e81ae 100644 --- a/types/backbone/backbone-tests.ts +++ b/types/backbone/backbone-tests.ts @@ -157,6 +157,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. diff --git a/types/backbone/index.d.ts b/types/backbone/index.d.ts index a880b27ff8..3278f54804 100644 --- a/types/backbone/index.d.ts +++ b/types/backbone/index.d.ts @@ -16,6 +16,7 @@ declare namespace Backbone { interface AddOptions extends Silenceable { at?: number; merge?: boolean; + sort?: boolean; } interface CollectionSetOptions extends Silenceable { From 27fd582d60a6f766044ce42a97848283de53bb39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20van=20Br=C3=BCgge?= Date: Tue, 17 Oct 2017 22:30:11 +0200 Subject: [PATCH 014/495] Add applyTo --- types/ramda/index.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index 776c074b73..9a611459d2 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -242,6 +242,13 @@ declare namespace R { * the supplied arguments. */ applySpec(obj: any): (...args: any[]) => T; + + /** + * Takes a value and applies a function to it. + * This function is also known as the thrush combinator. + */ + applyTo(el: T, fn: (t: T) => U): U; + applyTo(el: T): (fn: (t: T) => U) => U; /** * Makes an ascending comparator function out of a function that returns a value that can be compared with < and >. From 9a26cd4fb288ec2172062862227fd41fe40fde6c Mon Sep 17 00:00:00 2001 From: Cyril Gandon Date: Wed, 18 Oct 2017 11:03:56 +0200 Subject: [PATCH 015/495] remove unnecessary custom readme from the folder --- types/angular-hotkeys/README.md | 55 --------------------------------- 1 file changed, 55 deletions(-) delete mode 100644 types/angular-hotkeys/README.md diff --git a/types/angular-hotkeys/README.md b/types/angular-hotkeys/README.md deleted file mode 100644 index cade36b0dd..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 { HotkeysProvider } from 'angular-hotkeys'; - -class FooController { - static $inject = [ - 'hotkeys' - ]; - - constructor( - private hotkeys: HotkeysProvider - ) { } -} - -``` - -for a detailed explanation of the behavior of angular-hotkeys please refer to [its documentation](https://github.com/chieffancypants/angular-hotkeys/) - From 625d4a4404a818e0629cb0f9413f9d1e2498a058 Mon Sep 17 00:00:00 2001 From: Cyril Gandon Date: Wed, 18 Oct 2017 11:05:17 +0200 Subject: [PATCH 016/495] remove reference to custom readme --- types/angular-hotkeys/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/angular-hotkeys/index.d.ts b/types/angular-hotkeys/index.d.ts index c3dbbf3651..360e2cefbe 100644 --- a/types/angular-hotkeys/index.d.ts +++ b/types/angular-hotkeys/index.d.ts @@ -5,7 +5,6 @@ // Cyril Gandon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -// Readme written by David Valentine import * as ng from 'angular'; From bf50c9a7a74a5bef7c7de90e7a648bfc07ad6299 Mon Sep 17 00:00:00 2001 From: Kevin Greene Date: Wed, 18 Oct 2017 12:37:30 -0700 Subject: [PATCH 017/495] [node] Update older node types (7,6,4) for more consistency with 8 * Specifically add interfaces for reqeust headers * Make the naming of client request options consistent (ClientRequestArgs) --- types/node/v4/index.d.ts | 37 ++++++++++++++++++++++++------------- types/node/v6/index.d.ts | 35 +++++++++++++++++++++++------------ types/node/v7/index.d.ts | 34 ++++++++++++++++++++++------------ types/node/v7/node-tests.ts | 2 +- 4 files changed, 70 insertions(+), 38 deletions(-) diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index d88db82da1..59c298e328 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -565,19 +565,30 @@ declare module "http" { import * as net from "net"; import * as stream from "stream"; - export interface RequestOptions { + // incoming headers will never contain number + export interface IncomingHttpHeaders { + [header: string]: string | string[]; + } + + // outgoing headers allows numbers (as they are converted internally to strings) + export interface OutgoingHttpHeaders { + [header: string]: number | string | string[] | undefined; + } + + export interface ClientRequestArgs { 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 interface Server extends net.Server { @@ -600,8 +611,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 +621,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 +647,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 +658,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. @@ -720,7 +731,7 @@ declare module "http" { }; export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) =>void ): Server; export function createClient(port?: number, host?: string): any; - export function request(options: RequestOptions | string, callback?: (res: IncomingMessage) => void): ClientRequest; + export function request(options: ClientRequestArgs | string, callback?: (res: IncomingMessage) => void): ClientRequest; export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; export var globalAgent: Agent; } @@ -916,7 +927,7 @@ declare module "https" { SNICallback?: (servername: string) => any; } - export interface RequestOptions extends http.RequestOptions { + export interface RequestOptions extends http.ClientRequestArgs { pfx?: any; key?: any; passphrase?: string; diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 8f73bab752..1e20793cd7 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -637,19 +637,30 @@ declare module "http" { import * as net from "net"; import * as stream from "stream"; - export interface RequestOptions { + // incoming headers will never contain number + export interface IncomingHttpHeaders { + [header: string]: string | string[]; + } + + // outgoing headers allows numbers (as they are converted internally to strings) + export interface OutgoingHttpHeaders { + [header: string]: number | string | string[] | undefined; + } + + export interface ClientRequestArgs { 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 interface Server extends net.Server { @@ -673,8 +684,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 +695,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 +722,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 +736,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. @@ -798,7 +809,7 @@ declare module "http" { }; export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; export function createClient(port?: number, host?: string): any; - export function request(options: RequestOptions | string, callback?: (res: IncomingMessage) => void): ClientRequest; + export function request(options: ClientRequestArgs | string, callback?: (res: IncomingMessage) => void): ClientRequest; export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; export var globalAgent: Agent; } @@ -1323,7 +1334,7 @@ declare module "https" { SNICallback?: (servername: string, cb: (err: Error, ctx: tls.SecureContext) => any) => any; } - export interface RequestOptions extends http.RequestOptions { + export interface RequestOptions extends http.ClientRequestArgs { pfx?: any; key?: any; passphrase?: string; diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index 45df6015fe..0df238119a 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -654,17 +654,27 @@ declare module "http" { import * as net from "net"; import * as stream from "stream"; - export interface RequestOptions { + // incoming headers will never contain number + export interface IncomingHttpHeaders { + [header: string]: string | string[]; + } + + // outgoing headers allows numbers (as they are converted internally to strings) + export interface OutgoingHttpHeaders { + [header: string]: number | string | string[] | undefined; + } + + export interface ClientRequestArgs { 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; @@ -691,8 +701,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; @@ -702,7 +712,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 @@ -729,7 +739,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; @@ -743,10 +753,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. @@ -816,7 +826,7 @@ declare module "http" { }; export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; export function createClient(port?: number, host?: string): any; - export function request(options: RequestOptions | string, callback?: (res: IncomingMessage) => void): ClientRequest; + export function request(options: ClientRequestArgs | string, callback?: (res: IncomingMessage) => void): ClientRequest; export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; export var globalAgent: Agent; } @@ -1389,7 +1399,7 @@ declare module "https" { SNICallback?: (servername: string, cb: (err: Error, ctx: tls.SecureContext) => any) => any; } - export interface RequestOptions extends http.RequestOptions { + export interface RequestOptions extends http.ClientRequestArgs { pfx?: any; key?: any; passphrase?: string; diff --git a/types/node/v7/node-tests.ts b/types/node/v7/node-tests.ts index f439a83213..480280644a 100644 --- a/types/node/v7/node-tests.ts +++ b/types/node/v7/node-tests.ts @@ -1033,7 +1033,7 @@ namespace http_tests { request.abort(); } - const options: http.RequestOptions = { + const options: http.ClientRequestArgs = { timeout: 30000 }; } From 6abae6e969b629e8bd1a9006b7cceb1eaba2c1d8 Mon Sep 17 00:00:00 2001 From: Giorgio Delgado Date: Sun, 22 Oct 2017 19:37:47 -0400 Subject: [PATCH 018/495] update for v2 --- types/mock-require/index.d.ts | 32 +++++--------- types/mock-require/mock-require-tests.ts | 10 +++-- types/mock-require/tsconfig.json | 2 +- types/mock-require/tslint.json | 3 ++ types/mock-require/v1/index.d.ts | 31 ++++++++++++++ types/mock-require/v1/mock-require-tests.ts | 47 +++++++++++++++++++++ types/mock-require/v1/tsconfig.json | 23 ++++++++++ 7 files changed, 122 insertions(+), 26 deletions(-) create mode 100644 types/mock-require/tslint.json create mode 100644 types/mock-require/v1/index.d.ts create mode 100644 types/mock-require/v1/mock-require-tests.ts create mode 100644 types/mock-require/v1/tsconfig.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/mock-require/tslint.json b/types/mock-require/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/mock-require/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/mock-require/v1/index.d.ts b/types/mock-require/v1/index.d.ts new file mode 100644 index 0000000000..da5db1c07c --- /dev/null +++ b/types/mock-require/v1/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for mock-require v1.3.0 +// Project: https://github.com/boblauer/mock-require +// Definitions by: Daniel Pereira +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** Simple, intuitive mocking of Node.js modules. */ +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. + */ + 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; +} + +declare const myModule: Mock; +export = myModule; diff --git a/types/mock-require/v1/mock-require-tests.ts b/types/mock-require/v1/mock-require-tests.ts new file mode 100644 index 0000000000..2131bc56de --- /dev/null +++ b/types/mock-require/v1/mock-require-tests.ts @@ -0,0 +1,47 @@ +import mock = require('mock-require'); + +const request = () => { + console.log('http.request called'); +}; + +function testMock() { + mock('http', { + request + }); + + const http = require('http'); + http.request(); // 'http.request called' +} + +function testStop() { + mock('fs', { mockedFS: true }); + + const fs1 = require('fs'); + mock.stop('fs'); + + const fs2 = require('fs'); + fs1 === fs2; // false +} + +function testStopAll() { + mock('fs', {}); + mock('path', {}); + + const fs1 = require('fs'); + const path1 = require('path'); + + mock.stopAll(); + + const fs2 = require('fs'); + const path2 = require('path'); + + fs1 === fs2; // false + path1 === path2; // false +} + +function testReRequire() { + const fs = require('fs'); + let fileToTest = require('./fileToTest'); + mock('fs', {}); // fileToTest is still using the unmocked fs module + fileToTest = mock.reRequire('./fileToTest'); // fileToTest is now using your mock +} diff --git a/types/mock-require/v1/tsconfig.json b/types/mock-require/v1/tsconfig.json new file mode 100644 index 0000000000..1f6be404c6 --- /dev/null +++ b/types/mock-require/v1/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", + "mock-require-tests.ts" + ] +} \ No newline at end of file From 991d2f790578e0314c7dedfb1e1228f742cc62eb Mon Sep 17 00:00:00 2001 From: Sami Jaber Date: Mon, 23 Oct 2017 17:28:33 -0400 Subject: [PATCH 019/495] React-Router Link: extend LinkHTMLAttributes --- types/react-router/v2/lib/Link.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-router/v2/lib/Link.d.ts b/types/react-router/v2/lib/Link.d.ts index d90578b9f9..e86fcf2091 100644 --- a/types/react-router/v2/lib/Link.d.ts +++ b/types/react-router/v2/lib/Link.d.ts @@ -7,7 +7,7 @@ type Link = Link.Link; export default Link; declare namespace Link { - interface LinkProps extends React.HTMLAttributes { + interface LinkProps extends React.LinkHTMLAttributes { activeStyle?: React.CSSProperties; activeClassName?: string; onlyActiveOnIndex?: boolean; From 63e6236af8cdb8e278eeaee00556097db01d130e Mon Sep 17 00:00:00 2001 From: Kevin Greene Date: Mon, 23 Oct 2017 15:32:52 -0700 Subject: [PATCH 020/495] Fix to just make ClientRequestArgs an alias of RequestOptions --- types/node/v4/index.d.ts | 8 +++++--- types/node/v6/index.d.ts | 8 +++++--- types/node/v7/index.d.ts | 8 +++++--- 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index 59c298e328..45f882ebd4 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -575,7 +575,7 @@ declare module "http" { [header: string]: number | string | string[] | undefined; } - export interface ClientRequestArgs { + export interface RequestOptions { protocol?: string; host?: string; hostname?: string; @@ -591,6 +591,8 @@ declare module "http" { timeout?: number; } + export type ClientRequestArgs = RequestOptions + export interface Server extends net.Server { setTimeout(msecs: number, callback: Function): void; maxHeadersCount: number; @@ -731,7 +733,7 @@ declare module "http" { }; export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) =>void ): Server; export function createClient(port?: number, host?: string): any; - export function request(options: ClientRequestArgs | string, callback?: (res: IncomingMessage) => void): ClientRequest; + export function request(options: RequestOptions | string, callback?: (res: IncomingMessage) => void): ClientRequest; export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; export var globalAgent: Agent; } @@ -927,7 +929,7 @@ declare module "https" { SNICallback?: (servername: string) => any; } - export interface RequestOptions extends http.ClientRequestArgs { + export interface RequestOptions extends http.RequestOptions { pfx?: any; key?: any; passphrase?: string; diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 1e20793cd7..3f0379cc5a 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -647,7 +647,7 @@ declare module "http" { [header: string]: number | string | string[] | undefined; } - export interface ClientRequestArgs { + export interface RequestOptions { protocol?: string; host?: string; hostname?: string; @@ -663,6 +663,8 @@ declare module "http" { timeout?: number; } + export type ClientRequestArgs = RequestOptions + export interface Server extends net.Server { setTimeout(msecs: number, callback: Function): void; maxHeadersCount: number; @@ -809,7 +811,7 @@ declare module "http" { }; export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; export function createClient(port?: number, host?: string): any; - export function request(options: ClientRequestArgs | string, callback?: (res: IncomingMessage) => void): ClientRequest; + export function request(options: RequestOptions | string, callback?: (res: IncomingMessage) => void): ClientRequest; export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; export var globalAgent: Agent; } @@ -1334,7 +1336,7 @@ declare module "https" { SNICallback?: (servername: string, cb: (err: Error, ctx: tls.SecureContext) => any) => any; } - export interface RequestOptions extends http.ClientRequestArgs { + export interface RequestOptions extends http.RequestOptions { pfx?: any; key?: any; passphrase?: string; diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index 0df238119a..3ed2634aa9 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -664,7 +664,7 @@ declare module "http" { [header: string]: number | string | string[] | undefined; } - export interface ClientRequestArgs { + export interface RequestOptions { protocol?: string; host?: string; hostname?: string; @@ -680,6 +680,8 @@ declare module "http" { timeout?: number; } + export type ClientRequestArgs = RequestOptions + export interface Server extends net.Server { setTimeout(msecs: number, callback: Function): void; maxHeadersCount: number; @@ -826,7 +828,7 @@ declare module "http" { }; export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; export function createClient(port?: number, host?: string): any; - export function request(options: ClientRequestArgs | string, callback?: (res: IncomingMessage) => void): ClientRequest; + export function request(options: RequestOptions | string, callback?: (res: IncomingMessage) => void): ClientRequest; export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; export var globalAgent: Agent; } @@ -1399,7 +1401,7 @@ declare module "https" { SNICallback?: (servername: string, cb: (err: Error, ctx: tls.SecureContext) => any) => any; } - export interface RequestOptions extends http.ClientRequestArgs { + export interface RequestOptions extends http.RequestOptions { pfx?: any; key?: any; passphrase?: string; From f0ec8d77bf21d75e8a70db02e38db106967f8357 Mon Sep 17 00:00:00 2001 From: Ricardo Lopez Date: Mon, 23 Oct 2017 19:14:24 -0500 Subject: [PATCH 021/495] make nconf Provider options in constructor optional --- types/nconf/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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[]; From 87364923db0d4ddc0cfb6f9498fb18c05ad5a2a9 Mon Sep 17 00:00:00 2001 From: Giorgio Delgado Date: Mon, 23 Oct 2017 21:06:40 -0400 Subject: [PATCH 022/495] remove v1 typedefs --- types/mock-require/v1/index.d.ts | 31 -------------- types/mock-require/v1/mock-require-tests.ts | 47 --------------------- types/mock-require/v1/tsconfig.json | 23 ---------- 3 files changed, 101 deletions(-) delete mode 100644 types/mock-require/v1/index.d.ts delete mode 100644 types/mock-require/v1/mock-require-tests.ts delete mode 100644 types/mock-require/v1/tsconfig.json diff --git a/types/mock-require/v1/index.d.ts b/types/mock-require/v1/index.d.ts deleted file mode 100644 index da5db1c07c..0000000000 --- a/types/mock-require/v1/index.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Type definitions for mock-require v1.3.0 -// Project: https://github.com/boblauer/mock-require -// Definitions by: Daniel Pereira -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -/** Simple, intuitive mocking of Node.js modules. */ -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. - */ - 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; -} - -declare const myModule: Mock; -export = myModule; diff --git a/types/mock-require/v1/mock-require-tests.ts b/types/mock-require/v1/mock-require-tests.ts deleted file mode 100644 index 2131bc56de..0000000000 --- a/types/mock-require/v1/mock-require-tests.ts +++ /dev/null @@ -1,47 +0,0 @@ -import mock = require('mock-require'); - -const request = () => { - console.log('http.request called'); -}; - -function testMock() { - mock('http', { - request - }); - - const http = require('http'); - http.request(); // 'http.request called' -} - -function testStop() { - mock('fs', { mockedFS: true }); - - const fs1 = require('fs'); - mock.stop('fs'); - - const fs2 = require('fs'); - fs1 === fs2; // false -} - -function testStopAll() { - mock('fs', {}); - mock('path', {}); - - const fs1 = require('fs'); - const path1 = require('path'); - - mock.stopAll(); - - const fs2 = require('fs'); - const path2 = require('path'); - - fs1 === fs2; // false - path1 === path2; // false -} - -function testReRequire() { - const fs = require('fs'); - let fileToTest = require('./fileToTest'); - mock('fs', {}); // fileToTest is still using the unmocked fs module - fileToTest = mock.reRequire('./fileToTest'); // fileToTest is now using your mock -} diff --git a/types/mock-require/v1/tsconfig.json b/types/mock-require/v1/tsconfig.json deleted file mode 100644 index 1f6be404c6..0000000000 --- a/types/mock-require/v1/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "mock-require-tests.ts" - ] -} \ No newline at end of file From acf639ab3b31fea2f9e7f66ac4189e9ddedbb1b4 Mon Sep 17 00:00:00 2001 From: york yao Date: Tue, 24 Oct 2017 12:19:34 +0800 Subject: [PATCH 023/495] improve types of ioredis --- types/ioredis/index.d.ts | 1282 +++++++++++++++++--------------- types/ioredis/ioredis-tests.ts | 60 +- types/ioredis/tslint.json | 1 + 3 files changed, 735 insertions(+), 608 deletions(-) create mode 100644 types/ioredis/tslint.json diff --git a/types/ioredis/index.d.ts b/types/ioredis/index.d.ts index 8353b4e563..d80f4ed30e 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,732 @@ /// 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; } 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 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 +775,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 +804,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 +812,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 +828,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..55e3229eb4 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,36 @@ 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(() => { /* ... */ }); diff --git a/types/ioredis/tslint.json b/types/ioredis/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ioredis/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 14cb8715317c93d60f7faa93563eb53edabded5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pablo=20Rodr=C3=ADguez?= Date: Tue, 24 Oct 2017 15:59:19 +0200 Subject: [PATCH 024/495] Update knex to preserve type information Previously knex would lose type information when callink knex.transaction. --- types/knex/index.d.ts | 38 +++++++++++++++++++------------------- types/knex/knex-tests.ts | 15 ++++++++++++--- 2 files changed, 31 insertions(+), 22 deletions(-) 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(''); From 3a86a2b2c5f9cea00ae593e76bae204c2cb69264 Mon Sep 17 00:00:00 2001 From: Kevin Greene Date: Tue, 24 Oct 2017 09:02:06 -0700 Subject: [PATCH 025/495] [node] Fix linting errors --- types/node/v4/index.d.ts | 42 -------------------------- types/node/v6/index.d.ts | 64 +++++++--------------------------------- types/node/v7/index.d.ts | 60 ++++++------------------------------- 3 files changed, 20 insertions(+), 146 deletions(-) diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index 45f882ebd4..e3c95673e1 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; /** @@ -1589,15 +1581,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; @@ -1642,79 +1630,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; @@ -1749,8 +1720,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; @@ -1759,7 +1728,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. */ @@ -1769,7 +1737,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. */ @@ -1777,15 +1744,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; @@ -1793,7 +1756,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; @@ -1802,7 +1764,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; @@ -1923,9 +1884,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/v6/index.d.ts b/types/node/v6/index.d.ts index 3f0379cc5a..67835ca24c 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; /** @@ -2367,15 +2359,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; @@ -2420,79 +2408,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; @@ -2525,8 +2496,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; @@ -2535,7 +2504,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. */ @@ -2545,7 +2513,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. */ @@ -2553,15 +2520,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; @@ -2569,7 +2532,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; @@ -2578,7 +2540,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; @@ -2819,9 +2780,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; /** @@ -3020,7 +2978,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 }; /** @@ -3039,8 +2997,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; /** @@ -3049,8 +3007,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; @@ -3064,13 +3022,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; /** @@ -3099,9 +3057,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; @@ -3112,8 +3070,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/index.d.ts b/types/node/v7/index.d.ts index 3ed2634aa9..afeb025d93 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -166,8 +166,6 @@ declare var Buffer: { prototype: Buffer; /** * Allocates a new Buffer using an {array} of octets. - * - * @param array */ from(array: any[]): Buffer; /** @@ -177,22 +175,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; /** @@ -2500,15 +2492,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; @@ -2553,79 +2541,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; @@ -2659,8 +2630,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; @@ -2669,7 +2638,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. */ @@ -2679,7 +2647,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. */ @@ -2687,15 +2654,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; @@ -2703,7 +2666,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; @@ -2712,7 +2674,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; @@ -2953,9 +2914,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; /** @@ -3173,7 +3131,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 }; /** @@ -3192,7 +3150,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; @@ -3202,15 +3160,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; /** @@ -3245,9 +3203,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; @@ -3258,8 +3216,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; From 06a8ff4a13577f018d33486b20ab2e32f09000c7 Mon Sep 17 00:00:00 2001 From: Kevin Greene Date: Tue, 24 Oct 2017 11:14:44 -0700 Subject: [PATCH 026/495] Add tests for RequestOptions and ClientRequestArgs --- types/node/v4/node-tests.ts | 8 ++++++++ types/node/v6/node-tests.ts | 8 ++++++++ types/node/v7/node-tests.ts | 6 +++++- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/types/node/v4/node-tests.ts b/types/node/v4/node-tests.ts index 05b20806cd..3ba0db2851 100644 --- a/types/node/v4/node-tests.ts +++ b/types/node/v4/node-tests.ts @@ -499,6 +499,14 @@ namespace http_tests { request.setNoDelay(true); request.abort(); } + + const reqOptions: http.RequestOptions = { + timeout: 30000 + }; + + const clientArgs: http.ClientRequestArgs = { + timeout: 30000 + }; } ////////////////////////////////////////////////////// diff --git a/types/node/v6/node-tests.ts b/types/node/v6/node-tests.ts index 15c36ef058..c3cced9921 100644 --- a/types/node/v6/node-tests.ts +++ b/types/node/v6/node-tests.ts @@ -935,6 +935,14 @@ namespace http_tests { request.setNoDelay(true); request.abort(); } + + const reqOptions: http.RequestOptions = { + timeout: 30000 + }; + + const clientArgs: http.ClientRequestArgs = { + timeout: 30000 + }; } ////////////////////////////////////////////////////// diff --git a/types/node/v7/node-tests.ts b/types/node/v7/node-tests.ts index 480280644a..89f49817c7 100644 --- a/types/node/v7/node-tests.ts +++ b/types/node/v7/node-tests.ts @@ -1033,7 +1033,11 @@ namespace http_tests { request.abort(); } - const options: http.ClientRequestArgs = { + const reqOptions: http.RequestOptions = { + timeout: 30000 + }; + + const clientArgs: http.ClientRequestArgs = { timeout: 30000 }; } From f7f88b82ebf3508096a1b89e6b63aa664c823cae Mon Sep 17 00:00:00 2001 From: Tom Shen Date: Tue, 24 Oct 2017 15:06:59 -0400 Subject: [PATCH 027/495] Fix react-list export --- types/react-list/index.d.ts | 30 +++++++++++++-------------- types/react-list/react-list-tests.tsx | 3 +-- 2 files changed, 15 insertions(+), 18 deletions(-) diff --git a/types/react-list/index.d.ts b/types/react-list/index.d.ts index 9760419fff..30371fc35b 100644 --- a/types/react-list/index.d.ts +++ b/types/react-list/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for react-list 0.8 // Project: https://github.com/orgsync/react-list -// Definitions by: Yifei Yan +// Definitions by: Yifei Yan , Tom Shen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -8,22 +8,14 @@ import { Component, Props } from "react"; -export as namespace ReactList; -/*~ If this module has methods, declare them as functions like so. - */ -export function scrollTo(index: number): void; -export function scrollAround(index: number): void; -export function getVisibleRange(): number[]; +type ItemRenderer = (index: number, key: number | string) => JSX.Element; +type ItemsRenderer = (items: JSX.Element[], ref: string) => JSX.Element; +type ItemSizeEstimator = (index: number, cache: {}) => number; +type ItemSizeGetter = (index: number) => number; +type ScrollParentGetter = () => JSX.Element; -/*~ You can declare types that are available via importing the module */ -export type ItemRenderer = (index: number, key: number | string) => JSX.Element; -export type ItemsRenderer = (items: JSX.Element[], ref: string) => JSX.Element; -export type ItemSizeEstimator = (index: number, cache: {}) => number; -export type ItemSizeGetter = (index: number) => number; -export type ScrollParentGetter = () => JSX.Element; - -export interface ReactListProps extends Props { +interface ReactListProps extends Props { axis?: 'x' | 'y'; initialIndex?: number; itemRenderer?: ItemRenderer; @@ -40,4 +32,10 @@ export interface ReactListProps extends Props { useTranslate3d?: boolean; } -export default class ReactList extends Component {} +declare class ReactList extends Component { + scrollTo(index: number): void; + scrollAround(index: number): void; + getVisibleRange(): number[]; +} +declare namespace ReactList { } +export = ReactList; diff --git a/types/react-list/react-list-tests.tsx b/types/react-list/react-list-tests.tsx index 26d2781b02..f02b1643a5 100644 --- a/types/react-list/react-list-tests.tsx +++ b/types/react-list/react-list-tests.tsx @@ -1,6 +1,5 @@ import * as React from "react"; -// import * as ReactDOM from "react-dom"; -import ReactList from "react-list"; +import * as ReactList from "react-list"; const renderItem = (index: number, key: number) =>
From f2c89fb7cb0ac3018e1d42e6dd0c74b887482e5a Mon Sep 17 00:00:00 2001 From: Oliver Joseph Ash Date: Wed, 25 Oct 2017 14:18:46 +0100 Subject: [PATCH 028/495] React Router v2: `RouteComponentProps` non-optional `location` and `params` --- types/react-router/v2/lib/Router.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/react-router/v2/lib/Router.d.ts b/types/react-router/v2/lib/Router.d.ts index a7dff58369..6611fa55a9 100644 --- a/types/react-router/v2/lib/Router.d.ts +++ b/types/react-router/v2/lib/Router.d.ts @@ -83,8 +83,8 @@ declare namespace Router { interface RouteComponentProps { history?: History; - location?: Location; - params?: P; + location: Location; + params: P; route?: PlainRoute; routeParams?: R; routes?: PlainRoute[]; From 62f9c1b54da536811ec1ce1a0cbc8bc650a0b5d8 Mon Sep 17 00:00:00 2001 From: tlent Date: Wed, 25 Oct 2017 15:47:28 -0400 Subject: [PATCH 029/495] Format existing code --- types/opn/index.d.ts | 46 ++++++++++++++++++++++------------------- types/opn/opn-tests.ts | 24 ++++++++++----------- types/opn/tsconfig.json | 15 ++++---------- 3 files changed, 40 insertions(+), 45 deletions(-) diff --git a/types/opn/index.d.ts b/types/opn/index.d.ts index 78a1043442..511fbbd82d 100644 --- a/types/opn/index.d.ts +++ b/types/opn/index.d.ts @@ -6,27 +6,27 @@ /// -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 + * + * 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 + * + * 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. */ @@ -34,11 +34,11 @@ 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 + * + * 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. */ @@ -46,16 +46,20 @@ 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 + * + * 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; + ( + target: string, + options: Opn.Options, + callback: (err: Error) => void + ): cp.ChildProcess; } declare var opn: DefaultFunction; @@ -64,15 +68,15 @@ export = opn; declare namespace Opn { export interface Options { /** - * Wait for the opened app to exit before calling the `callback`. + * Wait for the opened app to exit before calling the `callback`. * If `false` it's called immediately when opening the app. * On Windows you have to explicitly specify an app for it to be able to wait. */ 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. + * 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[]; diff --git a/types/opn/opn-tests.ts b/types/opn/opn-tests.ts index 33a043de9f..204526bdad 100644 --- a/types/opn/opn-tests.ts +++ b/types/opn/opn-tests.ts @@ -1,18 +1,16 @@ - - -import * as opn from "opn"; +import * as opn from 'opn'; var errorCallback: (err: Error) => void; -opn("foo"); -opn("foo", errorCallback); +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' }); +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' }, errorCallback); +opn('foo', { app: ['bar', '--arg'] }, errorCallback); +opn('foo', { app: 'bar', wait: false }, errorCallback); +opn('foo', { app: ['bar', '--arg'], wait: false }, errorCallback); diff --git a/types/opn/tsconfig.json b/types/opn/tsconfig.json index 9c2829989d..6feeadec2b 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, "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"] +} From c11f6d661d898d14959563be6e757f4c628848f4 Mon Sep 17 00:00:00 2001 From: tlent Date: Wed, 25 Oct 2017 16:56:34 -0400 Subject: [PATCH 030/495] Enable disabled tslint rules and fix linter issues --- types/opn/index.d.ts | 80 ++++++++++++------------------------------ types/opn/opn-tests.ts | 6 ++-- types/opn/tslint.json | 78 +--------------------------------------- 3 files changed, 27 insertions(+), 137 deletions(-) diff --git a/types/opn/index.d.ts b/types/opn/index.d.ts index 511fbbd82d..afbf34bb38 100644 --- a/types/opn/index.d.ts +++ b/types/opn/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for opn 3.0.2 +// Type definitions for opn 3.0 // Project: https://github.com/sindresorhus/opn // Definitions by: Shinnosuke Watanabe , // Maxime LUCE @@ -8,65 +8,31 @@ 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 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. + */ +declare function opn( + target: string, + options?: Opn.Options, + callback?: (err: Error) => void +): cp.ChildProcess; + 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. diff --git a/types/opn/opn-tests.ts b/types/opn/opn-tests.ts index 204526bdad..5692dd4e89 100644 --- a/types/opn/opn-tests.ts +++ b/types/opn/opn-tests.ts @@ -1,9 +1,9 @@ -import * as opn from 'opn'; +import opn = require('opn'); -var errorCallback: (err: Error) => void; +const errorCallback = (err: Error) => {}; opn('foo'); -opn('foo', errorCallback); +opn('foo', null, errorCallback); opn('foo', { app: 'bar' }); opn('foo', { app: ['bar', '--arg'] }); 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" } From 4998c08085b098234917df96cae8e7bb8b278f3f Mon Sep 17 00:00:00 2001 From: tlent Date: Wed, 25 Oct 2017 16:56:57 -0400 Subject: [PATCH 031/495] Enable strictNullChecks --- types/opn/tsconfig.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/opn/tsconfig.json b/types/opn/tsconfig.json index 6feeadec2b..2a51fff8ca 100644 --- a/types/opn/tsconfig.json +++ b/types/opn/tsconfig.json @@ -4,7 +4,7 @@ "lib": ["es6"], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": ["../"], From a83c5527660bf19c9ba116762df9372b354eb381 Mon Sep 17 00:00:00 2001 From: tlent Date: Wed, 25 Oct 2017 17:36:31 -0400 Subject: [PATCH 032/495] Update for opn version 5.1 --- types/opn/index.d.ts | 33 +++++++++++++++++---------------- types/opn/opn-tests.ts | 16 +++++----------- 2 files changed, 22 insertions(+), 27 deletions(-) diff --git a/types/opn/index.d.ts b/types/opn/index.d.ts index afbf34bb38..e4e1416f20 100644 --- a/types/opn/index.d.ts +++ b/types/opn/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for opn 3.0 +// 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 /// @@ -15,36 +16,36 @@ import * as cp from 'child_process'; export = opn; /** - * Uses the command open on OS X, start on Windows and xdg-open on other platforms. + * 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. + * 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. 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. + * @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, - callback?: (err: Error) => void -): cp.ChildProcess; + options?: Opn.Options +): Promise; declare namespace Opn { 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. + * 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 5692dd4e89..ecf088037d 100644 --- a/types/opn/opn-tests.ts +++ b/types/opn/opn-tests.ts @@ -2,15 +2,9 @@ import opn = require('opn'); const errorCallback = (err: Error) => {}; -opn('foo'); -opn('foo', null, errorCallback); +opn('foo'); // $ExpectType Promise -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 From 9c61a0ccf37180a82c1b6468da80dd2414291d7e Mon Sep 17 00:00:00 2001 From: tlent Date: Wed, 25 Oct 2017 17:49:21 -0400 Subject: [PATCH 033/495] Remove unnecessary errorCallback --- types/opn/opn-tests.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/types/opn/opn-tests.ts b/types/opn/opn-tests.ts index ecf088037d..c2956f2546 100644 --- a/types/opn/opn-tests.ts +++ b/types/opn/opn-tests.ts @@ -1,7 +1,5 @@ import opn = require('opn'); -const errorCallback = (err: Error) => {}; - opn('foo'); // $ExpectType Promise opn('foo', { app: 'bar' }); // $ExpectType Promise From c6d20ce0974e7eedf4c537e9800d1eac39d6f928 Mon Sep 17 00:00:00 2001 From: tlent Date: Wed, 25 Oct 2017 17:55:36 -0400 Subject: [PATCH 034/495] Fix minor comment issues --- types/opn/index.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/types/opn/index.d.ts b/types/opn/index.d.ts index e4e1416f20..2a7c5afe25 100644 --- a/types/opn/index.d.ts +++ b/types/opn/index.d.ts @@ -18,12 +18,13 @@ 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 + * 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. + * 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( From 136a9bd82a7787e3a8557f471cbe12d31857f01e Mon Sep 17 00:00:00 2001 From: Martin Spencer Date: Thu, 26 Oct 2017 10:37:25 +0200 Subject: [PATCH 035/495] meta key should be optional in the Action interface --- types/redux-first-router/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/redux-first-router/index.d.ts b/types/redux-first-router/index.d.ts index 89be27f524..1480292935 100644 --- a/types/redux-first-router/index.d.ts +++ b/types/redux-first-router/index.d.ts @@ -114,7 +114,7 @@ export interface Meta { export interface Action { type: string; payload: Payload; - meta: Meta; + meta?: Meta; query?: object; navKey?: Nullable; } From 8cf32b0b40ac2f0879fa4b696535cd61702c2d13 Mon Sep 17 00:00:00 2001 From: Martin Spencer Date: Thu, 26 Oct 2017 10:47:58 +0200 Subject: [PATCH 036/495] Payload key in Action interface is optional --- types/redux-first-router/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/redux-first-router/index.d.ts b/types/redux-first-router/index.d.ts index 1480292935..085bf9b638 100644 --- a/types/redux-first-router/index.d.ts +++ b/types/redux-first-router/index.d.ts @@ -113,7 +113,7 @@ export interface Meta { export interface Action { type: string; - payload: Payload; + payload?: Payload; meta?: Meta; query?: object; navKey?: Nullable; From 07225f5d85fb63f8d17efc005045789e4ff5b924 Mon Sep 17 00:00:00 2001 From: Martin Spencer Date: Thu, 26 Oct 2017 10:52:56 +0200 Subject: [PATCH 037/495] updated version number --- types/redux-first-router/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/redux-first-router/index.d.ts b/types/redux-first-router/index.d.ts index 085bf9b638..66293012b0 100644 --- a/types/redux-first-router/index.d.ts +++ b/types/redux-first-router/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for redux-first-router 1.9 +// Type definitions for redux-first-router 1.10 // Project: https://github.com/faceyspacey/redux-first-router#readme // Definitions by: Valbrand // viggyfresh From 2efbb655a4c82906c87da31cb80a0f879e1b7dc1 Mon Sep 17 00:00:00 2001 From: Jussi Rantala Date: Thu, 26 Oct 2017 15:59:58 +0300 Subject: [PATCH 038/495] Added transportOptions in connectOpts, removed extraHeaders (not working) --- types/socket.io-client/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/socket.io-client/index.d.ts b/types/socket.io-client/index.d.ts index f4f14c41c6..75f313a3a6 100644 --- a/types/socket.io-client/index.d.ts +++ b/types/socket.io-client/index.d.ts @@ -617,9 +617,9 @@ declare namespace SocketIOClient { onlyBinaryUpgrades?: boolean; /** - * Header options for Node.js client + * Transport options for Node.js client (headers etc) */ - extraHeaders?: Object; + transportOptions?: Object; /** * (SSL) Certificate, Private key and CA certificates to use for SSL. From e442e87a8a12b96df9de2995278e0715e196aad2 Mon Sep 17 00:00:00 2001 From: Jim Cummins Date: Thu, 26 Oct 2017 11:25:16 -0500 Subject: [PATCH 039/495] fontfaceobserver: union with null in load --- types/fontfaceobserver/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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" { From 79f8957bbfea6648a4001c3aef088b374aab51c5 Mon Sep 17 00:00:00 2001 From: Matt Bishop Date: Mon, 16 Oct 2017 21:18:34 -0700 Subject: [PATCH 040/495] Added missing methods and tests to faker 4.1 --- types/faker/faker-tests.ts | 84 +++++++++++++++++++++++++++++++++++++- types/faker/index.d.ts | 15 ++++--- 2 files changed, 90 insertions(+), 9 deletions(-) diff --git a/types/faker/faker-tests.ts b/types/faker/faker-tests.ts index 5fb6a53746..09b564b607 100644 --- a/types/faker/faker-tests.ts +++ b/types/faker/faker-tests.ts @@ -63,6 +63,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 +88,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(); @@ -185,12 +190,15 @@ 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" ); @@ -199,7 +207,81 @@ resultStr = faker.system.commonFileType(); resultStr = faker.system.commonFileExt(); resultStr = faker.system.fileType(); 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..379c0eb900 100644 --- a/types/faker/index.d.ts +++ b/types/faker/index.d.ts @@ -64,6 +64,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; }; @@ -80,6 +81,8 @@ declare namespace Faker { currencyName(): string; currencySymbol(): string; bitcoinAddress(): string; + ethereumAddress(): string; + iban(formatted? :boolean): string bic(): string }; @@ -107,7 +110,6 @@ declare namespace Faker { createTransaction(): Faker.Transaction; }; - image: { image(): string; avatar(): string; @@ -186,11 +188,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 +204,8 @@ declare namespace Faker { commonFileExt(): string; fileType(): string; fileExt(mimeType: string): string; - //directoryPath(): string; - //filePath(): string; + directoryPath(): string; + filePath(): string; semver(): string; }; @@ -315,10 +318,6 @@ declare module "faker/locale/de_CH" { export = fakerStatic; } -declare module "faker/locale/el_GR" { - export = fakerStatic; -} - declare module "faker/locale/en" { export = fakerStatic; } From 068de21b0363dab93c8b91126c358d8cd9d0a303 Mon Sep 17 00:00:00 2001 From: Matt Bishop Date: Mon, 16 Oct 2017 21:25:20 -0700 Subject: [PATCH 041/495] Addint tslint and fixed related errors Added "no-declare-current-package" override because I can't figure out how to re-export interface-only exports from one module in another. --- types/faker/faker-tests.ts | 15 ++++++--------- types/faker/index.d.ts | 21 ++++++++++++--------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/types/faker/faker-tests.ts b/types/faker/faker-tests.ts index 09b564b607..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(); @@ -101,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#'); @@ -172,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(); @@ -184,7 +181,7 @@ 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(); @@ -200,13 +197,13 @@ 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(); diff --git a/types/faker/index.d.ts b/types/faker/index.d.ts index 379c0eb900..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 { @@ -75,14 +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 + iban(formatted?: boolean): string bic(): string }; @@ -104,10 +107,10 @@ 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: { From 3373e24ff8b4531eb3370f1435470b98425410f3 Mon Sep 17 00:00:00 2001 From: Borek Bernard Date: Fri, 27 Oct 2017 01:26:54 +0200 Subject: [PATCH 042/495] All the interfaces and types are now exported as well --- types/execa/index.d.ts | 100 +++++++++++++++++++++-------------------- 1 file changed, 51 insertions(+), 49 deletions(-) diff --git a/types/execa/index.d.ts b/types/execa/index.d.ts index 84c6939798..620f20aad4 100644 --- a/types/execa/index.d.ts +++ b/types/execa/index.d.ts @@ -1,63 +1,65 @@ -// 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 +// TypeScript Version: 2.5 /// 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 { - function stdout(file: string, options?: Partial): Promise; - function stdout(file: string, args?: string[], options?: Partial): Promise; - function stderr(file: string, options?: Partial): Promise; - function stderr(file: string, args?: string[], options?: Partial): Promise; - function shell(command: string, options?: Partial): ExecaChildProcess; - function sync(file: string, options?: Partial): ExecaReturns; - function sync(file: string, args?: string[], options?: Partial): ExecaReturns; - function shellSync(command: string, options?: Partial): ExecaReturns; + + export type StdIOOption = 'pipe' | 'ipc' | 'ignore' | number | Stream | undefined | null; + + export 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; + } + + export type Options = SpawnOptions & ExecaOptions & ExecOptions; + export type SyncOptions = SpawnSyncOptions & ExecaOptions & ExecOptions; + + export interface ExecaReturns { + cmd: string; + code: number; + failed: boolean; + killed: boolean; + signal: string | null; + stderr: string; + stdout: string; + timedOut: boolean; + } + + export type ExecaError = Error & ExecaReturns; + + export interface ExecaChildPromise { + catch(onrejected?: ((reason: ExecaError) => TResult | PromiseLike) | null): Promise; + } + export type ExecaChildProcess = ChildProcess & ExecaChildPromise & Promise; + + export function stdout(file: string, options?: Partial): Promise; + export function stdout(file: string, args?: string[], options?: Partial): Promise; + export function stderr(file: string, options?: Partial): Promise; + export function stderr(file: string, args?: string[], options?: Partial): Promise; + export function shell(command: string, options?: Partial): ExecaChildProcess; + export function sync(file: string, options?: Partial): ExecaReturns; + export function sync(file: string, args?: string[], options?: Partial): ExecaReturns; + export function shellSync(command: string, options?: Partial): ExecaReturns; } export = execa; From ce4efbacde57b78b633e31b9c51d89530811be5c Mon Sep 17 00:00:00 2001 From: Borek Bernard Date: Fri, 27 Oct 2017 01:36:30 +0200 Subject: [PATCH 043/495] Reverting "TypeScript Version" to 2.3 (2.5 was failing the build) --- types/execa/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/execa/index.d.ts b/types/execa/index.d.ts index 620f20aad4..1e692cbc23 100644 --- a/types/execa/index.d.ts +++ b/types/execa/index.d.ts @@ -4,7 +4,7 @@ // BendingBender // Borek Bernard // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.5 +// TypeScript Version: 2.3 /// From 4bf7b36a66613aa2879c0b4916bba40b411e162b Mon Sep 17 00:00:00 2001 From: Behind The Math Date: Thu, 26 Oct 2017 22:42:00 -0400 Subject: [PATCH 044/495] [xml2js] Add processors to the main xml2js object --- types/xml2js/index.d.ts | 4 ++++ types/xml2js/xml2js-tests.ts | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/types/xml2js/index.d.ts b/types/xml2js/index.d.ts index 59af909a09..30465ae8d5 100644 --- a/types/xml2js/index.d.ts +++ b/types/xml2js/index.d.ts @@ -4,10 +4,12 @@ // Jason McNeil // Christopher Currens // Edward Hinkle +// Behind The Math // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// import { EventEmitter } from 'events'; +import * as processors from './lib/processors'; export function parseString(xml: convertableToString, callback: (err: any, result: any) => void): void; export function parseString(xml: convertableToString, options: OptionsV2, callback: (err: any, result: any) => void): void; @@ -76,3 +78,5 @@ export interface OptionsV2 extends Options { export interface convertableToString { toString(): string; } + +export { processors }; diff --git a/types/xml2js/xml2js-tests.ts b/types/xml2js/xml2js-tests.ts index 4ee1c04e5a..d3298dbf4c 100644 --- a/types/xml2js/xml2js-tests.ts +++ b/types/xml2js/xml2js-tests.ts @@ -33,7 +33,7 @@ xml2js.parseString('Hello xml2js!', { }, (err: any, result: any) => { }); xml2js.parseString('Hello xml2js!', { - attrNameProcessors: [processors.firstCharLowerCase], + attrNameProcessors: [processors.firstCharLowerCase, xml2js.processors.normalize], attrValueProcessors: [processors.normalize], tagNameProcessors: [processors.stripPrefix], valueProcessors: [processors.parseBooleans, processors.parseNumbers] From df9c373de25f72876ab854ab824202db55837148 Mon Sep 17 00:00:00 2001 From: Kevin Greene Date: Thu, 26 Oct 2017 22:30:27 -0700 Subject: [PATCH 045/495] Make HttpHeader types more specific --- types/node/v4/index.d.ts | 12 ++++++++---- types/node/v6/index.d.ts | 12 ++++++++---- types/node/v7/index.d.ts | 12 ++++++++---- 3 files changed, 24 insertions(+), 12 deletions(-) diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index e3c95673e1..431cb7d07c 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -558,13 +558,17 @@ declare module "http" { import * as stream from "stream"; // incoming headers will never contain number - export interface IncomingHttpHeaders { - [header: string]: string | string[]; + export type IncomingHttpHeaders = { + [header: string]: string + } & { + 'set-cookie'?: string[] } // outgoing headers allows numbers (as they are converted internally to strings) - export interface OutgoingHttpHeaders { - [header: string]: number | string | string[] | undefined; + export type OutgoingHttpHeaders = { + [header: string]: number | string + } & { + 'set-cookie'?: string[] } export interface RequestOptions { diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 67835ca24c..a6d3d54b5b 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -630,13 +630,17 @@ declare module "http" { import * as stream from "stream"; // incoming headers will never contain number - export interface IncomingHttpHeaders { - [header: string]: string | string[]; + export type IncomingHttpHeaders = { + [header: string]: string + } & { + 'set-cookie'?: string[] } // outgoing headers allows numbers (as they are converted internally to strings) - export interface OutgoingHttpHeaders { - [header: string]: number | string | string[] | undefined; + export type OutgoingHttpHeaders = { + [header: string]: number | string + } & { + 'set-cookie'?: string[] } export interface RequestOptions { diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index afeb025d93..fae6d5700e 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -647,13 +647,17 @@ declare module "http" { import * as stream from "stream"; // incoming headers will never contain number - export interface IncomingHttpHeaders { - [header: string]: string | string[]; + export type IncomingHttpHeaders = { + [header: string]: string + } & { + 'set-cookie'?: string[] } // outgoing headers allows numbers (as they are converted internally to strings) - export interface OutgoingHttpHeaders { - [header: string]: number | string | string[] | undefined; + export type OutgoingHttpHeaders = { + [header: string]: number | string + } & { + 'set-cookie'?: string[] } export interface RequestOptions { From 018993aa6dd0d7f21940840e244a3eb937cbe87a Mon Sep 17 00:00:00 2001 From: Borek Bernard Date: Fri, 27 Oct 2017 12:34:36 +0200 Subject: [PATCH 046/495] Fixed dtslint issues --- types/execa/index.d.ts | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/types/execa/index.d.ts b/types/execa/index.d.ts index 1e692cbc23..ee33bea59e 100644 --- a/types/execa/index.d.ts +++ b/types/execa/index.d.ts @@ -14,10 +14,9 @@ import { Stream } from 'stream'; 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; - export type StdIOOption = 'pipe' | 'ipc' | 'ignore' | number | Stream | undefined | null; - - export interface ExecaOptions { + interface ExecaOptions { input: string | Buffer | Stream; preferLocal: boolean; stripEof: boolean; @@ -31,10 +30,10 @@ declare namespace execa { stderr: StdIOOption; } - export type Options = SpawnOptions & ExecaOptions & ExecOptions; - export type SyncOptions = SpawnSyncOptions & ExecaOptions & ExecOptions; + type Options = SpawnOptions & ExecaOptions & ExecOptions; + type SyncOptions = SpawnSyncOptions & ExecaOptions & ExecOptions; - export interface ExecaReturns { + interface ExecaReturns { cmd: string; code: number; failed: boolean; @@ -45,21 +44,21 @@ declare namespace execa { timedOut: boolean; } - export type ExecaError = Error & ExecaReturns; + type ExecaError = Error & ExecaReturns; - export interface ExecaChildPromise { + interface ExecaChildPromise { catch(onrejected?: ((reason: ExecaError) => TResult | PromiseLike) | null): Promise; } - export type ExecaChildProcess = ChildProcess & ExecaChildPromise & Promise; + type ExecaChildProcess = ChildProcess & ExecaChildPromise & Promise; - export function stdout(file: string, options?: Partial): Promise; - export function stdout(file: string, args?: string[], options?: Partial): Promise; - export function stderr(file: string, options?: Partial): Promise; - export function stderr(file: string, args?: string[], options?: Partial): Promise; - export function shell(command: string, options?: Partial): ExecaChildProcess; - export function sync(file: string, options?: Partial): ExecaReturns; - export function sync(file: string, args?: string[], options?: Partial): ExecaReturns; - export function shellSync(command: string, options?: Partial): ExecaReturns; + function stdout(file: string, options?: Partial): Promise; + function stdout(file: string, args?: string[], options?: Partial): Promise; + function stderr(file: string, options?: Partial): Promise; + function stderr(file: string, args?: string[], options?: Partial): Promise; + function shell(command: string, options?: Partial): ExecaChildProcess; + function sync(file: string, options?: Partial): ExecaReturns; + function sync(file: string, args?: string[], options?: Partial): ExecaReturns; + function shellSync(command: string, options?: Partial): ExecaReturns; } export = execa; From d1fe542d52898442c1afe26da8d6d2dcafd2dd64 Mon Sep 17 00:00:00 2001 From: Kevin Greene Date: Fri, 27 Oct 2017 10:05:05 -0700 Subject: [PATCH 047/495] Account for 'set-cookie' header in Node v8 types --- types/node/index.d.ts | 12 +++++++++--- types/node/node-tests.ts | 21 ++++++++++++++++++--- types/node/v4/index.d.ts | 20 +++++++++++--------- types/node/v4/node-tests.ts | 23 +++++++++++++++++------ types/node/v6/index.d.ts | 20 +++++++++++--------- types/node/v6/node-tests.ts | 23 +++++++++++++++++------ types/node/v7/index.d.ts | 20 +++++++++++--------- types/node/v7/node-tests.ts | 23 +++++++++++++++++------ 8 files changed, 111 insertions(+), 51 deletions(-) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index d8e8fe3358..419e09d667 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -836,14 +836,20 @@ declare module "http" { import * as stream from "stream"; import { URL } from "url"; - // incoming headers will never contain number - export interface IncomingHttpHeaders { + export interface BaseIncomingHttpHeaders { [header: string]: string | string[]; } + export interface SetCookieHttpHeader { + 'set-cookie'?: string[]; + } + + // incoming headers will never contain number + export type IncomingHttpHeaders = BaseIncomingHttpHeaders & SetCookieHttpHeader; + // outgoing headers allows numbers (as they are converted internally to strings) export interface OutgoingHttpHeaders { - [header: string]: number | string | string[] | undefined; + [header: string]: number | string | string[]; } export interface ClientRequestArgs { diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index c4cd693e03..e75059eea4 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -1316,9 +1316,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 431cb7d07c..792537be95 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -557,18 +557,20 @@ declare module "http" { import * as net from "net"; import * as stream from "stream"; - // incoming headers will never contain number - export type IncomingHttpHeaders = { - [header: string]: string - } & { - 'set-cookie'?: string[] + export interface BaseIncomingHttpHeaders { + [header: string]: string | string[]; } + export interface SetCookieHttpHeader { + 'set-cookie'?: string[]; + } + + // incoming headers will never contain number + export type IncomingHttpHeaders = BaseIncomingHttpHeaders & SetCookieHttpHeader; + // outgoing headers allows numbers (as they are converted internally to strings) - export type OutgoingHttpHeaders = { - [header: string]: number | string - } & { - 'set-cookie'?: string[] + export interface OutgoingHttpHeaders { + [header: string]: number | string | string[]; } export interface RequestOptions { diff --git a/types/node/v4/node-tests.ts b/types/node/v4/node-tests.ts index 3ba0db2851..1cca96f708 100644 --- a/types/node/v4/node-tests.ts +++ b/types/node/v4/node-tests.ts @@ -500,13 +500,24 @@ namespace http_tests { request.abort(); } - const reqOptions: http.RequestOptions = { - timeout: 30000 - }; + // http request options + { + const requestOpts: http.RequestOptions = { + timeout: 30000 + }; - const clientArgs: http.ClientRequestArgs = { - 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 a6d3d54b5b..0dd86fc790 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -629,18 +629,20 @@ declare module "http" { import * as net from "net"; import * as stream from "stream"; - // incoming headers will never contain number - export type IncomingHttpHeaders = { - [header: string]: string - } & { - 'set-cookie'?: string[] + export interface BaseIncomingHttpHeaders { + [header: string]: string | string[]; } + export interface SetCookieHttpHeader { + 'set-cookie'?: string[]; + } + + // incoming headers will never contain number + export type IncomingHttpHeaders = BaseIncomingHttpHeaders & SetCookieHttpHeader; + // outgoing headers allows numbers (as they are converted internally to strings) - export type OutgoingHttpHeaders = { - [header: string]: number | string - } & { - 'set-cookie'?: string[] + export interface OutgoingHttpHeaders { + [header: string]: number | string | string[]; } export interface RequestOptions { diff --git a/types/node/v6/node-tests.ts b/types/node/v6/node-tests.ts index c3cced9921..30f14e3c90 100644 --- a/types/node/v6/node-tests.ts +++ b/types/node/v6/node-tests.ts @@ -936,13 +936,24 @@ namespace http_tests { request.abort(); } - const reqOptions: http.RequestOptions = { - timeout: 30000 - }; + // http request options + { + const requestOpts: http.RequestOptions = { + timeout: 30000 + }; - const clientArgs: http.ClientRequestArgs = { - 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 fae6d5700e..e67dfdc969 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -646,18 +646,20 @@ declare module "http" { import * as net from "net"; import * as stream from "stream"; - // incoming headers will never contain number - export type IncomingHttpHeaders = { - [header: string]: string - } & { - 'set-cookie'?: string[] + export interface BaseIncomingHttpHeaders { + [header: string]: string | string[]; } + export interface SetCookieHttpHeader { + 'set-cookie'?: string[]; + } + + // incoming headers will never contain number + export type IncomingHttpHeaders = BaseIncomingHttpHeaders & SetCookieHttpHeader; + // outgoing headers allows numbers (as they are converted internally to strings) - export type OutgoingHttpHeaders = { - [header: string]: number | string - } & { - 'set-cookie'?: string[] + export interface OutgoingHttpHeaders { + [header: string]: number | string | string[]; } export interface RequestOptions { diff --git a/types/node/v7/node-tests.ts b/types/node/v7/node-tests.ts index 89f49817c7..8b64371d4d 100644 --- a/types/node/v7/node-tests.ts +++ b/types/node/v7/node-tests.ts @@ -1033,13 +1033,24 @@ namespace http_tests { request.abort(); } - const reqOptions: http.RequestOptions = { - timeout: 30000 - }; + // http request options + { + const requestOpts: http.RequestOptions = { + timeout: 30000 + }; - const clientArgs: http.ClientRequestArgs = { - timeout: 30000 - }; + const clientArgs: http.ClientRequestArgs = { + timeout: 30000 + }; + } + + // http headers + { + const headers: http.IncomingHttpHeaders = { + 'Content-Type': 'application/json', + 'set-cookie': [ 'type=ninja', 'language=javascript' ] + }; + } } ////////////////////////////////////////////////////// From 6d2a1ad81482ce86e6fb274a06142b0b2f0094cd Mon Sep 17 00:00:00 2001 From: Kevin Greene Date: Fri, 27 Oct 2017 10:09:18 -0700 Subject: [PATCH 048/495] [node] Fix linting errors in node v8 --- types/node/index.d.ts | 31 ++++++++++--------------------- types/node/node-tests.ts | 1 + 2 files changed, 11 insertions(+), 21 deletions(-) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 419e09d667..17ee26057d 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; /** @@ -4458,9 +4450,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; /** @@ -4679,7 +4668,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 }; /** @@ -4698,7 +4687,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; @@ -4708,21 +4697,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; /** @@ -4751,9 +4740,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; @@ -4764,8 +4753,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 e75059eea4..4fa5759075 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); From 96bbf2d34bf47a97cde54fb283a33bca558e1067 Mon Sep 17 00:00:00 2001 From: Rasmus Eneman Date: Fri, 27 Oct 2017 18:10:26 +0200 Subject: [PATCH 049/495] recompose: Support instance properties in lifecycle object --- types/recompose/index.d.ts | 26 ++++++++++++++------------ types/recompose/recompose-tests.tsx | 18 ++++++++++++++++++ 2 files changed, 32 insertions(+), 12 deletions(-) diff --git a/types/recompose/index.d.ts b/types/recompose/index.d.ts index 36621f3376..5fe0c82987 100644 --- a/types/recompose/index.d.ts +++ b/types/recompose/index.d.ts @@ -216,7 +216,7 @@ declare module 'recompose' { contextTypes: ValidationMap ) : InferableComponentEnhancer; - interface ReactLifeCycleFunctionsThisArguments { + interface _ReactLifeCycleFunctionsThisArguments { props: TProps, state: TState, setState(f: (prevState: TState, props: TProps) => Pick, callback?: () => any): void; @@ -228,20 +228,22 @@ declare module 'recompose' { [key: string]: React.ReactInstance }; } + type ReactLifeCycleFunctionsThisArguments = + _ReactLifeCycleFunctionsThisArguments & TInstance // lifecycle: https://github.com/acdlite/recompose/blob/master/docs/API.md#lifecycle - interface ReactLifeCycleFunctions { - componentWillMount?: (this: ReactLifeCycleFunctionsThisArguments) => void; - componentDidMount?: (this: ReactLifeCycleFunctionsThisArguments) => void; - componentWillReceiveProps?: (this: ReactLifeCycleFunctionsThisArguments, nextProps: TProps) => void; - shouldComponentUpdate?: (this: ReactLifeCycleFunctionsThisArguments, nextProps: TProps, nextState: TState) => boolean; - componentWillUpdate?: (this: ReactLifeCycleFunctionsThisArguments, nextProps: TProps, nextState: TState) => void; - componentDidUpdate?: (this: ReactLifeCycleFunctionsThisArguments, prevProps: TProps, prevState: TState) => void; - componentWillUnmount?: (this: ReactLifeCycleFunctionsThisArguments) => void; + interface ReactLifeCycleFunctions { + componentWillMount?: (this: ReactLifeCycleFunctionsThisArguments) => void; + componentDidMount?: (this: ReactLifeCycleFunctionsThisArguments) => void; + componentWillReceiveProps?: (this: ReactLifeCycleFunctionsThisArguments, nextProps: TProps) => void; + shouldComponentUpdate?: (this: ReactLifeCycleFunctionsThisArguments, nextProps: TProps, nextState: TState) => boolean; + componentWillUpdate?: (this: ReactLifeCycleFunctionsThisArguments, nextProps: TProps, nextState: TState) => void; + componentDidUpdate?: (this: ReactLifeCycleFunctionsThisArguments, prevProps: TProps, prevState: TState) => void; + componentWillUnmount?: (this: ReactLifeCycleFunctionsThisArguments) => void; } - export function lifecycle( - spec: ReactLifeCycleFunctions + export function lifecycle( + spec: ReactLifeCycleFunctions & TInstance ): InferableComponentEnhancer<{}>; // toClass: https://github.com/acdlite/recompose/blob/master/docs/API.md#toClass @@ -365,7 +367,7 @@ declare module 'recompose' { export function createEventHandler>(): EventHandlerOf; // createEventHandlerWithConfig: https://github.com/acdlite/recompose/blob/master/docs/API.md#createEventHandlerWithConfig - export function createEventHandlerWithConfig(config: ObservableConfig): + export function createEventHandlerWithConfig(config: ObservableConfig): >() => EventHandlerOf; // setObservableConfig: https://github.com/acdlite/recompose/blob/master/docs/API.md#setObservableConfig diff --git a/types/recompose/recompose-tests.tsx b/types/recompose/recompose-tests.tsx index 1ed22fac20..3bffa12cc6 100644 --- a/types/recompose/recompose-tests.tsx +++ b/types/recompose/recompose-tests.tsx @@ -289,3 +289,21 @@ function testOnlyUpdateForKeys() { // This should be a compile error // onlyUpdateForKeys(['fo'])(component) } + +function testLifecycle() { + interface Props { + foo: number; + bar: string; + } + interface State {} + interface Instance { + instanceValue: number + } + const component: React.StatelessComponent = (props) =>
{props.foo} {props.bar}
+ lifecycle({ + instanceValue: 1, + componentDidMount() { + this.instanceValue = 2 + } + })(component) +} From ed07a68500745c4b2a30d77d3a40ce877ae7c939 Mon Sep 17 00:00:00 2001 From: Dhaya Benmessaoud Date: Thu, 26 Oct 2017 22:18:50 +0200 Subject: [PATCH 050/495] Add typings for CardService (google-apps-script). --- .../google-apps-script.card.d.ts | 653 ++++++++++++++++++ .../google-apps-script.gmail.d.ts | 72 ++ types/google-apps-script/index.d.ts | 1 + 3 files changed, 726 insertions(+) create mode 100644 types/google-apps-script/google-apps-script.card.d.ts 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..5d973584d3 --- /dev/null +++ b/types/google-apps-script/google-apps-script.card.d.ts @@ -0,0 +1,653 @@ +// Type definitions for Google Apps Script 2017-10-26 +// 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 `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..f7383661f8 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. */ 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 @@ /// /// /// +/// /// /// /// From d17893c89bc6c6017f3d83d27c29703940e0575e Mon Sep 17 00:00:00 2001 From: Kevin Greene Date: Fri, 27 Oct 2017 12:30:59 -0700 Subject: [PATCH 051/495] Add specific properties to iIncomingHttpHeaders --- types/node/index.d.ts | 56 +++++++++++++++++++++++++++++-------- types/node/node-tests.ts | 2 +- types/node/v4/index.d.ts | 54 ++++++++++++++++++++++++++++------- types/node/v4/node-tests.ts | 2 +- types/node/v6/index.d.ts | 54 ++++++++++++++++++++++++++++------- types/node/v6/node-tests.ts | 2 +- types/node/v7/index.d.ts | 54 ++++++++++++++++++++++++++++------- types/node/v7/node-tests.ts | 2 +- 8 files changed, 181 insertions(+), 45 deletions(-) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 1a417542b7..853f9b29c2 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -828,20 +828,54 @@ declare module "http" { import * as stream from "stream"; import { URL } from "url"; - export interface BaseIncomingHttpHeaders { - [header: string]: string | string[]; - } - - export interface SetCookieHttpHeader { - 'set-cookie'?: string[]; - } - // incoming headers will never contain number - export type IncomingHttpHeaders = BaseIncomingHttpHeaders & SetCookieHttpHeader; + 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[]; + [header: string]: number | string | string[] | undefined; } export interface ClientRequestArgs { @@ -4669,7 +4703,7 @@ declare module "tls" { */ requestOCSP?: boolean }); - + /** * A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. */ diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index d833029f37..3dfe776df2 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -1332,7 +1332,7 @@ namespace http_tests { // http headers { const headers: http.IncomingHttpHeaders = { - 'Content-Type': 'application/json', + '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 792537be95..5496da86cd 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -557,20 +557,54 @@ declare module "http" { import * as net from "net"; import * as stream from "stream"; - export interface BaseIncomingHttpHeaders { - [header: string]: string | string[]; - } - - export interface SetCookieHttpHeader { - 'set-cookie'?: string[]; - } - // incoming headers will never contain number - export type IncomingHttpHeaders = BaseIncomingHttpHeaders & SetCookieHttpHeader; + 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[]; + [header: string]: number | string | string[] | undefined; } export interface RequestOptions { diff --git a/types/node/v4/node-tests.ts b/types/node/v4/node-tests.ts index 1cca96f708..8f005da455 100644 --- a/types/node/v4/node-tests.ts +++ b/types/node/v4/node-tests.ts @@ -514,7 +514,7 @@ namespace http_tests { // http headers { const headers: http.IncomingHttpHeaders = { - 'Content-Type': 'application/json', + '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 0dd86fc790..ef2208af0b 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -629,20 +629,54 @@ declare module "http" { import * as net from "net"; import * as stream from "stream"; - export interface BaseIncomingHttpHeaders { - [header: string]: string | string[]; - } - - export interface SetCookieHttpHeader { - 'set-cookie'?: string[]; - } - // incoming headers will never contain number - export type IncomingHttpHeaders = BaseIncomingHttpHeaders & SetCookieHttpHeader; + 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[]; + [header: string]: number | string | string[] | undefined; } export interface RequestOptions { diff --git a/types/node/v6/node-tests.ts b/types/node/v6/node-tests.ts index 30f14e3c90..1a6b87db05 100644 --- a/types/node/v6/node-tests.ts +++ b/types/node/v6/node-tests.ts @@ -950,7 +950,7 @@ namespace http_tests { // http headers { const headers: http.IncomingHttpHeaders = { - 'Content-Type': 'application/json', + '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 cb377bf9c1..9f4208a7cb 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -645,20 +645,54 @@ declare module "http" { import * as net from "net"; import * as stream from "stream"; - export interface BaseIncomingHttpHeaders { - [header: string]: string | string[]; - } - - export interface SetCookieHttpHeader { - 'set-cookie'?: string[]; - } - // incoming headers will never contain number - export type IncomingHttpHeaders = BaseIncomingHttpHeaders & SetCookieHttpHeader; + 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[]; + [header: string]: number | string | string[] | undefined; } export interface RequestOptions { diff --git a/types/node/v7/node-tests.ts b/types/node/v7/node-tests.ts index 8b64371d4d..9bbf6a9300 100644 --- a/types/node/v7/node-tests.ts +++ b/types/node/v7/node-tests.ts @@ -1047,7 +1047,7 @@ namespace http_tests { // http headers { const headers: http.IncomingHttpHeaders = { - 'Content-Type': 'application/json', + 'content-type': 'application/json', 'set-cookie': [ 'type=ninja', 'language=javascript' ] }; } From c0ce763347dd462af31fd3f5d04535b8a71fece9 Mon Sep 17 00:00:00 2001 From: Dhaya Benmessaoud Date: Sat, 28 Oct 2017 10:52:49 +0200 Subject: [PATCH 052/495] Add missing typings for draft email creation. --- types/google-apps-script/google-apps-script.gmail.d.ts | 8 ++++++++ 1 file changed, 8 insertions(+) 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 f7383661f8..4967f53394 100644 --- a/types/google-apps-script/google-apps-script.gmail.d.ts +++ b/types/google-apps-script/google-apps-script.gmail.d.ts @@ -203,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[]; @@ -241,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[]; From 9e0c0e74fbe721ee379aedf8cddcb17c5f266872 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jozef=20B=C3=ADro=C5=A1?= Date: Sat, 28 Oct 2017 11:38:09 +0200 Subject: [PATCH 053/495] Actualized FieldArrayMetaProps and FieldProps according to flow types from redux-form v7.1.2 --- types/redux-form/v6/lib/FieldArray.d.ts | 38 +++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/types/redux-form/v6/lib/FieldArray.d.ts b/types/redux-form/v6/lib/FieldArray.d.ts index 9629eecb27..42308c4f76 100644 --- a/types/redux-form/v6/lib/FieldArray.d.ts +++ b/types/redux-form/v6/lib/FieldArray.d.ts @@ -103,6 +103,10 @@ interface WrappedFieldArrayProps { } interface FieldsProps { + /** + * true if field is field array + */ + _isFieldArray: boolean /** * A method to iterate over each value of the array. */ @@ -134,6 +138,15 @@ interface FieldsProps { */ map(callback: (name: string, index: number, fields: FieldsProps) => any): any; + /** + * A method to move value in array on on different index in the field array + */ + move(from: number, to: number): void; + + /** + * Name of field array + */ + name: string; /** * Removes an item from the end of the array. Returns the item removed. */ @@ -144,16 +157,32 @@ interface FieldsProps { */ push(value: T): void; + /** + * TODO: Need to figure out what does this do, its taken + * directly form redux-form repo and flow types + */ + reduce(callback: Function): any + /** * Removes an item from the array at an arbitrary index. */ remove(index: number): void; + /** + * It will remove all fields in field array + */ + removeAll(): void + /** * Removes an item from beginning of the array. Returns the item removed. */ shift(): T; + /** + * TODO: Need to figure out what does this do, its taken + * directly form redux-form repo and flow types + */ + some(callback: Function): void /** * Swaps two items in the array at the given indexes. */ @@ -197,6 +226,15 @@ interface FieldArrayMetaProps { */ pristine: boolean; + /** + * true if field array is being submitted + */ + submitting: boolean; + + /** + * true if some field value in the field array fails validation on submit + */ + submitFailed: boolean; /** * true if any of the fields have been touched. */ From bbf068446ded2a942188cca0904854c6652c5d0f Mon Sep 17 00:00:00 2001 From: rhysd Date: Sat, 28 Oct 2017 19:20:36 +0900 Subject: [PATCH 054/495] twitter-text: Add missing options (fix #19595) --- types/twitter-text/index.d.ts | 13 +++++++++++-- types/twitter-text/twitter-text-tests.ts | 1 + 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/types/twitter-text/index.d.ts b/types/twitter-text/index.d.ts index b09af9d34c..ca6fd66007 100644 --- a/types/twitter-text/index.d.ts +++ b/types/twitter-text/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for twitter-text v1.13.4 +// Type definitions for twitter-text v1.14.7 // Project: https://github.com/twitter/twitter-text // Definitions by: rhysd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -36,6 +36,10 @@ interface Indices { indices: [number, number]; } +interface Attributes { + [name: string]: string | null; +} + export declare function htmlEscape(text: string): string; export declare function splitTags(text: string): string[]; @@ -69,12 +73,17 @@ export interface AutoLinkOptions { usernameClass?: string; usernameUrlBase?: string; listUrlBase?: string; - htmlAttrs?: string; invisibleTagAttrs?: string; htmlEscapeNonEntities?: boolean; targetBlank?: boolean; suppressNoFollow?: boolean; urlEntities?: UrlEntity[]; + usernameIncludeSymbol?: boolean; + linkAttributeBlock?: (entity: EntityWithIndices, attributes: Attributes) => void; + linkTextBlock?: (entity: EntityWithIndices, text: string) => void; + symbolTag?: string; + textWithSymbolTag?: string; + htmlAttrs?: Attributes; } export declare function autoLink(text: string, options?: AutoLinkOptions): string; diff --git a/types/twitter-text/twitter-text-tests.ts b/types/twitter-text/twitter-text-tests.ts index c1cc0917e0..a8e198e410 100644 --- a/types/twitter-text/twitter-text-tests.ts +++ b/types/twitter-text/twitter-text-tests.ts @@ -42,6 +42,7 @@ result = twitter.autoLinkUsernamesOrLists(text); result = twitter.autoLinkHashtags(text); result = twitter.autoLinkCashtags(text); result = twitter.autoLinkUrlsCustom(text, {targetBlank: true, suppressNoFollow: true}); +result = twitter.autoLinkUrlsCustom(text, {usernameIncludeSymbol: true, linkTextBlock: (entity, text) => {}}); const len: number = twitter.getTweetLength(text); From 83c42657443c2ff5c9eecc85bf3c978ead097f4c Mon Sep 17 00:00:00 2001 From: Steve Kellock Date: Fri, 20 Oct 2017 19:42:02 -0400 Subject: [PATCH 055/495] Fixes search callback for lists blessed. --- types/blessed/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/blessed/index.d.ts b/types/blessed/index.d.ts index 553942af2f..bd3a5aca7b 100644 --- a/types/blessed/index.d.ts +++ b/types/blessed/index.d.ts @@ -1691,7 +1691,7 @@ declare namespace Blessed { * 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; + search?: (err: any, value?: string) => void; /** * Whether the list is interactive and can have items selected (Default: true). */ From 1b74afc00a77fefea57112d68729fc07b246eec8 Mon Sep 17 00:00:00 2001 From: Steve Kellock Date: Fri, 20 Oct 2017 22:54:02 -0400 Subject: [PATCH 056/495] Lints the blessed typings. --- types/blessed/blessed-tests.ts | 560 ++-- types/blessed/index.d.ts | 5779 +++++++++++++++++--------------- 2 files changed, 3264 insertions(+), 3075 deletions(-) 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 bd3a5aca7b..c120cc0fc4 100644 --- a/types/blessed/index.d.ts +++ b/types/blessed/index.d.ts @@ -1,2837 +1,3052 @@ -// 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: https://github.com/borisyankov/DefinitelyTyped +// TypeScript Version: 2.1 -/// +/// 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?: (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; - } - - 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; + } + + 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: + /** 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" + , callback: (arg: Node) => void): this; + } + + 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: + "mouse" + | "mouseout" + | "mouseover" + | "mousedown" + | "mouseup" + | "mousewheel" + | "wheeldown" + | "wheelup" + | "mousemove" + , callback: (arg: Events.IMouseEventArg) => void): this; + + /** + * Received on key events. + */ + on(event: "keypress", callback: (ch: string, key: Events.IKeyEventArg) => void): this; + + on(event: + /** + * 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" + , 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: + /** 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" + , + 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; + } + + 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: + /** 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" + , 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; + } + + 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: + /** Value is an error. */ + | "error" + /** Value is submitted (enter). */ + | "submit" + /** Value is discared (escape). */ + | "cancel" + /** Either submit or cancel. */ + | "action" + , 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 +}; From ccf051763b9a4be08bf7d15649b429b39930c86e Mon Sep 17 00:00:00 2001 From: Steve Kellock Date: Fri, 20 Oct 2017 23:14:50 -0400 Subject: [PATCH 057/495] Adds prettier to the blessed typings. --- types/blessed/index.d.ts | 283 ++++++++++++++++++--------------------- 1 file changed, 132 insertions(+), 151 deletions(-) diff --git a/types/blessed/index.d.ts b/types/blessed/index.d.ts index c120cc0fc4..9098648240 100644 --- a/types/blessed/index.d.ts +++ b/types/blessed/index.d.ts @@ -1,12 +1,12 @@ // 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"; @@ -39,8 +39,8 @@ export namespace Widgets { hover?: boolean; focus?: boolean; label?: string; - track?: { bg?: string; fg?: string; }; - scrollbar?: { bg?: string; fg?: string; }; + track?: { bg?: string; fg?: string }; + scrollbar?: { bg?: string; fg?: string }; } interface TBorder { @@ -76,7 +76,7 @@ export namespace Widgets { /** * Shape of the cursor. Can be: block, underline, or line. */ - shape: 'block'|'underline'|'line'; + shape: "block" | "underline" | "line"; /** * Whether the cursor blinks. @@ -173,8 +173,7 @@ export namespace Widgets { destroy(): void; } - interface IOptions { - } + interface IOptions {} interface IHasOptions { options: T; @@ -212,7 +211,10 @@ export namespace Widgets { setup(): void; term(is: any): boolean; readTerminfo(term: string): string; - parseTerminfo(data: any, file: string): { + parseTerminfo( + data: any, + file: string + ): { header: { dataSize: number; headerSize: number; @@ -230,8 +232,8 @@ export namespace Widgets { strCount: number; strTableSize: number; lastStrTableOffset: number; - } - } + }; + }; name: string; names: string[]; desc: string; @@ -253,6 +255,18 @@ export namespace Widgets { 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); @@ -266,17 +280,17 @@ export namespace Widgets { /** * An object for any miscellanous user data. */ - data: { [index: string]: any; }; + data: { [index: string]: any }; /** * An object for any miscellanous user data. */ - _: { [index: string]: any; }; + _: { [index: string]: any }; /** * An object for any miscellanous user data. */ - $: { [index: string]: any; }; + $: { [index: string]: any }; /** * Type of the node (e.g. box). @@ -363,21 +377,58 @@ export namespace Widgets { set(name: string, value: any): void; on(event: string, listener: (...args: any[]) => void): this; - - on(event: - /** 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" - , callback: (arg: Node) => 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. @@ -396,72 +447,14 @@ export namespace Widgets { 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: - "mouse" - | "mouseout" - | "mouseover" - | "mousedown" - | "mouseup" - | "mousewheel" - | "wheeldown" - | "wheelup" - | "mousemove" - , callback: (arg: Events.IMouseEventArg) => void): this; - - /** - * Received on key events. - */ + /** 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: - /** - * 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" - , callback: (arg: Screen) => void): this; - - /** - * Received when blessed notices something untoward (output is not a tty, terminfo not found, etc). - */ + 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: - /** 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" - , - callback: () => void): this; + on(event: NodeGenericEventType, callback: () => void): this; } interface IScreenOptions extends INodeOptions { @@ -975,7 +968,12 @@ export namespace Widgets { /** * 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; + exec( + file: string, + args: string[], + options: NodeChildProcessExecOptions, + callback: (...args: any[]) => void + ): child_process.ChildProcess; /** * Read data from text editor. @@ -1243,7 +1241,7 @@ export namespace Widgets { yl: number; yi: number; base: number; - _contentEnd: { x: number; y: number; }; + _contentEnd: { x: number; y: number }; notop: Types.TTopLeft; noleft: Types.TTopLeft; noright: Types.TPosition; @@ -1642,7 +1640,7 @@ export namespace Widgets { * Object enabling a scrollbar. * Style of the scrollbar track if present (takes regular style options). */ - scrollbar?: { style?: any; track?: any; ch?: string; }; + scrollbar?: { style?: any; track?: any; ch?: string }; } interface ScrollableTextOptions extends ScrollableBoxOptions { @@ -1734,8 +1732,7 @@ export namespace Widgets { * A scrollable text box which can display and scroll text, as well as handle * pre-existing newlines and escape codes. */ - class ScrollableTextElement extends ScrollableBoxElement { - } + class ScrollableTextElement extends ScrollableBoxElement {} /** * A box element which draws a simple box containing content or other elements. @@ -1867,6 +1864,17 @@ export namespace Widgets { 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); @@ -1976,24 +1984,9 @@ export namespace Widgets { fuzzyFind(arg: string | RegExp | (() => void)): void; on(event: string, listener: (...args: any[]) => void): this; - - /** - * Received when an item is selected. - */ + /** Received when an item is selected. */ on(event: "select", callback: (item: BoxElement, index: number) => void): this; - - on(event: - /** 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" - , callback: () => void): this; - + on(event: ListElementEventType, callback: () => void): this; on(event: "select item", callback: (item: BlessedElement, index: number) => void): this; } @@ -2036,17 +2029,10 @@ export namespace Widgets { reset(callback?: () => void): void; on(event: string, listener: (...args: any[]) => void): this; - - /** - * Received when an item is selected. - */ + /** Received when an item is selected. */ on(event: "cd", callback: (file: string, cwd: string) => void): this; - - /** - * Received when an item is selected. - */ + /** 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; } @@ -2192,7 +2178,7 @@ export namespace Widgets { selectTab(index: number): void; on(event: string, listener: (...args: any[]) => void): this; - on(event: "set items" | "remove item" | "select tab", callback: () => void): this; + on(event: "set items" | "remove item" | "select tab", callback: () => void): this; } interface FormOptions extends BoxOptions { @@ -2246,16 +2232,12 @@ export namespace Widgets { reset(): void; on(event: string, listener: (...args: any[]) => void): this; - - /** - * Form is submitted. Receives a data object. - */ + /** 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 { } + interface InputOptions extends BoxOptions {} abstract class InputElement extends BoxElement { constructor(opts: InputOptions); @@ -2271,6 +2253,16 @@ export namespace Widgets { 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); @@ -2346,17 +2338,7 @@ export namespace Widgets { setValue(text: string): void; on(event: string, listener: (...args: any[]) => void): this; - - on(event: - /** Value is an error. */ - | "error" - /** Value is submitted (enter). */ - | "submit" - /** Value is discared (escape). */ - | "cancel" - /** Either submit or cancel. */ - | "action" - , callback: (err: any) => void): this; + on(event: TextareaElementEventType, callback: (err: any) => void): this; } interface TextboxOptions extends TextareaOptions { @@ -2390,7 +2372,7 @@ export namespace Widgets { censor: boolean; } - interface ButtonOptions extends BoxOptions { } + interface ButtonOptions extends BoxOptions {} class ButtonElement extends InputElement implements IHasOptions { constructor(opts: ButtonOptions); @@ -2463,7 +2445,7 @@ export namespace Widgets { toggle(): void; } - interface RadioSetOptions extends BoxOptions { } + interface RadioSetOptions extends BoxOptions {} /** * An element wrapping RadioButtons. RadioButtons within this element will be mutually exclusive @@ -2473,7 +2455,7 @@ export namespace Widgets { constructor(opts: RadioSetOptions); } - interface RadioButtonOptions extends BoxOptions { } + interface RadioButtonOptions extends BoxOptions {} /** * A radio button which can be used in a form element. @@ -2482,7 +2464,7 @@ export namespace Widgets { constructor(opts: RadioButtonOptions); } - interface PromptOptions extends BoxOptions { } + interface PromptOptions extends BoxOptions {} /** * A prompt box containing a text input, okay, and cancel buttons (automatically hidden). @@ -2500,7 +2482,7 @@ export namespace Widgets { readInput(text: string, value: string, callback: (err: any, value: string) => void): void; } - interface QuestionOptions extends BoxOptions { } + interface QuestionOptions extends BoxOptions {} /** * A question box containing okay and cancel buttons (automatically hidden). @@ -2516,7 +2498,7 @@ export namespace Widgets { ask(question: string, callback: (err: any, value: string) => void): void; } - interface MessageOptions extends BoxOptions { } + interface MessageOptions extends BoxOptions {} /** * A box containing a message to be displayed (automatically hidden). @@ -2542,7 +2524,7 @@ export namespace Widgets { error(text: string, callback: () => void): void; } - interface LoadingOptions extends BoxOptions { } + interface LoadingOptions extends BoxOptions {} /** * A box with a spinning line to denote loading (automatically hidden). @@ -2619,8 +2601,7 @@ export namespace Widgets { reset(): void; on(event: string, listener: (...args: any[]) => void): this; - - on(event: | "reset" | "complete" , callback: () => void): this; + on(event: "reset" | "complete", callback: () => void): this; } interface LogOptions extends ScrollableTextOptions { @@ -2729,7 +2710,7 @@ export namespace Widgets { /** * can be line, underline, and block. */ - cursor?: 'line'|'underline'|'block'; + cursor?: "line" | "underline" | "block"; terminal?: string; @@ -3014,7 +2995,7 @@ export namespace Widgets { } export namespace widget { - class Terminal extends Widgets.TerminalElement { } + class Terminal extends Widgets.TerminalElement {} } export function screen(options?: Widgets.IScreenOptions): Widgets.Screen; @@ -3048,5 +3029,5 @@ export function layout(options?: Widgets.LayoutOptions): Widgets.LayoutElement; export function escape(item: any): any; export const colors: { - match(hexColor: string): string + match(hexColor: string): string; }; From ec512e0f7468041c3e1b48672f9f16678766836e Mon Sep 17 00:00:00 2001 From: york yao Date: Mon, 30 Oct 2017 09:24:49 +0800 Subject: [PATCH 058/495] port pull request #21101 --- types/ioredis/index.d.ts | 6 ++++++ types/ioredis/ioredis-tests.ts | 8 ++++++++ 2 files changed, 14 insertions(+) diff --git a/types/ioredis/index.d.ts b/types/ioredis/index.d.ts index d80f4ed30e..f1d7f6eb95 100644 --- a/types/ioredis/index.d.ts +++ b/types/ioredis/index.d.ts @@ -20,6 +20,7 @@ interface RedisStatic { (host?: string, options?: IORedis.RedisOptions): IORedis.Redis; (options?: IORedis.RedisOptions): IORedis.Redis; Cluster: IORedis.Cluster; + Command: IORedis.Command; } declare var IORedis: RedisStatic; @@ -36,6 +37,11 @@ declare class Commander { } 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?: () => void): Promise; diff --git a/types/ioredis/ioredis-tests.ts b/types/ioredis/ioredis-tests.ts index 55e3229eb4..2be342c2bd 100644 --- a/types/ioredis/ioredis-tests.ts +++ b/types/ioredis/ioredis-tests.ts @@ -82,3 +82,11 @@ redis.pipeline([ ['set', 'foo', 'bar'], ['get', 'foo'] ]).exec(() => { /* ... */ }); + +Redis.Command.setArgumentTransformer('set', args => { + return args; +}); + +Redis.Command.setReplyTransformer('get', (result: any) => { + return result; +}); From 6223b3f97739485ca5696787c50abaef60d4b172 Mon Sep 17 00:00:00 2001 From: Dhaya Benmessaoud Date: Mon, 30 Oct 2017 10:50:26 +0100 Subject: [PATCH 059/495] Add missing method definition in CardService. --- types/google-apps-script/google-apps-script.card.d.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/types/google-apps-script/google-apps-script.card.d.ts b/types/google-apps-script/google-apps-script.card.d.ts index 5d973584d3..62d497eb4f 100644 --- a/types/google-apps-script/google-apps-script.card.d.ts +++ b/types/google-apps-script/google-apps-script.card.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2017-10-26 +// 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 @@ -330,6 +330,10 @@ declare namespace GoogleAppsScript { * Creates a new `SelectionInput`. */ newSelectionInput(): SelectionInput; + /** + * Creates a new `Suggestions`. + */ + newSuggestions(): Suggestions; /** * Creates a new `SuggestionsResponseBuilder`. */ From 2fd6e126d1adb9f086e84a017e6da1729d520f76 Mon Sep 17 00:00:00 2001 From: Kevin Greene Date: Mon, 30 Oct 2017 11:12:19 -0700 Subject: [PATCH 060/495] Fixing tests --- types/adone/glosses/datetime.d.ts | 3 --- types/cli/cli-tests.ts | 3 ++- types/content-type/index.d.ts | 2 +- types/ember/test/array-proxy.ts | 2 +- types/negotiator/index.d.ts | 2 +- types/viewporter/viewporter-tests.ts | 14 +++++++------- 6 files changed, 12 insertions(+), 14 deletions(-) diff --git a/types/adone/glosses/datetime.d.ts b/types/adone/glosses/datetime.d.ts index 417f706d95..5ce320f613 100644 --- a/types/adone/glosses/datetime.d.ts +++ b/types/adone/glosses/datetime.d.ts @@ -731,9 +731,6 @@ declare namespace adone { */ creationData(): DatetimeCreationData; - /** - * - */ parsingFlags(): DatetimeParsingFlags; /** 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/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/ember/test/array-proxy.ts b/types/ember/test/array-proxy.ts index 280ab52ded..3573a08139 100755 --- a/types/ember/test/array-proxy.ts +++ b/types/ember/test/array-proxy.ts @@ -21,6 +21,6 @@ class MyNewProxy extends Ember.ArrayProxy { isNew = true; } -let x: MyNewProxy = MyNewProxy.create({ content: Ember.A([1, 2, 3]) }); +let x: MyNewProxy = MyNewProxy.create, {}, {content: Ember.NativeArray}>({ content: Ember.A([1, 2, 3]) }); assertType(x.get('firstObject')); assertType(x.isNew); 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/viewporter/viewporter-tests.ts b/types/viewporter/viewporter-tests.ts index 9c720bec65..15997f9425 100644 --- a/types/viewporter/viewporter-tests.ts +++ b/types/viewporter/viewporter-tests.ts @@ -45,12 +45,12 @@ function test_swipey() { function rainbow(numOfSteps, step) { var r, g, b, h = step / numOfSteps, i = ~~(h * 6), f = h * 6 - i, q = 1 - f; switch (i % 6) { - case 0: r = 1, g = f, b = 0; break; - case 1: r = q, g = 1, b = 0; break; - case 2: r = 0, g = 1, b = f; break; - case 3: r = 0, g = q, b = 1; break; - case 4: r = f, g = 0, b = 1; break; - case 5: r = 1, g = 0, b = q; break; + case 0: r = 1; g = f; b = 0; break; + case 1: r = q; g = 1; b = 0; break; + case 2: r = 0; g = 1; b = f; break; + case 3: r = 0; g = q; b = 1; break; + case 4: r = f; g = 0; b = 1; break; + case 5: r = 1; g = 0; b = q; break; } return [((~ ~(r * 255))), (~ ~(g * 255)), (~ ~(b * 255))]; } @@ -171,4 +171,4 @@ function test_swipey() { }, 16); }); -} \ No newline at end of file +} From 58232d354e2af1e9dc4d5303b088d66eca037047 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Radek=20Mat=C4=9Bj?= Date: Tue, 31 Oct 2017 11:55:38 +0100 Subject: [PATCH 061/495] Declare property on window object --- types/cordova-plugin-device/index.d.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/types/cordova-plugin-device/index.d.ts b/types/cordova-plugin-device/index.d.ts index cb75703d1a..0ca54cf34a 100644 --- a/types/cordova-plugin-device/index.d.ts +++ b/types/cordova-plugin-device/index.d.ts @@ -2,14 +2,18 @@ // Project: https://github.com/apache/cordova-plugin-device // Definitions by: Microsoft Open Technologies Inc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// +// // Copyright (c) Microsoft Open Technologies Inc -// Licensed under the MIT license +// Licensed under the MIT license /** * This plugin defines a global device object, which describes the device's hardware and software. * Although the object is in the global scope, it is not available until after the deviceready event. */ + interface Window { + device: Device; +} + interface Device { /** Get the version of Cordova running on the device. */ cordova: string; From 2007d950cd9b6d459ba1d06f126281905dbbd5d7 Mon Sep 17 00:00:00 2001 From: Mark Florian Date: Tue, 31 Oct 2017 12:26:18 +0000 Subject: [PATCH 062/495] pusher-js: make available via global variable Using Pusher via a CDN script tag registers the `Pusher` global. This change allows for that global to be accessed/typed correctly. See the docs on [UMD modules][1] for details. [1]: https://www.typescriptlang.org/docs/handbook/modules.html#umd-modules --- types/pusher-js/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/pusher-js/index.d.ts b/types/pusher-js/index.d.ts index 0a9f3470b0..30853434a1 100644 --- a/types/pusher-js/index.d.ts +++ b/types/pusher-js/index.d.ts @@ -228,4 +228,6 @@ declare namespace pusher { declare var pusher: pusher.PusherStatic; +export as namespace pusher; + export = pusher; From efe640dd2d00ab12d7e51b1d5cce560f33247467 Mon Sep 17 00:00:00 2001 From: Kevin Greene Date: Mon, 30 Oct 2017 13:47:18 -0700 Subject: [PATCH 063/495] [baconjs] Fix compile errors --- types/baconjs/baconjs-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/baconjs/baconjs-tests.ts b/types/baconjs/baconjs-tests.ts index 75560d4e42..b23e99ccb4 100644 --- a/types/baconjs/baconjs-tests.ts +++ b/types/baconjs/baconjs-tests.ts @@ -183,10 +183,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 }); } From 06fbf8b67e175ad1f255069d3140c971919f55c9 Mon Sep 17 00:00:00 2001 From: Kevin Greene Date: Mon, 30 Oct 2017 10:54:48 -0700 Subject: [PATCH 064/495] [botvs] Fix linting errors --- types/botvs/index.d.ts | 1316 +--------------------------------------- 1 file changed, 1 insertion(+), 1315 deletions(-) diff --git a/types/botvs/index.d.ts b/types/botvs/index.d.ts index 2eabcb98da..4040b057c3 100644 --- a/types/botvs/index.d.ts +++ b/types/botvs/index.d.ts @@ -281,22 +281,16 @@ declare global { interface Exchange { /** * 返回交易所名称(string) - * - * @return {string} */ GetName(): string; /** * 返回交易所自定义的标签(string) - * - * @return {string} */ GetLabel(): string; /** * 返回交易所使用的美元的汇率, OKCoin期货返回官方提供的汇率, 该值不受SetRate影响 - * - * @return {number} */ GetUSDCNY(): number; @@ -305,8 +299,6 @@ declare global { * * 汇率接口调用雅虎提供的接口, 5分钟更新一次 * 所有函数自动经过汇率转换,如果为1指禁用汇率转换 - * - * @return {number} */ GetRate(): number; @@ -316,8 +308,6 @@ declare global { * 比如796期货设置SetRate(6.13), 就是设定USD/EUR对CNY的汇率为6.13, 程序所有价格会自动用这个汇率计算 * SetRate(), 如果不加参数,则恢复系统内置汇率 * SetRate(1), 就是禁用汇率转换 - * - * @param {number} rate */ SetRate(rate?: number): void; @@ -325,44 +315,31 @@ declare global { * 设置价格与品种下单量的小数位精度, 设置后会自动截断 * * exchange.SetPrecision(2, 3); // 设置价格小数位精度为2位, 品种下单量小数位精度为3位 - * - * @param {number} PricePrecision - * @param {number} AmountPrecision */ SetPrecision(PricePrecision: number, AmountPrecision: number): void; /** * 返回交易所操作的货币名称(string), 传统期货CTP返回的固定为STOCK - * - * @return {string} */ GetCurrency(): string; /** * 返回交易所操作的基础货币名称(string), BTC_CNY就返回CNY, ETH_BTC就返回BTC - * - * @return {string} */ GetBaseCurrency(): string; /** * 返回一个Ticker结构 - * - * @return {botvs.Ticker} */ GetTicker(): Ticker; /** * 返回一个Depth结构 - * - * @return {botvs.Depth} */ GetDepth(): Depth; /** * 返回一个Trade数组, 按时间从低到高的顺序, 只支持数字货币(BTC/LTC) - * - * @return {botvs.Trade[]} */ GetTrades(): Trade[]; @@ -372,16 +349,11 @@ declare global { * 不加参数, 默认返回添加机器人时时指量的K线周期, 但也可以自定义K线周期 * 支持: PERIOD_M1 指1分钟, PERIOD_M5 指5分钟, PERIOD_M15 指15分钟, * PERIOD_M30 指30分钟, PERIOD_H1 指1小时, PERIOD_D1 指一天 - * - * @param {number} Period - * @return {botvs.Record[]} */ GetRecords(Period?: VPeriod): Record[]; /** * 返回一个Account结构, 如exchange.GetAccount(), 将返回主交易所账户信息 - * - * @return {botvs.Account} */ GetAccount(): Account; @@ -392,59 +364,37 @@ declare global { * 支持现货(火币/BitVC/OKCoin/OKCoin国际/OKCoin期货/BTCChina/BitYes)市价单, 市价单价格指定为-1 * exchange.Buy(1000), 指买市价1000元的币, BTCChina例外exchange.Buy(0.3)指市价买0.3个币 * - * @param {number} Price - * @param {number} Amount - * @param {*[]} args - * @return {string} - 订单ID + * @return 订单ID */ Buy(Price: number, Amount: number, ...args: any[]): string; /** * 跟Buy函数一样的调用方法和场景 {@see Exchange#Buy} - * - * @param {number} Price - * @param {number} Amount - * @return {string} */ Sell(Price: number, Amount: number): string; /** * 获取所有未完成的订单, 返回一个Order数组结构 - * - * @return {botvs.Order[]} */ GetOrders(): Order[]; /** * 根据订单号获取订单详情, 返回一个Order结构 - * - * @param {string} orderId - * @return {botvs.Order} */ GetOrder(orderId: string): Order; /** * 根据订单号取消一个订单, 返回true或者false - * - * @param {string} orderId - * @return {boolean} */ CancelOrder(orderId: string): boolean; /** * 不下单, 只记录交易信息, logType可为LOG_TYPE_BUY/LOG_TYPE_SELL/LOG_TYPE_CANCEL - * - * @param {VLogType} logType - * @param {string} orderId - * @param {number} price - * @param {number} amount */ Log(logType: VLogType, orderId: string, price: number, amount: number): void; /** * 返回币最小交易数量 - * - * @return {number} */ GetMinStock(): number; @@ -452,15 +402,11 @@ declare global { * 返回一笔订单要求的最小金额(价格*数量) * * Bitstamp要求5美元(程序会根据汇率自动转换为人民币), 其它没有限制 - * - * @return {number} */ GetMinPrice(): number; /** * 返回一个Fee结构 - * - * @return {botvs.Fee} */ GetFee(): Fee; @@ -475,8 +421,6 @@ declare global { * exchange.GetAccount(); * Log(exchange.GetRawJSON());//在GetAccount成功后调用, 获取更详细的账户信息, 可以用JSON.parse解析 * 也支持GetTicker, GetDepth后的exchange.GetRawJSON(), 以及GetPosition与GetOrders,GetOrder这三个调用后的详细反馈数据 - * - * @return {string} */ GetRawJSON(): string; @@ -500,10 +444,6 @@ declare global { * // Python与Javascript的区别, Python的wait返回两个参数, 第一个是异步的api返回的结果, 第二个表示是异步调用是否完成 * ret, ok = d.wait() // ok是一定返回True的, 除非策略被停止 * ret, ok = d.wait(100) // ok返回False, 如果等待超时, 或者wait了一个已经结束的实例 - * - * @param {keyof botvs.Exchange} Method - * @param Args - * @return {botvs.AsyncJob} */ Go(Method: keyof Exchange, ...Args: any[]): AsyncJob; @@ -552,11 +492,6 @@ declare global { * 超时返回-1, 正常返回事件接收的时间(nano级), 只支持实盘 * exchange.IO("wait_instrument"); // 有任何品种更新行情信息时才返回, 可带第二个参数(毫秒数) * 指定超时, 超时返回空字符串, 正常返回触发事件的品种名称, 只支持实盘 - * - * @param {"api" | "usd" | "cny" | "currency" | string} Api - * @param {string} ApiName - * @param {string} Args - * @return {T} */ IO(Api: 'api' | 'usd' | 'cny' | 'currency' | string, ApiName?: string, Args?: string): T; @@ -564,8 +499,6 @@ declare global { * 获取当前持仓信息 * * 返回一个Position数组, (BitVC和OKCoin)可以传入一个参数, 指定要获取的合约类型 - * - * @return {botvs.Position[]} */ GetPosition(): Position[]; @@ -575,8 +508,6 @@ declare global { * 设置Buy(多单)或者Sell(空单)的杆杠大小, MarginLevel有5, 10, 20 三个可选参数 * 796支持5,10,20,50三个选项, BitVC的LTC不支持20倍杠杆, OKCoin支持10倍和20倍 * 如: exchange.SetMarginLevel(5) - * - * @param {number} MarginLevel */ SetMarginLevel(MarginLevel: number): void; @@ -616,9 +547,6 @@ declare global { * exchange.SetContractType("this_week"); * exchange.SetDirection("sell"); * exchange.Sell(1000, 1); - * - * @param {"buy" | "closebuy" | "sell" | "closesell" | "closebuy_today" | "closesell_today"} Direction - * @constructor */ SetDirection(Direction: 'buy' | 'closebuy' | 'sell' | 'closesell' | 'closebuy_today' | 'closesell_today'): void; @@ -633,8 +561,6 @@ declare global { * 默认为子账户A, 要指定子账户是A还是B, * 在合约后加"@A"或"@B", 如: "day@A" 为日合约A子账户 BitVC有week和quarter和next_week三个可选参数, OKCoin期货有this_week, * next_week, quarter三个参数 exchange.SetContractType("week"); - * - * @param {string} ContractType */ SetContractType(ContractType: string): void; } @@ -645,12 +571,6 @@ declare global { * 指数平滑异同平均线 * * MACD(数据, 快周期, 慢周期, 信号周期), 默认参数为(12, 26, 9), 返回二维数组, 分别是[DIF, DEA, MACD] - * - * @param {botvs.Record[]} Records - * @param {number} LongPeriod - * @param {number} ShortPeriod - * @param {number} SignalPeriod - * @return {[number[] , number[] , number[]]} */ function MACD( Records: botvs.Record[], @@ -663,12 +583,6 @@ declare global { * 随机指标 * * KDJ(数据, 周期1, 周期2, 周期3), 默认参数为(9, 3, 3), 返回二维数组, 分别是[K, D, J] - * - * @param {botvs.Record[]} Records - * @param {number} FirstPeriod - * @param {number} SecondPeriod - * @param {number} ThirdPeriod - * @return {[number[] , number[] , number[]]} */ function KDJ( Records: botvs.Record[], @@ -681,10 +595,6 @@ declare global { * 强弱指标 * * RSI(数据, 周期), 默认参数为14, 返回一个一维数组 - * - * @param {botvs.Record[]} Records - * @param {number} Period - * @return {number[]} */ function RSI(Records: botvs.Record[], Period?: number): number[]; @@ -692,10 +602,6 @@ declare global { * 平均真实波幅 * * ATR(数据, 周期), 默认参数为14, 返回一个一维数组 - * - * @param {botvs.Record[]} Records - * @param {number} Period - * @return {number[]} */ function ATR(Records: botvs.Record[], Period?: number): number[]; @@ -703,9 +609,6 @@ declare global { * 能量潮 * * OBV(数据), 返回一个一维数组 - * - * @param {botvs.Record[]} Records - * @return {[number[] , number[]]} */ function OBV(Records: botvs.Record[]): [number[], number[]]; @@ -713,20 +616,12 @@ declare global { * 移动平均线 * * MA(数据, 周期), 默认参数为9, 返回一个一维数组 - * - * @param {botvs.Record[]} Records - * @param {number} Period - * @return {number[]} */ function MA(Records: botvs.Record[], Period?: number): number[]; /** * 指数平均数指标 * EMA(数据, 周期), 默认参数为9, 返回一个一维数组 - * - * @param {botvs.Record[]} Records - * @param {number} Period - * @return {number[]} */ function EMA(Records: botvs.Record[], Period?: number): number[]; @@ -734,12 +629,6 @@ declare global { * Alligator Indicator * * Alligator(数据, 下颚周期,牙齿周期,上唇周期), 鳄鱼线指标, 默认参数为(13,8,5) 返回一个二维数组[下颚,牙齿,上唇] - * - * @param {botvs.Record[]} Records - * @param {number} JawPeriod - * @param {number} TeethPeriod - * @param {number} LibsPeriod - * @return {[number[] , number[] , number[]]} */ function Alligator( Records: botvs.Record[], @@ -752,10 +641,6 @@ declare global { * Chaikin Money Flow * * CMF(数据, 周期), 默认周期参数为20, 返回一个一维数组 - * - * @param {botvs.Record[]} Records - * @param {number} Period - * @return {number[]} */ function CMF(Records: botvs.Record[], Period?: number): number[]; @@ -764,12 +649,6 @@ declare global { * * Highest(数据, 周期, 属性), 返回最近周期内的最大值(不包含当前Bar), * 如TA.Highest(records, 30, 'High'), 如果周期为0指所有, 如属性不指定则视数据为普通数组 - * - * @param {botvs.Record[]} Records - * @param {number} Period - * @param {keyof botvs.Record} Property - * @return {number} - * @constructor */ function Highest(Records: botvs.Record[], Period?: number, Property?: keyof botvs.Record): number; @@ -777,11 +656,6 @@ declare global { * 周期最低价 * * Lowest(数据, 周期, 属性), 同上, 求最小值 - * - * @param {botvs.Record[]} Records - * @param {number} Period - * @param {keyof botvs.Record} Property - * @return {number} */ function Lowest(Records: botvs.Record[], Period?: number, Property?: keyof botvs.Record): number; } @@ -791,9 +665,6 @@ declare global { * 查询指标调用格式 * * Log(talib.help('MACD')); // 在回测环境下调用 - * - * @param {string} Func - * @return {string} */ function help(Func: string): string; @@ -801,9 +672,6 @@ declare global { * Vector Trigonometric ACos (反余弦函数) * * ACOS(Records[Close]) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function ACOS(Records: botvs.Record[] | number[]): number[]; @@ -811,21 +679,12 @@ declare global { * Chaikin A/D Line (线随机指标) * * AD(Records[High,Low,Close,Volume]) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function AD(Records: botvs.Record[]): number[]; /** * Chaikin A/D Line (线随机指标) * * AD(Records[High,Low,Close,Volume]) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number[]} Volume - * @return {number[]} */ function AD(High: number[], Low: number[], Close: number[], Volume: number[]): number[]; @@ -833,25 +692,12 @@ declare global { * Chaikin A/D Oscillator (佳庆指标) * * ADOSC(Records[High,Low,Close,Volume],Fast Period = 3,Slow Period = 10) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @param {number=3} FastPeriod - * @param {number=10} SlowPeriod - * @return {number[]} */ function ADOSC(Records: botvs.Record[], FastPeriod: number, SlowPeriod: number): number[]; /** * Chaikin A/D Oscillator (佳庆指标) * * ADOSC(Records[High,Low,Close,Volume],Fast Period = 3,Slow Period = 10) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number[]} Volume - * @param {number=3} FastPeriod - * @param {number=10} SlowPeriod - * @return {number[]} */ function ADOSC( High: number[], @@ -866,22 +712,12 @@ declare global { * Average Directional Movement Index (平均趋向指数) * * ADX(Records[High,Low,Close],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function ADX(Records: botvs.Record[], TimePeriod: number): number[]; /** * Average Directional Movement Index (平均趋向指数) * * ADX(Records[High,Low,Close],Time Period = 14) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=14} TimePeriod - * @return {number[]} */ function ADX(High: number[], Low: number[], Close: number[], TimePeriod: number): number[]; @@ -889,22 +725,12 @@ declare global { * Average Directional Movement Index Rating (评估指数) * * ADXR(Records[High,Low,Close],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function ADXR(Records: botvs.Record[], TimePeriod: number): number[]; /** * Average Directional Movement Index Rating (评估指数) * * ADXR(Records[High,Low,Close],Time Period = 14) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=14} TimePeriod - * @return {number[]} */ function ADXR(High: number[], Low: number[], Close: number[], TimePeriod: number): number[]; @@ -912,12 +738,6 @@ declare global { * Absolute Price Oscillator (绝对价格振荡指数) * * APO(Records[Close],Fast Period = 12,Slow Period = 26,MA Type = 0) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=12} FastPeriod - * @param {number=26} SlowPeriod - * @param {number=0} MAType - * @return {number[]} */ function APO( Records: botvs.Record[] | number[], @@ -930,21 +750,12 @@ declare global { * Aroon (阿隆指标) * * AROON(Records[High,Low],Time Period = 14) = [Array(outAroonDown),Array(outAroonUp)] - * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {[number[], number[]]} */ function AROON(Records: botvs.Record[], TimePeriod: number): [number[], number[]]; /** * Aroon (阿隆指标) * * AROON(Records[High,Low],Time Period = 14) = [Array(outAroonDown),Array(outAroonUp)] - * - * @param {number[]} High - * @param {number[]} Low - * @param {number=14} TimePeriod - * @return {[number[], number[]]} */ function AROON(High: number[], Low: number[], TimePeriod: number): [number[], number[]]; @@ -952,21 +763,12 @@ declare global { * Aroon Oscillator (阿隆震荡线) * * AROONOSC(Records[High,Low],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function AROONOSC(Records: botvs.Record[], TimePeriod: number): number[]; /** * Aroon Oscillator (阿隆震荡线) * * AROONOSC(Records[High,Low],Time Period = 14) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number=14} TimePeriod - * @return {number[]} */ function AROONOSC(High: number[], Low: number[], TimePeriod: number): number[]; @@ -974,9 +776,6 @@ declare global { * Vector Trigonometric ASin (反正弦函数) * * ASIN(Records[Close]) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function ASIN(Records: botvs.Record[] | number[]): number[]; @@ -984,9 +783,6 @@ declare global { * Vector Trigonometric ATan (反正切函数) * * ATAN(Records[Close]) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function ATAN(Records: botvs.Record[] | number[]): number[]; @@ -994,22 +790,12 @@ declare global { * Average True Range (平均真实波幅) * * ATR(Records[High,Low,Close],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function ATR(Records: botvs.Record[], TimePeriod: number): number[]; /** * Average True Range (平均真实波幅) * * ATR(Records[High,Low,Close],Time Period = 14) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=14} TimePeriod - * @return {number[]} */ function ATR(High: number[], Low: number[], Close: number[], TimePeriod: number): number[]; @@ -1017,21 +803,12 @@ declare global { * Average Price (平均价格) * * AVGPRICE(Records[Open,High,Low,Close]) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function AVGPRICE(Records: botvs.Record[]): number[]; /** * Average Price (平均价格) * * AVGPRICE(Records[Open,High,Low,Close]) = Array(outReal) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function AVGPRICE(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1040,13 +817,6 @@ declare global { * * BBANDS(Records[Close],Time Period = 5,Deviations up = 2,Deviations down = 2,MA Type = 0) = * [Array(outRealUpperBand),Array(outRealMiddleBand),Array(outRealLowerBand)] - * - * @param {botvs.Record[]|number[]} Records - * @param {number=5} TimePeriod - * @param {number=2} Deviationsup - * @param {number=2} Deviationsdown - * @param {number=0} MAType - * @return {[number[], number[], number[]]} */ function BBANDS( Records: botvs.Record[] | number[], @@ -1060,21 +830,12 @@ declare global { * Balance Of Power (均势指标) * * BOP(Records[Open,High,Low,Close]) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function BOP(Records: botvs.Record[]): number[]; /** * Balance Of Power (均势指标) * * BOP(Records[Open,High,Low,Close]) = Array(outReal) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function BOP(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1082,22 +843,12 @@ declare global { * Commodity Channel Index (顺势指标) * * CCI(Records[High,Low,Close],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function CCI(Records: botvs.Record[], TimePeriod: number): number[]; /** * Commodity Channel Index (顺势指标) * * CCI(Records[High,Low,Close],Time Period = 14) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=14} TimePeriod - * @return {number[]} */ function CCI(High: number[], Low: number[], Close: number[], TimePeriod: number): number[]; @@ -1105,21 +856,12 @@ declare global { * Two Crows (K线图--两只乌鸦) * * CDL2CROWS(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDL2CROWS(Records: botvs.Record[]): number[]; /** * Two Crows (K线图--两只乌鸦) * * CDL2CROWS(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDL2CROWS(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1127,21 +869,12 @@ declare global { * Three Black Crows (K线图--3只黑乌鸦) * * CDL3BLACKCROWS(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDL3BLACKCROWS(Records: botvs.Record[]): number[]; /** * Three Black Crows (K线图--3只黑乌鸦) * * CDL3BLACKCROWS(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDL3BLACKCROWS(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1149,21 +882,12 @@ declare global { * Three Inside Up/Down (K线图:3内上下震荡) * * CDL3INSIDE(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDL3INSIDE(Records: botvs.Record[]): number[]; /** * Three Inside Up/Down (K线图:3内上下震荡) * * CDL3INSIDE(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDL3INSIDE(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1171,21 +895,12 @@ declare global { * Three-Line Strike (K线图:3线震荡) * * CDL3LINESTRIKE(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDL3LINESTRIKE(Records: botvs.Record[]): number[]; /** * Three-Line Strike (K线图:3线震荡) * * CDL3LINESTRIKE(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDL3LINESTRIKE(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1193,21 +908,12 @@ declare global { * Three Outside Up/Down (K线图:3外下震荡) * * CDL3OUTSIDE(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDL3OUTSIDE(Records: botvs.Record[]): number[]; /** * Three Outside Up/Down (K线图:3外下震荡) * * CDL3OUTSIDE(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDL3OUTSIDE(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1215,21 +921,12 @@ declare global { * Three Stars In The South (K线图:南方三星) * * CDL3STARSINSOUTH(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDL3STARSINSOUTH(Records: botvs.Record[]): number[]; /** * Three Stars In The South (K线图:南方三星) * * CDL3STARSINSOUTH(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDL3STARSINSOUTH(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1237,21 +934,12 @@ declare global { * Three Advancing White Soldiers (K线图:三白兵) * * CDL3WHITESOLDIERS(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDL3WHITESOLDIERS(Records: botvs.Record[]): number[]; /** * Three Advancing White Soldiers (K线图:三白兵) * * CDL3WHITESOLDIERS(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDL3WHITESOLDIERS(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1259,23 +947,12 @@ declare global { * Abandoned Baby (K线图:弃婴) * * CDLABANDONEDBABY(Records[Open,High,Low,Close],Penetration = 0.3) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @param {number=0.3} Penetration - * @return {number[]} */ function CDLABANDONEDBABY(Records: botvs.Record[], Penetration: number): number[]; /** * Abandoned Baby (K线图:弃婴) * * CDLABANDONEDBABY(Records[Open,High,Low,Close],Penetration = 0.3) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=0.3} Penetration - * @return {number[]} */ function CDLABANDONEDBABY( Open: number[], @@ -1289,21 +966,12 @@ declare global { * Advance Block (K线图:推进) * * CDLADVANCEBLOCK(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLADVANCEBLOCK(Records: botvs.Record[]): number[]; /** * Advance Block (K线图:推进) * * CDLADVANCEBLOCK(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLADVANCEBLOCK(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1311,21 +979,12 @@ declare global { * Belt-hold (K线图:带住) * * CDLBELTHOLD(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLBELTHOLD(Records: botvs.Record[]): number[]; /** * Belt-hold (K线图:带住) * * CDLBELTHOLD(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLBELTHOLD(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1333,21 +992,12 @@ declare global { * Breakaway (K线图:分离) * * CDLBREAKAWAY(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLBREAKAWAY(Records: botvs.Record[]): number[]; /** * Breakaway (K线图:分离) * * CDLBREAKAWAY(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLBREAKAWAY(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1355,21 +1005,12 @@ declare global { * Closing Marubozu (K线图:收盘光头光脚) * * CDLCLOSINGMARUBOZU(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLCLOSINGMARUBOZU(Records: botvs.Record[]): number[]; /** * Closing Marubozu (K线图:收盘光头光脚) * * CDLCLOSINGMARUBOZU(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLCLOSINGMARUBOZU(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1377,21 +1018,12 @@ declare global { * Concealing Baby Swallow (K线图:藏婴吞没形态) * * CDLCONCEALBABYSWALL(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLCONCEALBABYSWALL(Records: botvs.Record[]): number[]; /** * Concealing Baby Swallow (K线图:藏婴吞没形态) * * CDLCONCEALBABYSWALL(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLCONCEALBABYSWALL(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1399,21 +1031,12 @@ declare global { * Counterattack (K线图:反击) * * CDLCOUNTERATTACK(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLCOUNTERATTACK(Records: botvs.Record[]): number[]; /** * Counterattack (K线图:反击) * * CDLCOUNTERATTACK(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLCOUNTERATTACK(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1421,23 +1044,12 @@ declare global { * Dark Cloud Cover (K线图:乌云盖) * * CDLDARKCLOUDCOVER(Records[Open,High,Low,Close],Penetration = 0.5) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @param {number=0.5} Penetration - * @return {number[]} */ function CDLDARKCLOUDCOVER(Records: botvs.Record[], Penetration: number): number[]; /** * Dark Cloud Cover (K线图:乌云盖) * * CDLDARKCLOUDCOVER(Records[Open,High,Low,Close],Penetration = 0.5) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=0.5} Penetration - * @return {number[]} */ function CDLDARKCLOUDCOVER( Open: number[], @@ -1451,21 +1063,12 @@ declare global { * Doji (K线图:十字星 ) * * CDLDOJI(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLDOJI(Records: botvs.Record[]): number[]; /** * Doji (K线图:十字星 ) * * CDLDOJI(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLDOJI(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1473,21 +1076,12 @@ declare global { * Doji Star (K线图:十字星) * * CDLDOJISTAR(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLDOJISTAR(Records: botvs.Record[]): number[]; /** * Doji Star (K线图:十字星) * * CDLDOJISTAR(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLDOJISTAR(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1495,21 +1089,12 @@ declare global { * Dragonfly Doji (K线图:蜻蜓十字星) * * CDLDRAGONFLYDOJI(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLDRAGONFLYDOJI(Records: botvs.Record[]): number[]; /** * Dragonfly Doji (K线图:蜻蜓十字星) * * CDLDRAGONFLYDOJI(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLDRAGONFLYDOJI(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1517,21 +1102,12 @@ declare global { * Engulfing Pattern (K线图:吞没) * * CDLENGULFING(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLENGULFING(Records: botvs.Record[]): number[]; /** * Engulfing Pattern (K线图:吞没) * * CDLENGULFING(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLENGULFING(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1539,23 +1115,12 @@ declare global { * Evening Doji Star (K线图:黄昏十字星) * * CDLEVENINGDOJISTAR(Records[Open,High,Low,Close],Penetration = 0.3) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @param {number=0.3} Penetration - * @return {number[]} */ function CDLEVENINGDOJISTAR(Records: botvs.Record[], Penetration: number): number[]; /** * Evening Doji Star (K线图:黄昏十字星) * * CDLEVENINGDOJISTAR(Records[Open,High,Low,Close],Penetration = 0.3) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=0.3} Penetration - * @return {number[]} */ function CDLEVENINGDOJISTAR( Open: number[], @@ -1569,23 +1134,12 @@ declare global { * Evening Star (K线图:黄昏之星) * * CDLEVENINGSTAR(Records[Open,High,Low,Close],Penetration = 0.3) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @param {number=0.3} Penetration - * @return {number[]} */ function CDLEVENINGSTAR(Records: botvs.Record[], Penetration: number): number[]; /** * Evening Star (K线图:黄昏之星) * * CDLEVENINGSTAR(Records[Open,High,Low,Close],Penetration = 0.3) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=0.3} Penetration - * @return {number[]} */ function CDLEVENINGSTAR( Open: number[], @@ -1599,21 +1153,12 @@ declare global { * Up/Down-gap side-by-side white lines (K线图:上/下间隙并排的白色线条) * * CDLGAPSIDESIDEWHITE(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLGAPSIDESIDEWHITE(Records: botvs.Record[]): number[]; /** * Up/Down-gap side-by-side white lines (K线图:上/下间隙并排的白色线条) * * CDLGAPSIDESIDEWHITE(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLGAPSIDESIDEWHITE(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1621,21 +1166,12 @@ declare global { * Gravestone Doji (K线图:墓碑十字线) * * CDLGRAVESTONEDOJI(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLGRAVESTONEDOJI(Records: botvs.Record[]): number[]; /** * Gravestone Doji (K线图:墓碑十字线) * * CDLGRAVESTONEDOJI(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLGRAVESTONEDOJI(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1643,21 +1179,12 @@ declare global { * Hammer (K线图:锤) * * CDLHAMMER(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLHAMMER(Records: botvs.Record[]): number[]; /** * Hammer (K线图:锤) * * CDLHAMMER(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLHAMMER(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1665,21 +1192,12 @@ declare global { * Hanging Man (K线图:吊人) * * CDLHANGINGMAN(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLHANGINGMAN(Records: botvs.Record[]): number[]; /** * Hanging Man (K线图:吊人) * * CDLHANGINGMAN(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLHANGINGMAN(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1687,21 +1205,12 @@ declare global { * Harami Pattern (K线图:阴阳线) * * CDLHARAMI(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLHARAMI(Records: botvs.Record[]): number[]; /** * Harami Pattern (K线图:阴阳线) * * CDLHARAMI(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLHARAMI(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1709,21 +1218,12 @@ declare global { * Harami Cross Pattern (K线图:交叉阴阳线) * * CDLHARAMICROSS(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLHARAMICROSS(Records: botvs.Record[]): number[]; /** * Harami Cross Pattern (K线图:交叉阴阳线) * * CDLHARAMICROSS(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLHARAMICROSS(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1731,21 +1231,12 @@ declare global { * High-Wave Candle (K线图:长脚十字线 ) * * CDLHIGHWAVE(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLHIGHWAVE(Records: botvs.Record[]): number[]; /** * High-Wave Candle (K线图:长脚十字线 ) * * CDLHIGHWAVE(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLHIGHWAVE(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1753,21 +1244,12 @@ declare global { * Hikkake Pattern (K线图:陷阱) * * CDLHIKKAKE(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLHIKKAKE(Records: botvs.Record[]): number[]; /** * Hikkake Pattern (K线图:陷阱) * * CDLHIKKAKE(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLHIKKAKE(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1775,21 +1257,12 @@ declare global { * Modified Hikkake Pattern (K线图:改良的陷阱) * * CDLHIKKAKEMOD(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLHIKKAKEMOD(Records: botvs.Record[]): number[]; /** * Modified Hikkake Pattern (K线图:改良的陷阱) * * CDLHIKKAKEMOD(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLHIKKAKEMOD(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1797,21 +1270,12 @@ declare global { * Homing Pigeon (K线图:信鸽) * * CDLHOMINGPIGEON(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLHOMINGPIGEON(Records: botvs.Record[]): number[]; /** * Homing Pigeon (K线图:信鸽) * * CDLHOMINGPIGEON(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLHOMINGPIGEON(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1819,21 +1283,12 @@ declare global { * Identical Three Crows (K线图:相同的三只乌鸦) * * CDLIDENTICAL3CROWS(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLIDENTICAL3CROWS(Records: botvs.Record[]): number[]; /** * Identical Three Crows (K线图:相同的三只乌鸦) * * CDLIDENTICAL3CROWS(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLIDENTICAL3CROWS(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1841,21 +1296,12 @@ declare global { * In-Neck Pattern (K线图:颈纹) * * CDLINNECK(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLINNECK(Records: botvs.Record[]): number[]; /** * In-Neck Pattern (K线图:颈纹) * * CDLINNECK(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLINNECK(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1863,21 +1309,12 @@ declare global { * Inverted Hammer (K线图:倒锤) * * CDLINVERTEDHAMMER(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLINVERTEDHAMMER(Records: botvs.Record[]): number[]; /** * Inverted Hammer (K线图:倒锤) * * CDLINVERTEDHAMMER(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLINVERTEDHAMMER(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1885,21 +1322,12 @@ declare global { * Kicking (K线图:踢) * * CDLKICKING(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLKICKING(Records: botvs.Record[]): number[]; /** * Kicking (K线图:踢) * * CDLKICKING(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLKICKING(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1907,21 +1335,12 @@ declare global { * Kicking - bull/bear determined by the longer marubozu (K线图:踢牛/踢熊) * * CDLKICKINGBYLENGTH(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLKICKINGBYLENGTH(Records: botvs.Record[]): number[]; /** * Kicking - bull/bear determined by the longer marubozu (K线图:踢牛/踢熊) * * CDLKICKINGBYLENGTH(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLKICKINGBYLENGTH(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1929,21 +1348,12 @@ declare global { * Ladder Bottom (K线图:梯底) * * CDLLADDERBOTTOM(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLLADDERBOTTOM(Records: botvs.Record[]): number[]; /** * Ladder Bottom (K线图:梯底) * * CDLLADDERBOTTOM(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLLADDERBOTTOM(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1951,21 +1361,12 @@ declare global { * Long Legged Doji (K线图:长腿十字线) * * CDLLONGLEGGEDDOJI(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLLONGLEGGEDDOJI(Records: botvs.Record[]): number[]; /** * Long Legged Doji (K线图:长腿十字线) * * CDLLONGLEGGEDDOJI(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLLONGLEGGEDDOJI(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1973,21 +1374,12 @@ declare global { * Long Line Candle (K线图:长线) * * CDLLONGLINE(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLLONGLINE(Records: botvs.Record[]): number[]; /** * Long Line Candle (K线图:长线) * * CDLLONGLINE(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLLONGLINE(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1995,21 +1387,12 @@ declare global { * Marubozu (K线图:光头光脚 ) * * CDLMARUBOZU(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLMARUBOZU(Records: botvs.Record[]): number[]; /** * Marubozu (K线图:光头光脚 ) * * CDLMARUBOZU(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLMARUBOZU(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2017,21 +1400,12 @@ declare global { * Matching Low (K线图:匹配低) * * CDLMATCHINGLOW(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLMATCHINGLOW(Records: botvs.Record[]): number[]; /** * Matching Low (K线图:匹配低) * * CDLMATCHINGLOW(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLMATCHINGLOW(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2039,23 +1413,12 @@ declare global { * Mat Hold (K线图:垫住) * * CDLMATHOLD(Records[Open,High,Low,Close],Penetration = 0.5) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @param {number=0.5} Penetration - * @return {number[]} */ function CDLMATHOLD(Records: botvs.Record[], Penetration: number): number[]; /** * Mat Hold (K线图:垫住) * * CDLMATHOLD(Records[Open,High,Low,Close],Penetration = 0.5) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=0.5} Penetration - * @return {number[]} */ function CDLMATHOLD( Open: number[], @@ -2069,23 +1432,12 @@ declare global { * Morning Doji Star (K线图:早晨十字星) * * CDLMORNINGDOJISTAR(Records[Open,High,Low,Close],Penetration = 0.3) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @param {number=0.3} Penetration - * @return {number[]} */ function CDLMORNINGDOJISTAR(Records: botvs.Record[], Penetration: number): number[]; /** * Morning Doji Star (K线图:早晨十字星) * * CDLMORNINGDOJISTAR(Records[Open,High,Low,Close],Penetration = 0.3) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=0.3} Penetration - * @return {number[]} */ function CDLMORNINGDOJISTAR( Open: number[], @@ -2099,23 +1451,12 @@ declare global { * Morning Star (K线图:晨星) * * CDLMORNINGSTAR(Records[Open,High,Low,Close],Penetration = 0.3) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @param {number=0.3} Penetration - * @return {number[]} */ function CDLMORNINGSTAR(Records: botvs.Record[], Penetration: number): number[]; /** * Morning Star (K线图:晨星) * * CDLMORNINGSTAR(Records[Open,High,Low,Close],Penetration = 0.3) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=0.3} Penetration - * @return {number[]} */ function CDLMORNINGSTAR( Open: number[], @@ -2129,21 +1470,12 @@ declare global { * On-Neck Pattern (K线图:颈型) * * CDLONNECK(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLONNECK(Records: botvs.Record[]): number[]; /** * On-Neck Pattern (K线图:颈型) * * CDLONNECK(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLONNECK(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2151,21 +1483,12 @@ declare global { * Piercing Pattern (K线图:穿孔模式) * * CDLPIERCING(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLPIERCING(Records: botvs.Record[]): number[]; /** * Piercing Pattern (K线图:穿孔模式) * * CDLPIERCING(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLPIERCING(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2173,21 +1496,12 @@ declare global { * Rickshaw Man (K线图:车夫) * * CDLRICKSHAWMAN(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLRICKSHAWMAN(Records: botvs.Record[]): number[]; /** * Rickshaw Man (K线图:车夫) * * CDLRICKSHAWMAN(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLRICKSHAWMAN(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2195,21 +1509,12 @@ declare global { * Rising/Falling Three Methods (K线图:上升/下降三法) * * CDLRISEFALL3METHODS(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLRISEFALL3METHODS(Records: botvs.Record[]): number[]; /** * Rising/Falling Three Methods (K线图:上升/下降三法) * * CDLRISEFALL3METHODS(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLRISEFALL3METHODS(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2217,21 +1522,12 @@ declare global { * Separating Lines (K线图:分割线) * * CDLSEPARATINGLINES(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLSEPARATINGLINES(Records: botvs.Record[]): number[]; /** * Separating Lines (K线图:分割线) * * CDLSEPARATINGLINES(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLSEPARATINGLINES(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2239,21 +1535,12 @@ declare global { * Shooting Star (K线图:流星) * * CDLSHOOTINGSTAR(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLSHOOTINGSTAR(Records: botvs.Record[]): number[]; /** * Shooting Star (K线图:流星) * * CDLSHOOTINGSTAR(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLSHOOTINGSTAR(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2261,21 +1548,12 @@ declare global { * Short Line Candle (K线图:短线) * * CDLSHORTLINE(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLSHORTLINE(Records: botvs.Record[]): number[]; /** * Short Line Candle (K线图:短线) * * CDLSHORTLINE(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLSHORTLINE(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2283,21 +1561,12 @@ declare global { * Spinning Top (K线图:陀螺) * * CDLSPINNINGTOP(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLSPINNINGTOP(Records: botvs.Record[]): number[]; /** * Spinning Top (K线图:陀螺) * * CDLSPINNINGTOP(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLSPINNINGTOP(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2305,21 +1574,12 @@ declare global { * Stalled Pattern (K线图:停滞模式) * * CDLSTALLEDPATTERN(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLSTALLEDPATTERN(Records: botvs.Record[]): number[]; /** * Stalled Pattern (K线图:停滞模式) * * CDLSTALLEDPATTERN(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLSTALLEDPATTERN(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2327,21 +1587,12 @@ declare global { * Stick Sandwich (K线图:棍子三明治) * * CDLSTICKSANDWICH(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLSTICKSANDWICH(Records: botvs.Record[]): number[]; /** * Stick Sandwich (K线图:棍子三明治) * * CDLSTICKSANDWICH(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLSTICKSANDWICH(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2349,21 +1600,12 @@ declare global { * Takuri (Dragonfly Doji with very long lower shadow) (K线图:托里) * * CDLTAKURI(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLTAKURI(Records: botvs.Record[]): number[]; /** * Takuri (Dragonfly Doji with very long lower shadow) (K线图:托里) * * CDLTAKURI(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLTAKURI(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2371,21 +1613,12 @@ declare global { * Tasuki Gap (K线图:翼隙) * * CDLTASUKIGAP(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLTASUKIGAP(Records: botvs.Record[]): number[]; /** * Tasuki Gap (K线图:翼隙) * * CDLTASUKIGAP(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLTASUKIGAP(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2393,21 +1626,12 @@ declare global { * Thrusting Pattern (K线图:推模式) * * CDLTHRUSTING(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLTHRUSTING(Records: botvs.Record[]): number[]; /** * Thrusting Pattern (K线图:推模式) * * CDLTHRUSTING(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLTHRUSTING(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2415,21 +1639,12 @@ declare global { * Tristar Pattern (K线图:三星模式) * * CDLTRISTAR(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLTRISTAR(Records: botvs.Record[]): number[]; /** * Tristar Pattern (K线图:三星模式) * * CDLTRISTAR(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLTRISTAR(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2437,21 +1652,12 @@ declare global { * Unique 3 River (K线图:独特的3河) * * CDLUNIQUE3RIVER(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLUNIQUE3RIVER(Records: botvs.Record[]): number[]; /** * Unique 3 River (K线图:独特的3河) * * CDLUNIQUE3RIVER(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLUNIQUE3RIVER(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2459,21 +1665,12 @@ declare global { * Upside Gap Two Crows (K线图:双飞乌鸦) * * CDLUPSIDEGAP2CROWS(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLUPSIDEGAP2CROWS(Records: botvs.Record[]): number[]; /** * Upside Gap Two Crows (K线图:双飞乌鸦) * * CDLUPSIDEGAP2CROWS(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLUPSIDEGAP2CROWS(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2481,21 +1678,12 @@ declare global { * Upside/Downside Gap Three Methods (K线图:上行/下行缺口三方法) * * CDLXSIDEGAP3METHODS(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLXSIDEGAP3METHODS(Records: botvs.Record[]): number[]; /** * Upside/Downside Gap Three Methods (K线图:上行/下行缺口三方法) * * CDLXSIDEGAP3METHODS(Records[Open,High,Low,Close]) = Array(outInteger) - * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLXSIDEGAP3METHODS(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2503,9 +1691,6 @@ declare global { * Vector Ceil (取整函数) * * CEIL(Records[Close]) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function CEIL(Records: botvs.Record[] | number[]): number[]; @@ -2513,10 +1698,6 @@ declare global { * Chande Momentum Oscillator (钱德动量摆动指标) * * CMO(Records[Close],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function CMO(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2524,9 +1705,6 @@ declare global { * Vector Trigonometric Cos (余弦函数) * * COS(Records[Close]) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function COS(Records: botvs.Record[] | number[]): number[]; @@ -2534,9 +1712,6 @@ declare global { * Vector Trigonometric Cosh (双曲余弦值) * * COSH(Records[Close]) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function COSH(Records: botvs.Record[] | number[]): number[]; @@ -2544,10 +1719,6 @@ declare global { * Double Exponential Moving Average (双指数移动平均线) * * DEMA(Records[Close],Time Period = 30) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function DEMA(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2555,22 +1726,12 @@ declare global { * Directional Movement Index (动向指数) * * DX(Records[High,Low,Close],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function DX(Records: botvs.Record[], TimePeriod: number): number[]; /** * Directional Movement Index (动向指数) * * DX(Records[High,Low,Close],Time Period = 14) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=14} TimePeriod - * @return {number[]} */ function DX(High: number[], Low: number[], Close: number[], TimePeriod: number): number[]; @@ -2578,10 +1739,6 @@ declare global { * Exponential Moving Average (指数移动平均线) * * EMA(Records[Close],Time Period = 30) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function EMA(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2589,9 +1746,6 @@ declare global { * Vector Arithmetic Exp (指数函数) * * EXP(Records[Close]) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function EXP(Records: botvs.Record[] | number[]): number[]; @@ -2599,9 +1753,6 @@ declare global { * Vector Floor (向下取整) * * FLOOR(Records[Close]) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function FLOOR(Records: botvs.Record[] | number[]): number[]; @@ -2609,9 +1760,6 @@ declare global { * Hilbert Transform - Dominant Cycle Period (希尔伯特变换, 主周期) * * HT_DCPERIOD(Records[Close]) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function HT_DCPERIOD(Records: botvs.Record[] | number[]): number[]; @@ -2619,9 +1767,6 @@ declare global { * Hilbert Transform - Dominant Cycle Phase (希尔伯特变换,主阶段) * * HT_DCPHASE(Records[Close]) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function HT_DCPHASE(Records: botvs.Record[] | number[]): number[]; @@ -2629,9 +1774,6 @@ declare global { * Hilbert Transform - Phasor Components (希尔伯特变换,相成分) * * HT_PHASOR(Records[Close]) = [Array(outInPhase),Array(outQuadrature)] - * - * @param {botvs.Record[]|number[]} Records - * @return {[number[], number[]]} */ function HT_PHASOR(Records: botvs.Record[] | number[]): [number[], number[]]; @@ -2639,9 +1781,6 @@ declare global { * Hilbert Transform - SineWave (希尔伯特变换,正弦波) * * HT_SINE(Records[Close]) = [Array(outSine),Array(outLeadSine)] - * - * @param {botvs.Record[]|number[]} Records - * @return {[number[], number[]]} */ function HT_SINE(Records: botvs.Record[] | number[]): [number[], number[]]; @@ -2649,9 +1788,6 @@ declare global { * Hilbert Transform - Instantaneous Trendline (希尔伯特变换,瞬时趋势) * * HT_TRENDLINE(Records[Close]) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function HT_TRENDLINE(Records: botvs.Record[] | number[]): number[]; @@ -2659,9 +1795,6 @@ declare global { * Hilbert Transform - Trend vs Cycle Mode (希尔伯特变换-趋势与周期模式) * * HT_TRENDMODE(Records[Close]) = Array(outInteger) - * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function HT_TRENDMODE(Records: botvs.Record[] | number[]): number[]; @@ -2669,10 +1802,6 @@ declare global { * Kaufman Adaptive Moving Average (适应性移动平均线) * * KAMA(Records[Close],Time Period = 30) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function KAMA(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2680,10 +1809,6 @@ declare global { * Linear Regression (线性回归) * * LINEARREG(Records[Close],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function LINEARREG(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2691,10 +1816,6 @@ declare global { * Linear Regression Angle (线性回归的角度) * * LINEARREG_ANGLE(Records[Close],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function LINEARREG_ANGLE(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2702,10 +1823,6 @@ declare global { * Linear Regression Intercept (线性回归截距) * * LINEARREG_INTERCEPT(Records[Close],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function LINEARREG_INTERCEPT(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2713,10 +1830,6 @@ declare global { * Linear Regression Slope (线性回归斜率) * * LINEARREG_SLOPE(Records[Close],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function LINEARREG_SLOPE(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2724,9 +1837,6 @@ declare global { * Vector Log Natural (自然对数) * * LN(Records[Close]) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function LN(Records: botvs.Record[] | number[]): number[]; @@ -2734,9 +1844,6 @@ declare global { * Vector Log10 (对数函数) * * LOG10(Records[Close]) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function LOG10(Records: botvs.Record[] | number[]): number[]; @@ -2744,11 +1851,6 @@ declare global { * Moving average (移动平均线) * * MA(Records[Close],Time Period = 30,MA Type = 0) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @param {number=0} MAType - * @return {number[]} */ function MA(Records: botvs.Record[] | number[], TimePeriod: number, MAType: number): number[]; @@ -2757,12 +1859,6 @@ declare global { * * MACD(Records[Close],Fast Period = 12,Slow Period = 26,Signal Period = 9) = * [Array(outMACD),Array(outMACDSignal),Array(outMACDHist)] - * - * @param {botvs.Record[]|number[]} Records - * @param {number=12} FastPeriod - * @param {number=26} SlowPeriod - * @param {number=9} SignalPeriod - * @return {[number[], number[], number[]]} */ function MACD( Records: botvs.Record[] | number[], @@ -2777,15 +1873,6 @@ declare global { * MACDEXT(Records[Close],Fast Period = 12,Fast MA = 0,Slow Period = 26,Slow MA = 0,Signal Period = 9,Signal MA * = * 0) = [Array(outMACD),Array(outMACDSignal),Array(outMACDHist)] - * - * @param {botvs.Record[]|number[]} Records - * @param {number=12} FastPeriod - * @param {number=0} FastMA - * @param {number=26} SlowPeriod - * @param {number=0} SlowMA - * @param {number=9} SignalPeriod - * @param {number=0} SignalMA - * @return {[number[], number[], number[]]} */ function MACDEXT( Records: botvs.Record[] | number[], @@ -2801,10 +1888,6 @@ declare global { * Moving Average Convergence/Divergence Fix 12/26 (移动平均收敛/发散修复12/26) * * MACDFIX(Records[Close],Signal Period = 9) = [Array(outMACD),Array(outMACDSignal),Array(outMACDHist)] - * - * @param {botvs.Record[]|number[]} Records - * @param {number=9} SignalPeriod - * @return {[number[], number[], number[]]} */ function MACDFIX(Records: botvs.Record[] | number[], SignalPeriod: number): [number[], number[], number[]]; @@ -2812,11 +1895,6 @@ declare global { * MESA Adaptive Moving Average (MESA 移动平均线) * * MAMA(Records[Close],Fast Limit = 0.5,Slow Limit = 0.05) = [Array(outMAMA),Array(outFAMA)] - * - * @param {botvs.Record[]|number[]} Records - * @param {number=0.5} FastLimit - * @param {number=0.05} SlowLimit - * @return {[number[], number[]]} */ function MAMA(Records: botvs.Record[] | number[], FastLimit: number, SlowLimit: number): [number[], number[]]; @@ -2824,10 +1902,6 @@ declare global { * Highest value over a specified period (最大值) * * MAX(Records[Close],Time Period = 30) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function MAX(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2835,10 +1909,6 @@ declare global { * Index of highest value over a specified period (最大值索引) * * MAXINDEX(Records[Close],Time Period = 30) = Array(outInteger) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function MAXINDEX(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2846,19 +1916,12 @@ declare global { * Median Price (中位数价格) * * MEDPRICE(Records[High,Low]) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function MEDPRICE(Records: botvs.Record[]): number[]; /** * Median Price (中位数价格) * * MEDPRICE(Records[High,Low]) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @return {number[]} */ function MEDPRICE(High: number[], Low: number[]): number[]; @@ -2866,23 +1929,12 @@ declare global { * Money Flow Index (货币流量指数) * * MFI(Records[High,Low,Close,Volume],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function MFI(Records: botvs.Record[], TimePeriod: number): number[]; /** * Money Flow Index (货币流量指数) * * MFI(Records[High,Low,Close,Volume],Time Period = 14) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number[]} Volume - * @param {number=14} TimePeriod - * @return {number[]} */ function MFI(High: number[], Low: number[], Close: number[], Volume: number[], TimePeriod: number): number[]; @@ -2890,10 +1942,6 @@ declare global { * MidPoint over period (中点) * * MIDPOINT(Records[Close],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function MIDPOINT(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2901,21 +1949,12 @@ declare global { * Midpoint Price over period (中点价格) * * MIDPRICE(Records[High,Low],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function MIDPRICE(Records: botvs.Record[], TimePeriod: number): number[]; /** * Midpoint Price over period (中点价格) * * MIDPRICE(Records[High,Low],Time Period = 14) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number=14} TimePeriod - * @return {number[]} */ function MIDPRICE(High: number[], Low: number[], TimePeriod: number): number[]; @@ -2923,10 +1962,6 @@ declare global { * Lowest value over a specified period (最小值) * * MIN(Records[Close],Time Period = 30) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function MIN(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2934,10 +1969,6 @@ declare global { * Index of lowest value over a specified period (最小值索引) * * MININDEX(Records[Close],Time Period = 30) = Array(outInteger) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function MININDEX(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2945,10 +1976,6 @@ declare global { * Lowest and highest values over a specified period (最小最大值) * * MINMAX(Records[Close],Time Period = 30) = [Array(outMin),Array(outMax)] - * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {[number[], number[]]} */ function MINMAX(Records: botvs.Record[] | number[], TimePeriod: number): [number[], number[]]; @@ -2956,10 +1983,6 @@ declare global { * Indexes of lowest and highest values over a specified period (最小最大值索引) * * MINMAXINDEX(Records[Close],Time Period = 30) = [Array(outMinIdx),Array(outMaxIdx)] - * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {[number[], number[]]} */ function MINMAXINDEX(Records: botvs.Record[] | number[], TimePeriod: number): [number[], number[]]; @@ -2967,22 +1990,12 @@ declare global { * Minus Directional Indicator (负向指标) * * MINUS_DI(Records[High,Low,Close],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function MINUS_DI(Records: botvs.Record[], TimePeriod: number): number[]; /** * Minus Directional Indicator (负向指标) * * MINUS_DI(Records[High,Low,Close],Time Period = 14) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=14} TimePeriod - * @return {number[]} */ function MINUS_DI(High: number[], Low: number[], Close: number[], TimePeriod: number): number[]; @@ -2990,21 +2003,12 @@ declare global { * Minus Directional Movement (负向运动) * * MINUS_DM(Records[High,Low],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function MINUS_DM(Records: botvs.Record[], TimePeriod: number): number[]; /** * Minus Directional Movement (负向运动) * * MINUS_DM(Records[High,Low],Time Period = 14) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number=14} TimePeriod - * @return {number[]} */ function MINUS_DM(High: number[], Low: number[], TimePeriod: number): number[]; @@ -3012,10 +2016,6 @@ declare global { * Momentum (动量) * * MOM(Records[Close],Time Period = 10) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=10} TimePeriod - * @return {number[]} */ function MOM(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3023,22 +2023,12 @@ declare global { * Normalized Average True Range (归一化平均值范围) * * NATR(Records[High,Low,Close],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function NATR(Records: botvs.Record[], TimePeriod: number): number[]; /** * Normalized Average True Range (归一化平均值范围) * * NATR(Records[High,Low,Close],Time Period = 14) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=14} TimePeriod - * @return {number[]} */ function NATR(High: number[], Low: number[], Close: number[], TimePeriod: number): number[]; @@ -3046,9 +2036,6 @@ declare global { * On Balance Volume (能量潮) * * OBV(Records[Close],Records[Volume]) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function OBV(Records: botvs.Record[]): number[]; @@ -3056,10 +2043,6 @@ declare global { * On Balance Volume (能量潮) * * OBV(Records[Close],Records[Volume]) = Array(outReal) - * - * @param {number[]} Close - * @param {number[]} Volume - * @return {number[]} */ function OBV(Close: number[], Volume: number[]): number[]; @@ -3067,22 +2050,12 @@ declare global { * Plus Directional Indicator (更向指示器) * * PLUS_DI(Records[High,Low,Close],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function PLUS_DI(Records: botvs.Record[], TimePeriod: number): number[]; /** * Plus Directional Indicator (更向指示器) * * PLUS_DI(Records[High,Low,Close],Time Period = 14) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=14} TimePeriod - * @return {number[]} */ function PLUS_DI(High: number[], Low: number[], Close: number[], TimePeriod: number): number[]; @@ -3090,21 +2063,12 @@ declare global { * Plus Directional Movement (定向运动) * * PLUS_DM(Records[High,Low],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function PLUS_DM(Records: botvs.Record[], TimePeriod: number): number[]; /** * Plus Directional Movement (定向运动) * * PLUS_DM(Records[High,Low],Time Period = 14) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number=14} TimePeriod - * @return {number[]} */ function PLUS_DM(High: number[], Low: number[], TimePeriod: number): number[]; @@ -3112,12 +2076,6 @@ declare global { * Percentage Price Oscillator (价格振荡百分比) * * PPO(Records[Close],Fast Period = 12,Slow Period = 26,MA Type = 0) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=12} FastPeriod - * @param {number=26} SlowPeriod - * @param {number=0} MAType - * @return {number[]} */ function PPO( Records: botvs.Record[] | number[], @@ -3130,10 +2088,6 @@ declare global { * Rate of change : ((price/prevPrice)-1)*100 (变动率指标) * * ROC(Records[Close],Time Period = 10) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=10} TimePeriod - * @return {number[]} */ function ROC(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3141,10 +2095,6 @@ declare global { * Rate of change Percentage: (price-prevPrice)/prevPrice (价格变化率) * * ROCP(Records[Close],Time Period = 10) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=10} TimePeriod - * @return {number[]} */ function ROCP(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3152,10 +2102,6 @@ declare global { * Rate of change ratio: (price/prevPrice) (价格变化率) * * ROCR(Records[Close],Time Period = 10) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=10} TimePeriod - * @return {number[]} */ function ROCR(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3163,10 +2109,6 @@ declare global { * Rate of change ratio 100 scale: (price/prevPrice)*100 (价格变化率) * * ROCR100(Records[Close],Time Period = 10) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=10} TimePeriod - * @return {number[]} */ function ROCR100(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3174,10 +2116,6 @@ declare global { * Relative Strength Index (相对强弱指标) * * RSI(Records[Close],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function RSI(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3185,23 +2123,12 @@ declare global { * Parabolic SAR (抛物线转向) * * SAR(Records[High,Low],Acceleration Factor = 0.02,AF Maximum = 0.2) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @param {number=0.02} AccelerationFactor - * @param {number=0.2} AFMaximum - * @return {number[]} */ function SAR(Records: botvs.Record[], AccelerationFactor: number, AFMaximum: number): number[]; /** * Parabolic SAR (抛物线转向) * * SAR(Records[High,Low],Acceleration Factor = 0.02,AF Maximum = 0.2) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number=0.02} AccelerationFactor - * @param {number=0.2} AFMaximum - * @return {number[]} */ function SAR(High: number[], Low: number[], AccelerationFactor: number, AFMaximum: number): number[]; @@ -3211,17 +2138,6 @@ declare global { * SAREXT(Records[High,Low],Start Value = 0,Offset on Reverse = 0,AF Init Long = 0.02,AF Long = 0.02,AF Max * Long = * 0.2,AF Init Short = 0.02,AF Short = 0.02,AF Max Short = 0.2) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @param {number=0} StartValue - * @param {number=0} OffsetonReverse - * @param {number=0.02} AFInitLong - * @param {number=0.02} AFLong - * @param {number=0.2} AFMaxLong - * @param {number=0.02} AFInitShort - * @param {number=0.02} AFShort - * @param {number=0.2} AFMaxShort - * @return {number[]} */ function SAREXT( Records: botvs.Record[], @@ -3240,18 +2156,6 @@ declare global { * SAREXT(Records[High,Low],Start Value = 0,Offset on Reverse = 0,AF Init Long = 0.02,AF Long = 0.02,AF Max * Long = * 0.2,AF Init Short = 0.02,AF Short = 0.02,AF Max Short = 0.2) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number=0} StartValue - * @param {number=0} OffsetonReverse - * @param {number=0.02} AFInitLong - * @param {number=0.02} AFLong - * @param {number=0.2} AFMaxLong - * @param {number=0.02} AFInitShort - * @param {number=0.02} AFShort - * @param {number=0.2} AFMaxShort - * @return {number[]} */ function SAREXT( High: number[], @@ -3270,9 +2174,6 @@ declare global { * Vector Trigonometric Sin (正弦值) * * SIN(Records[Close]) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function SIN(Records: botvs.Record[] | number[]): number[]; @@ -3280,9 +2181,6 @@ declare global { * Vector Trigonometric Sinh (双曲正弦函数) * * SINH(Records[Close]) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function SINH(Records: botvs.Record[] | number[]): number[]; @@ -3290,10 +2188,6 @@ declare global { * Simple Moving Average (简单移动平均) * * SMA(Records[Close],Time Period = 30) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function SMA(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3301,9 +2195,6 @@ declare global { * Vector Square Root (平方根) * * SQRT(Records[Close]) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function SQRT(Records: botvs.Record[] | number[]): number[]; @@ -3311,11 +2202,6 @@ declare global { * Standard Deviation (标准偏差) * * STDDEV(Records[Close],Time Period = 5,Deviations = 1) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=5} TimePeriod - * @param {number=1} Deviations - * @return {number[]} */ function STDDEV(Records: botvs.Record[] | number[], TimePeriod: number, Deviations: number): number[]; @@ -3325,14 +2211,6 @@ declare global { * STOCH(Records[High,Low,Close],Fast-K Period = 5,Slow-K Period = 3,Slow-K MA = 0,Slow-D Period = 3,Slow-D MA * = 0) * = [Array(outSlowK),Array(outSlowD)] - * - * @param {botvs.Record[]} Records - * @param {number=5} Fast_KPeriod - * @param {number=3} Slow_KPeriod - * @param {number=0} Slow_KMA - * @param {number=3} Slow_DPeriod - * @param {number=0} Slow_DMA - * @return {[number[], number[]]} */ function STOCH( Records: botvs.Record[], @@ -3348,16 +2226,6 @@ declare global { * STOCH(Records[High,Low,Close],Fast-K Period = 5,Slow-K Period = 3,Slow-K MA = 0,Slow-D Period = 3,Slow-D MA * = 0) * = [Array(outSlowK),Array(outSlowD)] - * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=5} Fast_KPeriod - * @param {number=3} Slow_KPeriod - * @param {number=0} Slow_KMA - * @param {number=3} Slow_DPeriod - * @param {number=0} Slow_DMA - * @return {[number[], number[]]} */ function STOCH( High: number[], @@ -3375,12 +2243,6 @@ declare global { * * STOCHF(Records[High,Low,Close],Fast-K Period = 5,Fast-D Period = 3,Fast-D MA = 0) = * [Array(outFastK),Array(outFastD)] - * - * @param {botvs.Record[]} Records - * @param {number=5} Fast_KPeriod - * @param {number=3} Fast_DPeriod - * @param {number=0} Fast_DMA - * @return {[number[], number[]]} */ function STOCHF( Records: botvs.Record[], @@ -3393,14 +2255,6 @@ declare global { * * STOCHF(Records[High,Low,Close],Fast-K Period = 5,Fast-D Period = 3,Fast-D MA = 0) = * [Array(outFastK),Array(outFastD)] - * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=5} Fast_KPeriod - * @param {number=3} Fast_DPeriod - * @param {number=0} Fast_DMA - * @return {[number[], number[]]} */ function STOCHF( High: number[], @@ -3416,13 +2270,6 @@ declare global { * * STOCHRSI(Records[Close],Time Period = 14,Fast-K Period = 5,Fast-D Period = 3,Fast-D MA = 0) = * [Array(outFastK),Array(outFastD)] - * - * @param {botvs.Record[]|number[]} Records - * @param {number=14} TimePeriod - * @param {number=5} Fast_KPeriod - * @param {number=3} Fast_DPeriod - * @param {number=0} Fast_DMA - * @return {[number[], number[]]} */ function STOCHRSI( Records: botvs.Record[] | number[], @@ -3436,10 +2283,6 @@ declare global { * Summation (求和) * * SUM(Records[Close],Time Period = 30) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function SUM(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3447,11 +2290,6 @@ declare global { * Triple Exponential Moving Average (T3) (三指数移动平均) * * T3(Records[Close],Time Period = 5,Volume Factor = 0.7) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=5} TimePeriod - * @param {number=0.7} VolumeFactor - * @return {number[]} */ function T3(Records: botvs.Record[] | number[], TimePeriod: number, VolumeFactor: number): number[]; @@ -3459,9 +2297,6 @@ declare global { * Vector Trigonometric Tan (正切) * * TAN(Records[Close]) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function TAN(Records: botvs.Record[] | number[]): number[]; @@ -3469,9 +2304,6 @@ declare global { * Vector Trigonometric Tanh (双曲正切函数) * * TANH(Records[Close]) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function TANH(Records: botvs.Record[] | number[]): number[]; @@ -3479,10 +2311,6 @@ declare global { * Triple Exponential Moving Average (三指数移动平均) * * TEMA(Records[Close],Time Period = 30) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function TEMA(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3490,20 +2318,12 @@ declare global { * True Range (真实范围) * * TRANGE(Records[High,Low,Close]) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function TRANGE(Records: botvs.Record[]): number[]; /** * True Range (真实范围) * * TRANGE(Records[High,Low,Close]) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function TRANGE(High: number[], Low: number[], Close: number[]): number[]; @@ -3511,10 +2331,6 @@ declare global { * Triangular Moving Average (三指数移动平均) * * TRIMA(Records[Close],Time Period = 30) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function TRIMA(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3522,10 +2338,6 @@ declare global { * 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA (三重指数平滑平均线) * * TRIX(Records[Close],Time Period = 30) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function TRIX(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3533,10 +2345,6 @@ declare global { * Time Series Forecast (时间序列预测) * * TSF(Records[Close],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function TSF(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3544,20 +2352,12 @@ declare global { * Typical Price (典型价格) * * TYPPRICE(Records[High,Low,Close]) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function TYPPRICE(Records: botvs.Record[]): number[]; /** * Typical Price (典型价格) * * TYPPRICE(Records[High,Low,Close]) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function TYPPRICE(High: number[], Low: number[], Close: number[]): number[]; @@ -3565,12 +2365,6 @@ declare global { * Ultimate Oscillator (极限振子) * * ULTOSC(Records[High,Low,Close],First Period = 7,Second Period = 14,Third Period = 28) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @param {number=7} FirstPeriod - * @param {number=14} SecondPeriod - * @param {number=28} ThirdPeriod - * @return {number[]} */ function ULTOSC( Records: botvs.Record[], @@ -3582,14 +2376,6 @@ declare global { * Ultimate Oscillator (极限振子) * * ULTOSC(Records[High,Low,Close],First Period = 7,Second Period = 14,Third Period = 28) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=7} FirstPeriod - * @param {number=14} SecondPeriod - * @param {number=28} ThirdPeriod - * @return {number[]} */ function ULTOSC( High: number[], @@ -3604,11 +2390,6 @@ declare global { * Variance (变量定义) * * VAR(Records[Close],Time Period = 5,Deviations = 1) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=5} TimePeriod - * @param {number=1} Deviations - * @return {number[]} */ function VAR(Records: botvs.Record[] | number[], TimePeriod: number, Deviations: number): number[]; @@ -3616,20 +2397,12 @@ declare global { * Weighted Close Price (加权收盘价) * * WCLPRICE(Records[High,Low,Close]) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @return {number[]} */ function WCLPRICE(Records: botvs.Record[]): number[]; /** * Weighted Close Price (加权收盘价) * * WCLPRICE(Records[High,Low,Close]) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function WCLPRICE(High: number[], Low: number[], Close: number[]): number[]; @@ -3637,22 +2410,12 @@ declare global { * Williams' %R (威廉指标) * * WILLR(Records[High,Low,Close],Time Period = 14) = Array(outReal) - * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function WILLR(Records: botvs.Record[], TimePeriod: number): number[]; /** * Williams' %R (威廉指标) * * WILLR(Records[High,Low,Close],Time Period = 14) = Array(outReal) - * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=14} TimePeriod - * @return {number[]} */ function WILLR(High: number[], Low: number[], Close: number[], TimePeriod: number): number[]; @@ -3660,10 +2423,6 @@ declare global { * Weighted Moving Average (加权移动平均) * * WMA(Records[Close],Time Period = 30) = Array(outReal) - * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function WMA(Records: botvs.Record[] | number[], TimePeriod: number): number[]; } @@ -3779,8 +2538,6 @@ declare global { * def main(): * plt.plot([3,6,2,4,7,1]) * Log(plt) - * - * @param {string} arg */ function Log(arg: string): void; @@ -3788,8 +2545,6 @@ declare global { * 休眠函数 * * 参数为毫秒数,如Sleep(1000)为休眠一秒 - * - * @param {number} Millisecond */ function Sleep(Millisecond: number): void; @@ -3797,29 +2552,21 @@ declare global { * 判断是否是模拟回测 * * 模拟回测状态返回true,实盘返回false - * - * @return {boolean} */ function IsVirtual(): boolean; /** * 记录盈利值,这个为总盈利的值,参数类型为浮点数 - * - * @param {number} Profit */ function LogProfit(Profit: number): void; /** * 清空所有收益日志, 可以带一个数字参数, 指定保留的条数 - * - * @param {number} reserve */ function LogProfitReset(reserve?: number): void; /** * 清空所有日志, 可以带一个数字参数, 指定保留的条数 - * - * @param {number} reserve */ function LogReset(reserve?: number): void; @@ -3855,15 +2602,11 @@ declare global { * // 可以自定义按钮风格(bootstrap的按钮属性) * LogStatus('`' + JSON.stringify({'type':'button', 'class': 'btn btn-xs btn-danger', 'cmd': 'coverAll', 'name': * '平仓'}) + '`') - * - * @param {string} Msg */ function LogStatus(Msg: string): void; /** * 打开或者关闭定单和出错信息的日志记录 - * - * @param {boolean} IsEnable */ function EnableLog(IsEnable: boolean): void; @@ -3882,9 +2625,6 @@ declare global { * 那么add时指定0与1序列ID代表更新图表1的两个序列的数据, add时指定序列ID为2指图表2的第一个 * series的数据, 指定序列3指的是图表3的第一个series的数据 HighStocks: * http://api.highcharts.com/highstock - * - * @param {botvs.ChartOptions} options - * @return {botvs.RChart} */ function Chart(...options: botvs.ChartOptions[]): botvs.RChart; @@ -3893,14 +2633,6 @@ declare global { * * Mail(smtpServer, smtpUsername, smtpPassword, mailTo, title, body); ret true or false * Mail("smtp.163.com", "asdf@163.com", "password", "111@163.com", "title", "body") - * - * @param {string} smtpServer - * @param {string} smtpUsername - * @param {string} smtpPassword - * @param {string} mailTo - * @param {string} title - * @param {string} body - * @return {boolean} */ function Mail( smtpServer: string, @@ -3917,22 +2649,16 @@ declare global { * 被此正则表达式匹配的错误将不上传到日志系统, 可多次调用设置多个 * SetErrorFilter("502:|503:|tcp|character|unexpected|network|timeout|WSARecv|Connect|GetAddr|no * such|reset|http|received|EOF|reused"); - * - * @param {string} RegEx */ function SetErrorFilter(RegEx: string): void; /** * 返回机器人进程ID - * - * @return {number} */ function GetPid(): number; /** * 获取最近一次出错信息,一般无需使用,因为程序会把出错信息自动上传到日志系统 - * - * @return {string} */ function GetLastError(): string; @@ -3947,9 +2673,6 @@ declare global { * _G("num"); // 返回全局变量num的值 * _G(); // 返回当前机器人的ID * _G(null); // 删除所有全局变量 - * - * @param {string} K - * @param {T} V */ function _G(K: string, V: T): void; @@ -3964,8 +2687,6 @@ declare global { * } * Sleep(1000); * } - * - * @return {string} */ function GetCommand(): string | null; @@ -3988,10 +2709,6 @@ declare global { * client.close(); * } * ``` - * - * @param {string} Address - * @param {number} Timeout - * @return {botvs.Socket} */ function Dial(Address: string, Timeout?: number): botvs.Socket | void; @@ -4008,12 +2725,6 @@ declare global { * HttpQuery("http://www.163.com", "xxx"); // Post * HttpQuery("http://www.baidu.com/", null, "a=10; b=20", "User-Agent: Mobile\nContent-Type: text/html", true); * // will return {Header: HTTP Header, Body: HTML} - * - * @param {string} Url - * @param {string | null | {method: string; data?: string}} PostData - * @param {string} Cookies - * @param {string} Headers - * @return {string} */ function HttpQuery( Url: string, @@ -4035,11 +2746,6 @@ declare global { * 第二个参数可设置为raw/hex/base64, 分别指输出加密后的 原始内容/hex编码过的/base64编码过的 * Log(Hash('md5', 'hex', 'hello')); * Log(Hash('sha512', 'base64', 'hello')); - * - * @param {"md5" | "sha256" | "sha512" | "sha1"} Algo - * @param {"hex" | "base64"} OutputAlgo - * @param {string} Data - * @return {string} */ function Hash( Algo: 'md5' | 'sha256' | 'sha512' | 'sha1', @@ -4053,12 +2759,6 @@ declare global { * 第二个参数可设置为raw/hex/base64, 分别指输出加密后的 原始内容/hex编码过的/base64编码过的 * Log(HMAC('md5', 'hex', 'hello', 'pass')); * Log(HMAC('sha512', 'base64', 'hello', 'pass')); - * - * @param {"md5" | "sha256" | "sha512" | "sha1"} Algo - * @param {"hex" | "base64" | "raw"} OutputAlgo - * @param {string} Data - * @param {string} password - * @return {string} */ function HMAC( Algo: 'md5' | 'sha256' | 'sha512' | 'sha1', @@ -4070,19 +2770,11 @@ declare global { /** * 返回指定时间戳(ms)字符串, 不传任何参数就返回当前时间, * 如_D(),或者_D(1478570053241), 默认格式为yyyy-MM-dd hh:mm:ss - * - * @param {string} timestamp - * @param {string} format - * @return {string} */ function _D(timestamp: string, format: string): string; /** * 格式化一个浮点函数 - * - * @param {number} num - * @param {number=4} precision - * @return {string} */ function _N(num: number, precision?: number): string; @@ -4090,17 +2782,11 @@ declare global { * 重试函数, 会一直调用指定函数到成功返回(函数返回null或者false会重试), * 比如_C(exchange.GetTicker), 默认重试间隔为3秒, 可以调用_CDelay函数来控制重试间隔 * 比如_CDelay(1000), 指改变_C函数重试间隔为1秒 - * - * @param {(...args: any[]) => T} func - * @param args - * @return {T} */ function _C(func: (...args: any[]) => T, ...args: any[]): T; /** * 比如_CDelay(1000), 指改变_C函数重试间隔为1秒, 默认为3秒 - * - * @param {number} delay */ function _CDelay(delay: number): void; } From 3ac9d950a0c5af9ce95c85d2318c7f8b7ec5852c Mon Sep 17 00:00:00 2001 From: Josh Goldberg Date: Tue, 31 Oct 2017 15:22:01 -0700 Subject: [PATCH 065/495] Made name optional in jasmine::createSpy See https://github.com/jasmine/jasmine/issues/1438 --- types/jasmine/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/jasmine/index.d.ts b/types/jasmine/index.d.ts index 900c235990..7d5fc71cdb 100644 --- a/types/jasmine/index.d.ts +++ b/types/jasmine/index.d.ts @@ -137,7 +137,7 @@ declare namespace jasmine { function arrayContaining(sample: any[]): 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; From 2357543d014de299f7e7ead05c87f33aa4267046 Mon Sep 17 00:00:00 2001 From: Cory Deppen Date: Tue, 17 Oct 2017 17:46:41 -0500 Subject: [PATCH 066/495] Allow arbitrary keys to be included in RoutesMap * Resolve no-unnecessary-generics errors * Related to conversation in faceyspacey/redux-first-router/#15 --- types/redux-first-router/index.d.ts | 84 ++++++++++++------- .../redux-first-router-tests.ts | 43 ++++++---- 2 files changed, 80 insertions(+), 47 deletions(-) diff --git a/types/redux-first-router/index.d.ts b/types/redux-first-router/index.d.ts index 410cbc74cc..5209d7ded0 100644 --- a/types/redux-first-router/index.d.ts +++ b/types/redux-first-router/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Valbrand // viggyfresh // janb87 +// corydeppen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -21,21 +22,24 @@ export type StateGetter = () => object; export type RouteString = string; -export type RouteThunk = (dispatch: Dispatch, getState: StateGetter) => any | Promise; +export type RouteThunk = ( + dispatch: Dispatch, + getState: StateGetter +) => any | Promise; -export interface RouteObject { - path: string; +export type RouteObject = TKeys & { capitalizedWords?: boolean; - toPath?(param: string, key?: string): string; - fromPath?(path: string, key?: string): string; - thunk?: RouteThunk; navKey?: string; -} + path: string; + thunk?: RouteThunk; + fromPath?(path: string, key?: string): string; + toPath?(param: string, key?: string): string; +}; -export type Route = RouteString | RouteObject; +export type Route = RouteString | RouteObject; -export interface RoutesMap { - [key: string]: Route; +export interface RoutesMap { + [key: string]: Route; } export interface ReceivedAction { @@ -127,14 +131,25 @@ export interface HistoryLocation { export type HistoryAction = string; -export type Listener = (location: HistoryLocation, action: HistoryAction) => void; +export type Listener = ( + location: HistoryLocation, + action: HistoryAction +) => void; export type ScrollBehavior = object; export interface Router { - getStateForActionOriginal(action: object, state: Nullable): Nullable; - getStateForAction(action: object, state: Nullable): Nullable; - getPathAndParamsForState(state: object): { path: Nullable, params: Nullable }; + getStateForActionOriginal( + action: object, + state: Nullable + ): Nullable; + getStateForAction( + action: object, + state: Nullable + ): Nullable; + getPathAndParamsForState( + state: object + ): { path: Nullable; params: Nullable }; getActionForPathAndParams(path: string): Nullable; } @@ -164,14 +179,14 @@ export interface NavigatorsConfig { navigationAction: Nullable, route: Nullable ): object; - navigationToAction( + navigationToAction( navigators: Navigators, - store: Store, + store: Store, routesMap: RoutesMap, action: object ): { - action: object, - navigationAction: Nullable + action: object; + navigationAction: Nullable; }; } @@ -180,9 +195,9 @@ export interface Options { location?: string | SelectLocationState; notFoundPath?: string; scrollTop?: boolean; - onBeforeChange?(dispatch: Dispatch, getState: StateGetter): void; - onAfterChange?(dispatch: Dispatch, getState: StateGetter): void; - onBackNext?(dispatch: Dispatch, getState: StateGetter): void; + onBeforeChange?(dispatch: Dispatch, getState: StateGetter): void; + onAfterChange?(dispatch: Dispatch, getState: StateGetter): void; + onBackNext?(dispatch: Dispatch, getState: StateGetter): void; restoreScroll?(history: History): ScrollBehavior; initialDispatch?: boolean; querySerializer?: QuerySerializer; @@ -196,7 +211,11 @@ export type ScrollUpdater = (performedByUser: boolean) => void; export const NOT_FOUND: '@@redux-first-router/NOT_FOUND'; -export function actionToPath(action: ReceivedAction, routesMap: RoutesMap, querySerializer?: QuerySerializer): string; +export function actionToPath( + action: ReceivedAction, + routesMap: RoutesMap, + querySerializer?: QuerySerializer +): string; export function back(): void; @@ -206,12 +225,16 @@ export function canGoBack(): boolean; export function canGoForward(): boolean; -export function connectRoutes(history: History, routesMap: RoutesMap, options?: Options): { - reducer: Reducer, - middleware: Middleware, - thunk(store: Store): Promise>, - enhancer: GenericStoreEnhancer, - initialDispatch?(): void +export function connectRoutes( + history: History, + routesMap: RoutesMap, + options?: Options +): { + reducer: Reducer; + middleware: Middleware; + thunk(store: Store): Promise>; + enhancer: GenericStoreEnhancer; + initialDispatch?(): void; }; export function go(n: number): void; @@ -224,7 +247,10 @@ export function next(): void; export function nextPath(): string | void; -export function pathToAction(pathname: string, routesMap: RoutesMap): ReceivedAction; +export function pathToAction( + pathname: string, + routesMap: RoutesMap +): ReceivedAction; export function prevPath(): string | void; diff --git a/types/redux-first-router/redux-first-router-tests.ts b/types/redux-first-router/redux-first-router-tests.ts index 39b00c7a94..3c9e69a82e 100644 --- a/types/redux-first-router/redux-first-router-tests.ts +++ b/types/redux-first-router/redux-first-router-tests.ts @@ -9,16 +9,16 @@ import { QuerySerializer } from 'redux-first-router'; import { - createStore, - applyMiddleware, - Middleware, - MiddlewareAPI, - Store, - Dispatch, - compose, - Action, - GenericStoreEnhancer, - StoreEnhancerStoreCreator + createStore, + applyMiddleware, + Middleware, + MiddlewareAPI, + Store, + Dispatch, + compose, + Action, + GenericStoreEnhancer, + StoreEnhancerStoreCreator } from 'redux'; import { History } from 'history'; @@ -28,24 +28,31 @@ declare var history: History; type State = LocationState; type StoreCreator = StoreEnhancerStoreCreator; -const routesMap = { - HOME: '/' +const routesMap: RoutesMap<{ role: string }> = { + HOME: '/', + ADMIN: { + path: '/admin', + role: 'admin' + } }; const { - reducer, - middleware, - enhancer, - initialDispatch + reducer, + middleware, + enhancer, + initialDispatch } = connectRoutes(history, routesMap, { - initialDispatch: false + initialDispatch: false }); const dumbMiddleware: Middleware = store => next => action => next(action); const composedMiddleware = applyMiddleware(middleware, dumbMiddleware); -const storeEnhancer = compose(enhancer, composedMiddleware); +const storeEnhancer = compose( + enhancer, + composedMiddleware +); const store = createStore(reducer, storeEnhancer); From 610c4850a3ecba04bfedd2c17c2518d735317070 Mon Sep 17 00:00:00 2001 From: Keenan Jaenicke Date: Wed, 1 Nov 2017 10:05:26 -0400 Subject: [PATCH 067/495] changes deprecated static prop to new plaintext prop --- types/reactstrap/lib/Input.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/reactstrap/lib/Input.d.ts b/types/reactstrap/lib/Input.d.ts index eb82296e39..d0552648da 100644 --- a/types/reactstrap/lib/Input.d.ts +++ b/types/reactstrap/lib/Input.d.ts @@ -40,7 +40,7 @@ interface InputProps extends Intermediate { valid?: boolean; tag?: React.ReactType; innerRef?: string | ((instance: HTMLInputElement) => any); - static?: boolean; + plaintext?: boolean; addon?: boolean; className?: string; cssModule?: CSSModule; From ad79219ebad15eb9d8aba1c8e3509f3c5e3b3d8a Mon Sep 17 00:00:00 2001 From: Keenan Jaenicke Date: Wed, 1 Nov 2017 10:07:34 -0400 Subject: [PATCH 068/495] remove comments since static is no longer used --- types/reactstrap/lib/Input.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/types/reactstrap/lib/Input.d.ts b/types/reactstrap/lib/Input.d.ts index d0552648da..80aea96c20 100644 --- a/types/reactstrap/lib/Input.d.ts +++ b/types/reactstrap/lib/Input.d.ts @@ -44,8 +44,6 @@ interface InputProps extends Intermediate { addon?: boolean; className?: string; cssModule?: CSSModule; - // We don't have the property 'static' here because 'static' is a reserved keyword in TypeScript - // Maybe reactstrap will support an 'isStatic' alias in the future } declare var Input: React.StatelessComponent; From c0f617b6025fc60df2ff571bd635c4d6cc0dad28 Mon Sep 17 00:00:00 2001 From: Mark Perkins Date: Wed, 1 Nov 2017 10:48:51 -0600 Subject: [PATCH 069/495] added optional id to ColumnProps --- types/react-virtualized/dist/es/Table.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/types/react-virtualized/dist/es/Table.d.ts b/types/react-virtualized/dist/es/Table.d.ts index c1216f12b1..9b9e7d3d95 100644 --- a/types/react-virtualized/dist/es/Table.d.ts +++ b/types/react-virtualized/dist/es/Table.d.ts @@ -96,6 +96,8 @@ export type ColumnProps = { style?: React.CSSProperties; /** Flex basis (width) for this column; This value can grow or shrink based on :flexGrow and :flexShrink properties. */ width: number; + /** Optional id for column header */ + id?: string; } export class Column extends Component { static propTypes: { @@ -114,7 +116,8 @@ export class Column extends Component { maxWidth: Requireable, minWidth: Requireable, style: Requireable, - width: Validator + width: Validator, + id: Requireable }; static defaultProps: { From b7172b90c4eb0bb3d3064c679b7d8afaed2e4147 Mon Sep 17 00:00:00 2001 From: Mark Perkins Date: Wed, 1 Nov 2017 10:59:39 -0600 Subject: [PATCH 070/495] updated comment according to react-virtualized documentation --- types/react-virtualized/dist/es/Table.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-virtualized/dist/es/Table.d.ts b/types/react-virtualized/dist/es/Table.d.ts index 9b9e7d3d95..e8cafc5dc9 100644 --- a/types/react-virtualized/dist/es/Table.d.ts +++ b/types/react-virtualized/dist/es/Table.d.ts @@ -96,7 +96,7 @@ export type ColumnProps = { style?: React.CSSProperties; /** Flex basis (width) for this column; This value can grow or shrink based on :flexGrow and :flexShrink properties. */ width: number; - /** Optional id for column header */ + /** Optional id to set on the column header; used for aria-describedby */ id?: string; } export class Column extends Component { From e2f170b88b3ddd2d745238d76e08d9682bae0dcd Mon Sep 17 00:00:00 2001 From: RetroCraft Date: Wed, 1 Nov 2017 19:41:08 -0400 Subject: [PATCH 071/495] Remove error-stack-parser (closes #21153) --- notNeededPackages.json | 6 ++ .../error-stack-parser-tests.ts | 3 - types/error-stack-parser/index.d.ts | 26 ------ types/error-stack-parser/tsconfig.json | 23 ------ types/error-stack-parser/tslint.json | 79 ------------------- 5 files changed, 6 insertions(+), 131 deletions(-) delete mode 100644 types/error-stack-parser/error-stack-parser-tests.ts delete mode 100644 types/error-stack-parser/index.d.ts delete mode 100644 types/error-stack-parser/tsconfig.json delete mode 100644 types/error-stack-parser/tslint.json diff --git a/notNeededPackages.json b/notNeededPackages.json index 498e2e1c4a..1c930643e1 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/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/tsconfig.json b/types/error-stack-parser/tsconfig.json deleted file mode 100644 index 98f3beb1a5..0000000000 --- a/types/error-stack-parser/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "error-stack-parser-tests.ts" - ] -} \ No newline at end of file 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 - } -} From 194023b78330537cbba06b11f5c37e323a913e52 Mon Sep 17 00:00:00 2001 From: Leo Liang Date: Fri, 3 Nov 2017 15:18:21 +0800 Subject: [PATCH 072/495] cassandra-driver: give sslOptions a type --- .../cassandra-driver-tests.ts | 11 ++- types/cassandra-driver/index.d.ts | 71 ++++++++++--------- 2 files changed, 45 insertions(+), 37 deletions(-) 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..cae0eeaded 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, @@ -169,8 +170,8 @@ export namespace types { text, timestamp, uuid, - varchar, - varint, + letchar, + letint, timeuuid, inet, date, @@ -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"; From 7adfaa04907c33fb37e7bb6943dd46a4b8f05122 Mon Sep 17 00:00:00 2001 From: benishouga Date: Fri, 3 Nov 2017 16:38:15 +0900 Subject: [PATCH 073/495] [react-mdl] Fixed title type of HeaderRowProps. --- types/react-mdl/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-mdl/index.d.ts b/types/react-mdl/index.d.ts index 33dccccd07..8e70852190 100644 --- a/types/react-mdl/index.d.ts +++ b/types/react-mdl/index.d.ts @@ -418,7 +418,7 @@ declare namespace __ReactMDL { hideSpacer?: boolean; } interface HeaderRowProps extends __MDLOtherProps { - title?: string; + title?: any; // string | JSX.Element hideSpacer?: boolean; } interface HeaderTabsProps extends __MDLOtherProps, RippleComponent { From 79325cc16763dc38fddc26bef4b23dc94c86a717 Mon Sep 17 00:00:00 2001 From: Yu Date: Fri, 3 Nov 2017 16:58:44 +0800 Subject: [PATCH 074/495] [react-native]fix raw event arg ignored error --- types/react-native/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 58af56a5ac..63848bcd8c 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -7981,7 +7981,7 @@ export namespace Animated { config?: ParallelConfig ): CompositeAnimation; - type Mapping = { [key: string]: Mapping } | AnimatedValue; + type Mapping = { [key: string]: Mapping } | AnimatedValue | null; interface EventConfig { listener?: ValueListenerCallback; useNativeDriver?: boolean; From 06fd47385443744c4752d5a51c16665883ddb387 Mon Sep 17 00:00:00 2001 From: Jack Wilsdon Date: Sat, 4 Nov 2017 23:18:26 +0000 Subject: [PATCH 075/495] Add missing strict option to IRouterOptions --- types/koa-router/index.d.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/types/koa-router/index.d.ts b/types/koa-router/index.d.ts index 972c02014c..7c0cffe113 100644 --- a/types/koa-router/index.d.ts +++ b/types/koa-router/index.d.ts @@ -33,15 +33,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 { From e0da5d33e6a545b00c62d89a774d869df9fecbc8 Mon Sep 17 00:00:00 2001 From: Jeremy Morton Date: Sun, 5 Nov 2017 15:16:12 +0000 Subject: [PATCH 076/495] Add various effective UID and groups operations --- types/node/index.d.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 5b0e8b4b19..6dddebcc12 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -477,6 +477,14 @@ declare namespace NodeJS { getuid(): number; setuid(id: number): void; setuid(id: string): void; + geteuid(): number; + seteuid(id: number): void; + seteuid(id: string): void; + getegid(): number; + setegid(id: number): void; + setegid(id: string): void; + getgroups(): number[]; + setgroups(groups: (string | number)[]): void; version: string; versions: ProcessVersions; config: { From ffbf3b101a25527c9ff9954f2a58a77a68264e49 Mon Sep 17 00:00:00 2001 From: Jeremy Morton Date: Sun, 5 Nov 2017 17:07:25 +0000 Subject: [PATCH 077/495] Fix array type notation --- types/node/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 6dddebcc12..929c6264ee 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -13,7 +13,7 @@ // Deividas Bakanas // Kelvin Jin // Alvis HT Tang -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped) // TypeScript Version: 2.2 /************************************************ @@ -484,7 +484,7 @@ declare namespace NodeJS { setegid(id: number): void; setegid(id: string): void; getgroups(): number[]; - setgroups(groups: (string | number)[]): void; + setgroups(groups: Array): void; version: string; versions: ProcessVersions; config: { From 28f78b8c2aaa9d7da031d79b82f8050f24d052f3 Mon Sep 17 00:00:00 2001 From: Jeremy Morton Date: Sun, 5 Nov 2017 18:00:00 +0000 Subject: [PATCH 078/495] Use unions instead of overloads --- types/node/index.d.ts | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 929c6264ee..ef4ac81bac 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -13,7 +13,7 @@ // Deividas Bakanas // Kelvin Jin // Alvis HT Tang -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped) +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 /************************************************ @@ -472,17 +472,13 @@ 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): void; - seteuid(id: string): void; + seteuid(id: number | string): void; getegid(): number; - setegid(id: number): void; - setegid(id: string): void; + setegid(id: number | string): void; getgroups(): number[]; setgroups(groups: Array): void; version: string; From 1cdffab913be878743025a3b0ba46e747dd640cc Mon Sep 17 00:00:00 2001 From: Steven Masala Date: Mon, 6 Nov 2017 12:03:33 +0100 Subject: [PATCH 079/495] added container property --- types/daterangepicker/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/daterangepicker/index.d.ts b/types/daterangepicker/index.d.ts index f31f9fee6e..22fc118cf7 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; From 29ccdc57c90d2920aa47bcc1aa4fec35ced6a9cd Mon Sep 17 00:00:00 2001 From: Jason Johnston Date: Mon, 6 Nov 2017 09:42:52 -0500 Subject: [PATCH 080/495] Updated doc for closeContainer --- types/office-js/index.d.ts | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) 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; } From c68ec62d1a173bdd448505cb2964f7fd90284efd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20Dal=C3=A9n?= Date: Mon, 6 Nov 2017 17:11:04 +0100 Subject: [PATCH 081/495] react-bootstrap: Add bsClass to Glyphicon See https://react-bootstrap.github.io/components.html#glyphicons-props --- types/react-bootstrap/lib/Glyphicon.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/react-bootstrap/lib/Glyphicon.d.ts b/types/react-bootstrap/lib/Glyphicon.d.ts index 036af24cb3..17cf8e9fc7 100644 --- a/types/react-bootstrap/lib/Glyphicon.d.ts +++ b/types/react-bootstrap/lib/Glyphicon.d.ts @@ -4,6 +4,8 @@ declare namespace Glyphicon { export interface GlyphiconProps extends React.HTMLProps { // Required glyph: string; + // Optional + bsClass?: string; } } declare class Glyphicon extends React.Component { } From 811ab539557556ba0ef0f346a3b31e1dddc02b74 Mon Sep 17 00:00:00 2001 From: Gregor Yushinov Date: Mon, 6 Nov 2017 17:28:28 +0100 Subject: [PATCH 082/495] Bull 3.3.5 update --- types/bull/index.d.ts | 981 +++++++++++++++++++++++++----------------- 1 file changed, 582 insertions(+), 399 deletions(-) diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index abfd4ddd98..75c7341723 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for bull 3.0 +// Type definitions for bull 3.3.5 // Project: https://github.com/OptimalBits/bull // Definitions by: Bruno Grieder // Cameron Crothers @@ -6,6 +6,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as Redis from "ioredis"; +import * as Promise from "bluebird"; /** * This is the Queue constructor. @@ -13,407 +14,589 @@ 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: object): 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. + * + * 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. + * + * 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. + * + * name: Bull will only call the handler if the job name matches + */ + 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. + * + * name: Bull will only call the handler if the job name matches + */ + 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. + * + * name: Bull will only call the handler if the job name matches + * 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. + * + * name: Bull will only call the handler if the job name matches + * 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 {number} grace Grace period in milliseconds. + * @param {JobStatus} status Status of the job to clean. Values are completed, wait, active, delayed, and failed. Defaults to completed. + * @param {number} 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; From 1c4f1ef167d50e0632d5fa3381fe64dcb3353545 Mon Sep 17 00:00:00 2001 From: Gregor Yushinov Date: Mon, 6 Nov 2017 17:51:28 +0100 Subject: [PATCH 083/495] Don't include patch version in header --- types/bull/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index 75c7341723..b7a2142fa0 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for bull 3.3.5 +// Type definitions for bull 3.3 // Project: https://github.com/OptimalBits/bull // Definitions by: Bruno Grieder // Cameron Crothers @@ -233,7 +233,7 @@ declare namespace Bull { failed: number; delayed: number; } - + interface JobInformation { key: string; name: string; From ef92e136d150bb5e8fd2ae16d1647a3870f0ec84 Mon Sep 17 00:00:00 2001 From: Gregor Yushinov Date: Mon, 6 Nov 2017 19:21:20 +0100 Subject: [PATCH 084/495] Most tslint issues fixed --- types/bull/index.d.ts | 37 +++++++++++++++++++------------------ 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index b7a2142fa0..3208637a32 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Bruno Grieder // Cameron Crothers // Marshall Cottrell +// Weeco // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as Redis from "ioredis"; @@ -107,7 +108,7 @@ declare namespace Bull { /** * Update a specific job's data. Promise resolves when the job has been updated. */ - update(data: object): Promise; + update(data: any): Promise; /** * Removes a job from the queue and from any lists it may be included in. @@ -286,7 +287,7 @@ declare namespace Bull { * 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. + * @param concurrency Bull will then call you handler in parallel respecting this max number. */ process(concurrency: number, callback: (job: Job) => void): Promise; @@ -301,7 +302,7 @@ declare namespace Bull { * 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. + * @param concurrency Bull will then call you handler in parallel respecting this max number. */ process(concurrency: number, callback: (job: Job, done: DoneCallback) => void): void; @@ -315,7 +316,7 @@ declare namespace Bull { * 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. * - * name: Bull will only call the handler if the job name matches + * @param name Bull will only call the handler if the job name matches */ process(name: string, callback: (job: Job) => void): Promise; @@ -330,7 +331,7 @@ declare namespace Bull { * Errors will be passed as a second argument to the "failed" event; * results, as a second argument to the "completed" event. * - * name: Bull will only call the handler if the job name matches + * @param name Bull will only call the handler if the job name matches */ process(name: string, callback: (job: Job, done: DoneCallback) => void): void; @@ -344,8 +345,8 @@ declare namespace Bull { * 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. * - * name: Bull will only call the handler if the job name matches - * concurrency: Bull will then call you handler in parallel respecting this max number. + * @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; @@ -360,8 +361,8 @@ declare namespace Bull { * Errors will be passed as a second argument to the "failed" event; * results, as a second argument to the "completed" event. * - * name: Bull will only call the handler if the job name matches - * concurrency: Bull will then call you handler in parallel respecting this max number. + * @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; @@ -425,33 +426,33 @@ declare namespace Bull { /** * Returns a promise that will return an array with the active jobs between start and end. */ - getActive(start?: number, end?: number) : Promise> + 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> + 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> + 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> + 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> + getRepeatableJobs(start?: number, end?: number, asc?: boolean): Promise; /** * ??? */ - nextRepeatableJob(name: string, data: any, opts: JobOptions): 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 @@ -510,9 +511,9 @@ declare namespace Bull { /** * 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 {number} grace Grace period in milliseconds. - * @param {JobStatus} status Status of the job to clean. Values are completed, wait, active, delayed, and failed. Defaults to completed. - * @param {number} limit Maximum amount of jobs to clean per call. If not provided will clean all matching jobs. + * @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; From 4439847c0675470e184334fccfb7a0abb010fc0a Mon Sep 17 00:00:00 2001 From: Joseph Roque Date: Mon, 6 Nov 2017 15:26:37 -0500 Subject: [PATCH 085/495] [react-native-fs] add missing function and const declarations --- types/react-native-fs/index.d.ts | 63 +++++++++++++++++++++++++++++--- 1 file changed, 57 insertions(+), 6 deletions(-) diff --git a/types/react-native-fs/index.d.ts b/types/react-native-fs/index.d.ts index b9ad43eec3..71e6525514 100644 --- a/types/react-native-fs/index.d.ts +++ b/types/react-native-fs/index.d.ts @@ -7,6 +7,10 @@ /// export interface ReadDirItem { + // The creation date of the file (iOS only) + ctime: Date | undefined; + // The last modified date of the file + mtime: Date; // The name of the item name: string; // The absolute path to the item @@ -28,6 +32,10 @@ export interface StatResult { size: string; // UNIX file mode mode: number; + // Created date + ctime: number; + // Updated date + utime: number; // Is the file just a file? isFile(): boolean; // Is the file a directory? @@ -63,8 +71,11 @@ export interface DownloadFileOptions { toFile: string; // An object of headers to be passed to the server headers?: Headers; + // iOS only background?: boolean; progressDivider?: number; + readTimeout?: number; + connectionTimeout?: number; begin?: DownloadCallbackBegin; progress?: DownloadCallbackProgress; } @@ -155,6 +166,29 @@ export interface JobReturnValue { promise: Promise; } +// Can be one of utf8 (default), ascii, base64. Use base64 for reading binary files +export type Encoding = + | 'utf8' + | 'ascii' + | 'base64' + ; + +// Optional object wrapper for encoding options +export type EncodingOrOptions = + | Encoding + | { encoding?: Encoding } + ; + +// Available hashing algorithms +export type HashAlgorithm = + | "md5" + | "sha1" + | "sha224" + | "sha256" + | "sha384" + | "sha512" + ; + // The absolute path to the main bundle directory export const MainBundlePath: string; // The absolute path to the caches directory @@ -167,21 +201,38 @@ export const TemporaryDirectoryPath: string; export const ExternalDirectoryPath: string; // The absolute path to the external storage, shared directory (android only) export const ExternalStorageDirectoryPath: string; +// The absolute path to the NSLibraryDirectory (iOS only) +export const LibraryDirectoryPath: string; +// The absolute path to the pictures directory (android only) +export const PicturesDirectoryPath: string; export function readDir(path: string): Promise; +export function readDirAssets(dirpath: string): Promise; export function readdir(path: string): Promise; export function stat(filepath: string): Promise; -export function readFile(filepath: string, encoding?: string): Promise; +export function read(filepath: string, length?: number, position?: number, encodingOrOptions?: EncodingOrOptions): Promise; +export function readFile(filepath: string, encodingOrOptions?: EncodingOrOptions): Promise; +export function readFileAssets(filepath: string, encodingOrOptions?: EncodingOrOptions): Promise; +export function existsAssets(filepath: string): Promise; export function unlink(filepath: string): Promise; -export function writeFile(filepath: string, contents: string, encoding?: string): Promise; -export function appendFile(filepath: string, contents: string, encoding?: string): Promise; +export function write(filepath: string, contents: string, position?: number, encodingOrOptions?: EncodingOrOptions): Promise; +export function writeFile(filepath: string, contents: string, encodingOrOptions?: EncodingOrOptions): Promise; +export function appendFile(filepath: string, contents: string, encodingOrOptions?: EncodingOrOptions): Promise; export function moveFile(filepath: string, destPath: string): Promise; export function copyFile(filepath: string, destPath: string): Promise; +export function copyFileAssets(filepath: string, destPath: string): Promise; +export function copyAssetsFileIOS(imageUri: string, destPath: string, width: number, height: number, + scale?: number, compression?: number, resizeMode?: string): Promise; +export function copyAssetsVideoIOS(imageUri: string, destPath: string): Promise; export function exists(filepath: string): Promise; -export function hash(filepath: string, algorithm: string): Promise; +export function hash(filepath: string, algorithm: HashAlgorithm): Promise; export function mkdir(filepath: string, options?: MkdirOptions): Promise; +export function touch(filepath: string, mtime?: Date, ctime?: Date): Promise; export function downloadFile(options: DownloadFileOptions): JobReturnValue; -export function stopDownload(jobId: number): Promise; +export function stopDownload(jobId: number): void; export function uploadFiles(options: UploadFileOptions): JobReturnValue; -export function stopUpload(jobId: number): Promise; +export function stopUpload(jobId: number): void; +export function pathForBundle(bundleNamed: string): Promise; +export function pathForGroup(groupName: string): Promise; +export function setReadable(filepath: string, readable: boolean, ownerOnly: boolean): Promise; export function getFSInfo(): Promise; From 20a611973cf3a3544cb0460171cf7d24711cd1e6 Mon Sep 17 00:00:00 2001 From: Joseph Roque Date: Mon, 6 Nov 2017 16:41:21 -0500 Subject: [PATCH 086/495] [react-native-fs] update header with new version, new contributor --- types/react-native-fs/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/react-native-fs/index.d.ts b/types/react-native-fs/index.d.ts index 71e6525514..8c7945010d 100644 --- a/types/react-native-fs/index.d.ts +++ b/types/react-native-fs/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for react-native-fs 2.0 +// Type definitions for react-native-fs 2.8 // Project: https://github.com/johanneslumpe/react-native-fs // Definitions by: Paulo Cesar +// Joseph Roque // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 From 05735d2abf0974dc01d3d33f69e92de993b279e5 Mon Sep 17 00:00:00 2001 From: segayuu Date: Tue, 7 Nov 2017 12:14:42 +0900 Subject: [PATCH 087/495] Activate unnecessarily ignored rules --- types/bluebird-retry/tslint.json | 59 -------------------------------- 1 file changed, 59 deletions(-) diff --git a/types/bluebird-retry/tslint.json b/types/bluebird-retry/tslint.json index a41bf5d19a..6994644fac 100644 --- a/types/bluebird-retry/tslint.json +++ b/types/bluebird-retry/tslint.json @@ -1,79 +1,20 @@ { "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 } } From f8d93098e233c6a54a33dfba4caed5611323a384 Mon Sep 17 00:00:00 2001 From: segayuu Date: Tue, 7 Nov 2017 12:21:14 +0900 Subject: [PATCH 088/495] cleanup ignore format lint errors: comment-format, eofline, no-consecutive-blank-lines, no-padding, semicolon, space-within-parens, typedef-whitespace, whitespace --- types/bluebird-retry/bluebird-retry-tests.ts | 13 ++++++------- types/bluebird-retry/index.d.ts | 1 - types/bluebird-retry/tslint.json | 10 +--------- 3 files changed, 7 insertions(+), 17 deletions(-) diff --git a/types/bluebird-retry/bluebird-retry-tests.ts b/types/bluebird-retry/bluebird-retry-tests.ts index eb3260a007..ce094918f9 100644 --- a/types/bluebird-retry/bluebird-retry-tests.ts +++ b/types/bluebird-retry/bluebird-retry-tests.ts @@ -1,9 +1,9 @@ import Promise = require('bluebird'); import retry = require('bluebird-retry'); -function promiseSuccess(text:string) { +function promiseSuccess(text: string) { return Promise.resolve(text); -}; +} var count = 0; function myfunc() { @@ -16,18 +16,17 @@ function myfunc() { } retry(myfunc) - .done(function(result) { console.log(result); } ); + .done(function(result) { console.log(result); }); - -//Options example +// Options example function logFail() { console.log(new Date().toISOString()); throw new Error('bail'); } -var options:retry.Options = { +var 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..c6f66a11ee 100644 --- a/types/bluebird-retry/index.d.ts +++ b/types/bluebird-retry/index.d.ts @@ -22,7 +22,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 6994644fac..9a40f717d9 100644 --- a/types/bluebird-retry/tslint.json +++ b/types/bluebird-retry/tslint.json @@ -1,20 +1,12 @@ { "extends": "dtslint/dt.json", "rules": { - "comment-format": false, "dt-header": false, - "eofline": false, - "no-consecutive-blank-lines": false, - "no-padding": false, "no-reference-import": false, "no-var-keyword": false, "only-arrow-functions": false, "prefer-const": false, "prefer-template": false, - "semicolon": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "typedef-whitespace": false, - "whitespace": false + "strict-export-declare-modifiers": false } } From 47dd70182ed6713add942549f4a5ba119b487215 Mon Sep 17 00:00:00 2001 From: segayuu Date: Tue, 7 Nov 2017 12:28:03 +0900 Subject: [PATCH 089/495] cleanup ignore lint error: dt-header --- types/bluebird-retry/index.d.ts | 2 +- types/bluebird-retry/tslint.json | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/types/bluebird-retry/index.d.ts b/types/bluebird-retry/index.d.ts index c6f66a11ee..33239e28cc 100644 --- a/types/bluebird-retry/index.d.ts +++ b/types/bluebird-retry/index.d.ts @@ -1,4 +1,4 @@ -// 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 diff --git a/types/bluebird-retry/tslint.json b/types/bluebird-retry/tslint.json index 9a40f717d9..bd08097d46 100644 --- a/types/bluebird-retry/tslint.json +++ b/types/bluebird-retry/tslint.json @@ -1,7 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "dt-header": false, "no-reference-import": false, "no-var-keyword": false, "only-arrow-functions": false, From 92c323aadda5cecbcba096022faec1a1ef13c3a6 Mon Sep 17 00:00:00 2001 From: segayuu Date: Tue, 7 Nov 2017 12:29:53 +0900 Subject: [PATCH 090/495] cleanup ignore lint errors: no-var-keyword, prefer-const --- types/bluebird-retry/bluebird-retry-tests.ts | 4 ++-- types/bluebird-retry/tslint.json | 2 -- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/types/bluebird-retry/bluebird-retry-tests.ts b/types/bluebird-retry/bluebird-retry-tests.ts index ce094918f9..69712384bd 100644 --- a/types/bluebird-retry/bluebird-retry-tests.ts +++ b/types/bluebird-retry/bluebird-retry-tests.ts @@ -5,7 +5,7 @@ function promiseSuccess(text: string) { return Promise.resolve(text); } -var count = 0; +let count = 0; function myfunc() { console.log('myfunc called ' + (++count) + ' times'); if (count < 3) { @@ -24,7 +24,7 @@ function logFail() { throw new Error('bail'); } -var options: retry.Options = { +const options: retry.Options = { max_tries: 4, interval: 500 }; diff --git a/types/bluebird-retry/tslint.json b/types/bluebird-retry/tslint.json index bd08097d46..4d6d0732aa 100644 --- a/types/bluebird-retry/tslint.json +++ b/types/bluebird-retry/tslint.json @@ -2,9 +2,7 @@ "extends": "dtslint/dt.json", "rules": { "no-reference-import": false, - "no-var-keyword": false, "only-arrow-functions": false, - "prefer-const": false, "prefer-template": false, "strict-export-declare-modifiers": false } From 5bd797fde042b525ccc625cba6570793b307df06 Mon Sep 17 00:00:00 2001 From: segayuu Date: Tue, 7 Nov 2017 12:31:23 +0900 Subject: [PATCH 091/495] cleanup ignore lint error: only-arrow-functions --- types/bluebird-retry/bluebird-retry-tests.ts | 2 +- types/bluebird-retry/tslint.json | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/types/bluebird-retry/bluebird-retry-tests.ts b/types/bluebird-retry/bluebird-retry-tests.ts index 69712384bd..597f946335 100644 --- a/types/bluebird-retry/bluebird-retry-tests.ts +++ b/types/bluebird-retry/bluebird-retry-tests.ts @@ -16,7 +16,7 @@ function myfunc() { } retry(myfunc) - .done(function(result) { console.log(result); }); + .done(result => { console.log(result); }); // Options example function logFail() { diff --git a/types/bluebird-retry/tslint.json b/types/bluebird-retry/tslint.json index 4d6d0732aa..0388bdbbed 100644 --- a/types/bluebird-retry/tslint.json +++ b/types/bluebird-retry/tslint.json @@ -2,7 +2,6 @@ "extends": "dtslint/dt.json", "rules": { "no-reference-import": false, - "only-arrow-functions": false, "prefer-template": false, "strict-export-declare-modifiers": false } From 4aa84e56674c98f034297ca17543e5970b7599a8 Mon Sep 17 00:00:00 2001 From: segayuu Date: Tue, 7 Nov 2017 12:32:31 +0900 Subject: [PATCH 092/495] cleanup ignore lint error: no-reference-import --- types/bluebird-retry/index.d.ts | 2 -- types/bluebird-retry/tslint.json | 1 - 2 files changed, 3 deletions(-) diff --git a/types/bluebird-retry/index.d.ts b/types/bluebird-retry/index.d.ts index 33239e28cc..0e39ef3b89 100644 --- a/types/bluebird-retry/index.d.ts +++ b/types/bluebird-retry/index.d.ts @@ -4,8 +4,6 @@ // 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; diff --git a/types/bluebird-retry/tslint.json b/types/bluebird-retry/tslint.json index 0388bdbbed..84c5ab57a3 100644 --- a/types/bluebird-retry/tslint.json +++ b/types/bluebird-retry/tslint.json @@ -1,7 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "no-reference-import": false, "prefer-template": false, "strict-export-declare-modifiers": false } From 8441c251e8df0337e897b32c4cefb11613454adc Mon Sep 17 00:00:00 2001 From: segayuu Date: Tue, 7 Nov 2017 12:34:10 +0900 Subject: [PATCH 093/495] cleanup ignore lint error: prefer-template --- types/bluebird-retry/bluebird-retry-tests.ts | 2 +- types/bluebird-retry/tslint.json | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/types/bluebird-retry/bluebird-retry-tests.ts b/types/bluebird-retry/bluebird-retry-tests.ts index 597f946335..e9beaf5562 100644 --- a/types/bluebird-retry/bluebird-retry-tests.ts +++ b/types/bluebird-retry/bluebird-retry-tests.ts @@ -7,7 +7,7 @@ function promiseSuccess(text: string) { 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 { diff --git a/types/bluebird-retry/tslint.json b/types/bluebird-retry/tslint.json index 84c5ab57a3..4c4fc86ace 100644 --- a/types/bluebird-retry/tslint.json +++ b/types/bluebird-retry/tslint.json @@ -1,7 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "prefer-template": false, "strict-export-declare-modifiers": false } } From 68a6a6273d4207dc9743b929c3261505ccbc0f5c Mon Sep 17 00:00:00 2001 From: segayuu Date: Tue, 7 Nov 2017 12:38:03 +0900 Subject: [PATCH 094/495] cleanup lint error: strict-export-declare-modifiers --- types/bluebird-retry/index.d.ts | 2 +- types/bluebird-retry/tslint.json | 7 +------ 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/types/bluebird-retry/index.d.ts b/types/bluebird-retry/index.d.ts index 0e39ef3b89..358c75936d 100644 --- a/types/bluebird-retry/index.d.ts +++ b/types/bluebird-retry/index.d.ts @@ -9,7 +9,7 @@ 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; diff --git a/types/bluebird-retry/tslint.json b/types/bluebird-retry/tslint.json index 4c4fc86ace..3db14f85ea 100644 --- a/types/bluebird-retry/tslint.json +++ b/types/bluebird-retry/tslint.json @@ -1,6 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "strict-export-declare-modifiers": false - } -} +{ "extends": "dtslint/dt.json" } From 25696174e1e6428c5cdd47d64eb8a99b54a5b506 Mon Sep 17 00:00:00 2001 From: Ron Martinez Date: Mon, 6 Nov 2017 23:10:19 -0500 Subject: [PATCH 095/495] Update webpack-hot-middleware to use `webpack.ICompiler` instead of `compiler.Compiler` --- types/webpack-hot-middleware/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/webpack-hot-middleware/index.d.ts b/types/webpack-hot-middleware/index.d.ts index 725fb65c4f..e7108008ac 100644 --- a/types/webpack-hot-middleware/index.d.ts +++ b/types/webpack-hot-middleware/index.d.ts @@ -1,15 +1,15 @@ // Type definitions for webpack-hot-middleware 2.16 // Project: https://github.com/glenjamin/webpack-hot-middleware#readme -// Definitions by: Benjamin Lim +// Definitions by: Benjamin Lim , Ron Martinez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import { NextHandleFunction } from 'connect'; -import { compiler } from 'webpack'; +import * as webpack from 'webpack'; export = WebpackHotMiddleware; declare function WebpackHotMiddleware( - compiler: compiler.Compiler, + compiler: webpack.ICompiler, options?: WebpackHotMiddleware.Options ): NextHandleFunction & WebpackHotMiddleware.EventStream; From b739873dd4952ecc78feca47cd3e1f8a3f7039d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Jalette?= Date: Tue, 7 Nov 2017 11:25:22 -0500 Subject: [PATCH 096/495] typo fix in class names (b2Pully to b2Pulley) --- types/box2d/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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. From b80407270a994022630b0526270588d1d8948def Mon Sep 17 00:00:00 2001 From: Herman-Freund Date: Tue, 7 Nov 2017 15:57:46 -0500 Subject: [PATCH 097/495] React - Updated index.d.ts Updated SVGAttributes' strokeMiterlimit to accept number or string --- types/react/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 8b2654db82..e6d87fdb9a 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -3190,7 +3190,7 @@ declare namespace React { strokeDashoffset?: string | number; strokeLinecap?: "butt" | "round" | "square" | "inherit"; strokeLinejoin?: "miter" | "round" | "bevel" | "inherit"; - strokeMiterlimit?: string; + strokeMiterlimit?: number | string; strokeOpacity?: number | string; strokeWidth?: number | string; surfaceScale?: number | string; From 402d56507fbe7975f895b86aace7c5dbb3ed44ab Mon Sep 17 00:00:00 2001 From: Herman-Freund Date: Tue, 7 Nov 2017 16:00:16 -0500 Subject: [PATCH 098/495] React v15 - Updated index.d.ts Updated SVGAttributes' strokeMiterlimit to accept number or string --- types/react/v15/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react/v15/index.d.ts b/types/react/v15/index.d.ts index 19cd290c7b..e3f738275b 100644 --- a/types/react/v15/index.d.ts +++ b/types/react/v15/index.d.ts @@ -3122,7 +3122,7 @@ declare namespace React { strokeDashoffset?: string | number; strokeLinecap?: "butt" | "round" | "square" | "inherit"; strokeLinejoin?: "miter" | "round" | "bevel" | "inherit"; - strokeMiterlimit?: string; + strokeMiterlimit?: number | string; strokeOpacity?: number | string; strokeWidth?: number | string; surfaceScale?: number | string; From af8f9c5fe496a41a51ac549e5084b34a68fa2393 Mon Sep 17 00:00:00 2001 From: Clark Stevenson Date: Tue, 7 Nov 2017 21:50:07 +0000 Subject: [PATCH 099/495] Update pixi.js to 4.6 --- types/pixi.js/index.d.ts | 65 ++++++++++++++++++++++++++-------- types/pixi.js/pixi.js-tests.ts | 61 +++++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+), 14 deletions(-) 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; From bc20b02f4ce24e255f8fdd1bcf5799d3b8477f89 Mon Sep 17 00:00:00 2001 From: ZheyangSong Date: Mon, 6 Nov 2017 16:16:55 -0800 Subject: [PATCH 100/495] Recharts Typing Update + Many interfaces are partially shaped or wrongly shaped. + Replace tab with 4-spaces --- types/recharts/index.d.ts | 1393 +++++++++++++++-------------- types/recharts/recharts-tests.tsx | 1 + 2 files changed, 743 insertions(+), 651 deletions(-) diff --git a/types/recharts/index.d.ts b/types/recharts/index.d.ts index c9bf71283d..81fa7aee98 100644 --- a/types/recharts/index.d.ts +++ b/types/recharts/index.d.ts @@ -3,843 +3,934 @@ // Definitions by: Maarten Mulders // Raphael Mueller // Roy Xue +// Zheyang Song // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import * as React from 'react'; +import { CurveFactory } from 'd3-shape'; export type Percentage = string; export type RechartsFunction = () => void; export type TickFormatterFunction = (value: any) => any; +export type TickGeneratorFunction = (noTicksProps: object) => any[]; export type LabelFormatter = (label: string | number) => React.ReactNode; export type TooltipFormatter = (value: string | number | Array, name: string, entry: TooltipPayload, index: number) => React.ReactNode; export type ItemSorter = (a: T, b: T) => number; export type ContentRenderer

= (props: P) => React.ReactNode; +export type DataKey = string | number | ((dataObject: any) => number | [number, number]); -export type LegendType = 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none'; +export type IconType = 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye'; +export type LegendType = IconType | 'none'; export type LayoutType = 'horizontal' | 'vertical'; export type AnimationEasingType = 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'; -export type ScaleType = 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utcTime' | 'sequential' | 'threshold'; -export type PositionType = 'top' | 'left' | 'right' | 'bottom' | 'inside' | 'outside'| 'insideLeft' | 'insideRight' | - 'insideTop' | 'insideBottom' | 'insideTopLeft' | 'insideBottomLeft' | 'insideTopRight' | 'insideBottomRight' | 'insideStart' | 'insideEnd' | 'end' | 'center'; +export type ScaleType = + 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | + 'ordinal' | 'quantile' | 'quantize' | 'utcTime' | 'sequential' | 'threshold'; +export type PositionType = + 'top' | 'left' | 'right' | 'bottom' | 'inside' | 'outside'| 'insideLeft' | 'insideRight' | + 'insideTop' | 'insideBottom' | 'insideTopLeft' | 'insideBottomLeft' | 'insideTopRight' | + 'insideBottomRight' | 'insideStart' | 'insideEnd' | 'end' | 'center'; +export type StackOffsetType = 'sign' | 'expand' | 'none' | 'wiggle' | 'silhouette'; +export type LineType = + 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | + 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | CurveFactory; +export type AxisInterval = number | 'preserveStart' | 'preserveEnd' | 'preserveStartEnd'; -export type PartialAndNumber = { - [P in keyof T]?: number | T[P]; -}; +export type PickedCSSStyleDeclarationKeys = + 'alignmentBaseline' | 'baselineShift' | 'clip' | 'clipPath' | 'clipRule' | 'color' | + 'colorInterpolationFilters' | 'cursor' | 'direction' | 'display' | 'dominantBaseline' | + 'enableBackground' | 'fill' | 'fillRule' | 'filter' | 'floodColor' | + 'floodOpacity' | 'font' | 'fontFamily' | 'fontStretch' | 'fontStyle' | 'fontVariant' | + 'glyphOrientationHorizontal' | 'glyphOrientationVertical' | 'letterSpacing' | 'lightingColor' | + 'markerEnd' | 'markerMid' | 'markerStart' | 'mask' | 'overflow' | 'pointerEvents' | + 'stopColor' | 'strokeDasharray' | 'strokeLinecap' | 'strokeLinejoin' | 'textAnchor' | + 'textDecoration' | 'unicodeBidi' | 'visibility' | 'writingMode' | 'transform'; -export interface Margin { - top: number; - right: number; - bottom: number; - left: number; +export interface Point { + x: number; + y: number; + value: number | any[]; } -export interface AreaProps extends Partial { - type?: 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | RechartsFunction; - dataKey?: string | number; - xAxisId?: string | number; - yAxisId?: string | number; - legendType?: LegendType; - dot?: boolean | any | React.ReactElement | RechartsFunction; - activeDot?: boolean | any | React.ReactElement | RechartsFunction; - label?: boolean | any | React.ReactElement | RechartsFunction; - stroke?: string; - layout?: LayoutType; - baseLine?: number | any[]; - points?: any[]; - stackId?: string | number; - connectNulls?: boolean; - unit?: string | number; - name?: string | number; - isAnimationActive?: boolean; - animationBegin?: number; - animationEasing?: AnimationEasingType; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface Margin { + top: number; + right: number; + bottom: number; + left: number; +} + +export interface Animatable { + onAnimationStart?: RechartsFunction; + onAnimationEnd?: RechartsFunction; + animationId?: number; + isAnimationActive?: boolean; + isUpdateAnimationActive?: boolean; + animationBegin?: number; + animationDuration?: number; + animationEasing?: AnimationEasingType; +} + +export interface CategoricalChartWrapper { + syncId?: string | number; + compact?: boolean; + width?: number; + height?: number; + data?: object[]; + layout?: L; + stackOffset?: StackOffsetType; + throttleDelay?: number; + margin?: Partial; + barCategoryGap?: number | string; + barGap?: number | string; + barSize?: number | string; + maxBarSize?: number; + style?: object; + className?: string; + children?: React.ReactNode | React.ReactNode[]; + onClick?: RechartsFunction; + onMouseLeave?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + reverseStackOrder?: boolean; +} + +export interface EventAttributes { + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + onTouchEnd?: RechartsFunction; + onTouchMove?: RechartsFunction; + onTouchStart?: RechartsFunction; + onTouchCancel?: RechartsFunction; +} + +export interface PresentationAttributes extends Pick { + angle: number; + colorInterpolation: string; + colorProfile: string; + colorRendering: string; + fillOpacity: number | string; + fontSize: number | string; + fontSizeAdjust: number | string; + fontWeight: 'normal' | 'bold' | 'bolder' | 'lighter' | + 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | 'inherit'; + imageRendering: 'auto' | 'optimizeSpeed' | 'optimizeQuality' | 'inherit'; + kerning: number | string; + opacity: number | string; + shapeRendering: 'auto' | 'optimizeSpeed' | 'crispEdges' | 'geometricPrecision' | 'inherit'; + stopOpacity: number | string; + stroke: number | string; + strokeDashoffset: number | string; + strokeMiterlimit: number | string; + strokeOpacity: number | string; + strokeWidth: number | string; + textRendering: 'auto' | 'optimizeSpeed' | 'optimizeLegibility' | 'geometricPrecision' | 'inherit'; + wordSpacing: number | string; + style: object; + width: number; + height: number; + dx: number; + dy: number; + x: X; + y: Y; + r: number; +} + +export interface AreaProps extends EventAttributes, Partial, Animatable { + dataKey: DataKey; // As the source code states, dataKey will replace valueKey in 1.1.0 and it'll be required (it's already required in current implementation). + className?: string; + type?: LineType; + unit?: string | number; + name?: string | number; + xAxisId?: string | number; + yAxisId?: string | number; + xAxis?: object; + yAxis?: object; + stackId?: string | number; + legendType?: LegendType; + connectNulls?: boolean; + activeDot?: boolean | object | React.ReactElement | ContentRenderer; + dot?: boolean | object | React.ReactElement | ContentRenderer; + label?: boolean | object | React.ReactElement | Label['content']; + hide?: boolean; + layout?: LayoutType; + baseLine?: number | any[]; + isRange?: boolean; + points?: Point[]; } export class Area extends React.Component { } -export interface AreaChartProps { - layout?: LayoutType; - syncId?: string; - width: number; - height: number; - data: any[]; - margin?: Margin; - stackOffset?: 'expand' | 'none' | 'wiggle' | 'silhouette'; - baseValue?: number | 'dataMin' | 'dataMax' | 'auto'; - onClick?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseLeave?: RechartsFunction; -} +// NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). +export type AreaChartProps = CategoricalChartWrapper & EventAttributes; export class AreaChart extends React.Component { } -export interface BarProps extends Partial { - layout?: LayoutType; - dataKey?: string | number; - xAxisId?: string | number; - yAxisId?: string | number; - legendType?: LegendType; - label?: boolean | any | React.ReactElement | RechartsFunction; - data?: any[]; - barSize?: number; - maxBarSize?: number; - minPointSize?: number; - shape?: React.ReactElement | RechartsFunction; - stackId?: string | number; - unit?: string | number; - name?: string | number; - isAnimationActive?: boolean; - animationBegin?: number; - animationEasing?: AnimationEasingType; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface BarData { + x: number; + y: number; + width: number; + height: number; + radius: number | any[]; + value: number | string | any[]; +} + +export interface BarProps extends EventAttributes, Partial, Animatable { + dataKey: DataKey; // As the source code states, dataKey will replace valueKey in 1.1.0 and it'll be required (it's already required in current implementation). + className?: string; + layout?: LayoutType; + xAxisId?: string | number; + yAxisId?: string | number; + yAxis?: object; + xAxis?: object; + stackId?: string | number; + barSize?: number; + unit?: string | number; + name?: string | number; + legendType?: LegendType; + minPointSize?: number; + maxBarSize?: number; + hide?: boolean; + shape?: React.ReactElement | ContentRenderer; + data?: BarData[]; } export class Bar extends React.Component { } -export interface BarChartProps { - layout?: LayoutType; - syncId?: string; - width?: number; - height?: number; - data?: any[]; - margin?: Margin; - barCategoryGap?: Percentage | number; - barGap?: Percentage | number; - barSize?: number; - maxBarSize?: number; - stackOffset?: 'expand' | 'none' | 'wiggle' | 'silhouette' | 'sign'; - onClick?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseLeave?: RechartsFunction; -} +// NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). +export type BarChartProps = CategoricalChartWrapper & EventAttributes; export class BarChart extends React.Component { } export interface BrushProps { - dataKey: number | string; - x?: number; - y?: number; - width?: number; - height?: number; - data: any[]; - travellerWidth?: number; - startIndex?: number; - endIndex?: number; - tickFormatter?: TickFormatterFunction; - onChange?: RechartsFunction; + className?: string; + fill?: string; + stroke?: string; + x: number; + y: number; + width: number; + height: number; + travellerWidth?: number; + padding?: Partial; + dataKey?: DataKey; + data?: any[]; + startIndex?: number; + endIndex?: number; + tickFormatter?: TickFormatterFunction; + children?: React.ReactNode; + onChange?: (newIndex: { + startIndex: number; + endIndex: number; + }) => void; + updateId?: string | number; } export class Brush extends React.Component { } -export interface CartesianAxisProps { - x?: number; - y?: number; - width?: number; - height?: number; - orientation?: 'top' | 'bottom' | 'left' | 'right'; - viewBox?: ViewBox; - axisLine?: boolean | any; - tickLine?: boolean | any; - minTickGap?: number; - tickSize?: number; - interval?: "preserveStart" | "preserveEnd" | "preserveStartEnd" | number; - tick?: boolean | any | React.ReactElement | RechartsFunction; - label?: string | number | React.ReactElement | ContentRenderer; - mirror?: boolean; +export interface CartesianAxisProps extends EventAttributes, Partial { + className?: string; + x?: number; + y?: number; + width?: number; + height?: number; + orientation?: 'top' | 'bottom' | 'left' | 'right'; + viewBox?: ViewBox; + tick?: boolean | ContentRenderer | object | React.ReactElement; + axisLine?: boolean | object; + tickLine?: boolean | object; + mirror?: boolean; + minTickGap?: number; + ticks?: any[]; + tickSize?: number; + stroke?: string; + tickFormatter?: TickFormatterFunction; + ticksGenerator?: TickGeneratorFunction; + interval?: AxisInterval; } export class CartesianAxis extends React.Component { } -export interface CartesianGridProps extends Partial { - x?: number; - y?: number; - horizontal?: boolean; - vertical?: boolean; - horizontalPoints?: any[]; - verticalPoints?: any[]; +export interface CartesianGridProps extends Partial { + y?: number; + width?: number; + height?: number; + horizontal?: object | React.ReactElement | ContentRenderer | boolean; + vertical?: object | React.ReactElement | ContentRenderer | boolean; + horizontalPoints?: number[]; + verticalPoints?: number[]; + horizontalCoordinatesGenerator?: (arg: { + yAxis: CartesianGridProps['yAxis']; + width: CartesianGridProps['chartWidth']; + height: CartesianGridProps['chartHeight']; + offset: CartesianGridProps['offset']; + }) => number[]; + verticalCoordinatesGenerator?: (arg: { + yAxis: CartesianGridProps['xAxis']; + width: CartesianGridProps['chartWidth']; + height: CartesianGridProps['chartHeight']; + offset: CartesianGridProps['offset']; + }) => number[]; + xAxis?: object; + yAxis?: object; + offset?: object; + chartWidth?: number; + chartHeight?: number; } export class CartesianGrid extends React.Component { } -export interface CellProps { - fill?: string; - stroke?: string; -} +// NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). +export type CellProps = Partial; export class Cell extends React.Component { } -export interface ComposedChartProps { - layout?: LayoutType; - syncId?: string; - width?: number; - height?: number; - data?: any[]; - margin?: Margin; - barCategoryGap?: Percentage | number; - barGap?: number; - barSize?: number; - onClick?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseLeave?: RechartsFunction; -} +// NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). +export type ComposedChartProps = CategoricalChartWrapper & EventAttributes; export class ComposedChart extends React.Component { } -export interface CrossProps { - x?: number; - y?: number; - top?: number; - left?: number; - width?: number; - height?: number; +export interface CrossProps extends Partial { + className?: string; + x?: number; + y?: number; + width?: number; + height?: number; + top?: number; + left?: number; } export class Cross extends React.Component { } -export interface CurveProps extends Partial { - type?: 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | RechartsFunction; - points: any[]; - layout?: LayoutType; - baseLine?: number | any[]; - connectNulls?: boolean; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +// NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). +export interface CurveProps extends EventAttributes, Partial { + className?: string; + type?: LineType; + layout?: LayoutType; + baseLine?: number | any[]; + points?: object[]; + connectNulls?: boolean; + path?: string; + pathRef?: React.Ref; } export class Curve extends React.Component { } -export interface DotProps { - cx: number; - cy: number; - r: number; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseLeave?: RechartsFunction; +// NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). +export interface DotProps extends EventAttributes { + className?: string; + cx?: number; + cy?: number; + r?: number; } export class Dot extends React.Component { } -export interface ErrorBarProps extends Partial { - dataKey?: string | number; - strokeWidth?: string; - stroke?: string; - direction?: string; +export interface ErrorBarProps { + dataKey: DataKey; // As the source code states, dataKey will replace valueKey in 1.1.0 and it'll be required (it's already required in current implementation). + data?: any[]; + xAxis?: object; + yAxis?: object; + layout?: string; + dataPointFormatter?: (entry: any, dataKey: DataKey) => { x: number; y: number, value: any; errorVal: any; }; + stroke?: string; + strokeWidth?: number; + width?: number; + offset?: number; } export class ErrorBar extends React.Component { } +export interface LegendPayload { + value: any; + id: any; + type: LegendType; +} + export interface LegendProps { - width?: number; - height?: number; - layout?: LayoutType; - align?: 'left' | 'center' | 'right'; - verticalAlign?: 'top' | 'middle' | 'bottom'; - iconSize?: number; - iconType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye'; - payload?: any[]; - chartWidth?: number; - chartHeight?: number; - margin?: Margin; - content?: React.ReactElement | ContentRenderer; - wrapperStyle?: any; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; + content?: React.ReactElement | ContentRenderer; + wrapperStyle?: object; + chartWidth?: number; + chartHeight?: number; + width?: number; + height?: number; + iconSize?: number; + iconType?: IconType; + layout?: LayoutType; + align?: 'left' | 'center' | 'right'; + verticalAlign?: 'top' | 'middle' | 'bottom'; + margin?: Partial; + payload?: LegendPayload[]; + formatter?: RechartsFunction; + onClick?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + onBBoxUpdate?: (box: { width: number; height: number; }) => void; } export class Legend extends React.Component { } -export interface LineProps extends Partial { - type?: 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | RechartsFunction; - dataKey: string | number; - xAxisId?: string | number; - yAxisId?: string | number; - legendType?: LegendType; - dot?: boolean | any | React.ReactElement | RechartsFunction; - activeDot?: boolean | any | React.ReactElement | RechartsFunction; - label?: boolean | any | React.ReactElement | RechartsFunction; - points?: any[]; // made this points property partial, since in every example they don't use this property. But their definition says not optional. - layout?: LayoutType; - connectNulls?: boolean; - unit?: string | number; - name?: string | number; - isAnimationActive?: boolean; - animationBegin?: number; - animationEasing?: AnimationEasingType; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface LineProps extends EventAttributes, Partial, Animatable { + className?: string; + type?: LineType; + unit?: string | number; + name?: string | number; + xAxisId?: string | number; + yAxisId?: string | number; + yAxis?: object; + xAxis?: object; + legendType?: LegendType; + layout?: LayoutType; + connectNulls?: boolean; + hide?: boolean; + activeDot?: object | React.ReactElement | ContentRenderer | boolean; + dot?: object | React.ReactElement | ContentRenderer | boolean; + top?: number; + left?: number; + width?: number; + height?: number; + dataKey: string | number; // As the source code states, dataKey will replace valueKey in 1.1.0 and it'll be required (it's already required in current implementation). + label?: boolean | object | React.ReactElement | Label['content']; + points?: Point[]; } export class Line extends React.Component { } -export interface LineChartProps { - layout?: LayoutType; - syncId?: string; - width?: number; - height?: number; - data?: any[]; - margin?: Margin; - onClick?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseLeave?: RechartsFunction; -} +// NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). +export type LineChartProps = CategoricalChartWrapper & EventAttributes; export class LineChart extends React.Component { } -export interface PieProps extends Partial { - cx?: Percentage | number; - cy?: Percentage | number; - innerRadius?: Percentage | number; - outerRadius?: Percentage | number; - startAngle?: number; - endAngle?: number; - minAngle?: number; - paddingAngle?: number; - nameKey?: string; - dataKey?: string; - valueKey?: string; - legendType?: LegendType; - label?: boolean | any | React.ReactElement | RechartsFunction; - labelLine?: boolean | any | React.ReactElement | RechartsFunction; - data: any[]; - activeIndex?: number | number[]; - activeShape?: any | React.ReactElement | RechartsFunction; - isAnimationActive?: boolean; - animationBegin?: number; - animationEasing?: AnimationEasingType | RechartsFunction; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface PieProps extends EventAttributes, Partial, Animatable { + className?: string; + dataKey: DataKey; // As the source code states, dataKey will replace valueKey in 1.1.0 and it'll be required (it's already required in current implementation). + cx?: number | string; + cy?: number | string; + startAngle?: number; + endAngle?: number; + paddingAngle?: number; + innerRadius?: number | string; + outerRadius?: number | string; + cornerRadius?: number | string; + nameKey?: string | number | ((dataObject: any) => number); + valueKey?: string | number | ((dataObject: any) => number); + data?: object[]; + minAngle?: number; + legendType?: LegendType; + maxRadius?: number; + sectors?: object[]; + hide?: boolean; + labelLine?: object | ContentRenderer | React.ReactElement | boolean; + label?: { + offsetRadius: number; + } | Label['content'] | React.ReactElement | boolean; + activeShape?: object |ContentRenderer | React.ReactElement; + activeIndex?: number | number[]; } export class Pie extends React.Component { } -export interface PieChartProps { - width: number; - height: number; - margin?: Margin; - onClick?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +// NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). +export interface PieChartProps extends EventAttributes, CategoricalChartWrapper<'centric'> { + startAngle?: number; + endAngle?: number; + cx?: number | string; + cy?: number | string; + innerRadius?: number | string; + outerRadius?: number | string; } export class PieChart extends React.Component { } -export interface PolarAngleAxisProps { - dataKey: string | number; - cx: number; - cy: number; - radius: Percentage | number; - axisLine?: boolean | any; - axisLineType?: string; - tickLine?: boolean | any; - tick?: boolean | any | React.ReactElement | RechartsFunction; - ticks: any[]; - orient?: string; - tickFormatter: TickFormatterFunction; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface PolarAngleAxisTick { + value: any; + coordinate: number; +} + +export interface PolarAngleAxisProps extends EventAttributes, Partial { + type?: 'number' | 'category'; + angleAxisId?: string | number; + dataKey?: DataKey; // As the source code states, dataKey will replace valueKey in 1.1.0 and it'll be required (it's already required in current implementation). + cx?: number; + cy?: number; + radius?: Percentage | number; + hide?: boolean; + scale?: ScaleType | RechartsFunction; // this seems not being used by the lib. + axisLine?: boolean | object; + axisLineType?: 'polygon' | 'circle'; + tickLine?: boolean | object; + tick?: boolean | ContentRenderer | object | React.ReactElement; + ticks?: PolarAngleAxisTick[]; + stroke?: string; + orientation?: 'inner' | 'outer'; + tickFormatter: TickFormatterFunction; } export class PolarAngleAxis extends React.Component { } -export interface PolarGridProps extends Partial { - cx: number; - cy: number; - innerRadius: number; - outerRadius: number; - polarAngles: any[]; - polarRadius: any[]; - gridType?: 'polygon' | 'circle'; +export interface PolarGridProps extends Partial { + cx?: number; + cy?: number; + innerRadius?: number; + outerRadius?: number; + polarAngles?: number[]; + polarRadius?: number[]; + gridType?: 'polygon' | 'circle'; } export class PolarGrid extends React.Component { } -export interface PolarRadiusAxisProps { - angle?: number; - cx: number; - cy: number; - domain?: any[]; - label?: string | number | React.ReactElement | RechartsFunction; - orientation?: "left" | "right" | "middle"; - axisLine?: boolean | any; - tick?: boolean | any | Element | RechartsFunction; - tickFormatter: TickFormatterFunction; - tickCount?: number; - scale?: ScaleType | RechartsFunction; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface PolarRadiusAxisTick { + value: any; + coordinate: number; +} + +export type PolarRadiusAxisDomain = number | 'auto' | 'dataMin' | 'dataMax'; + +export interface PolarRadiusAxisProps extends EventAttributes, Partial { + type?: 'number' | 'category'; + cx?: number; + cy?: number; + hide?: boolean; + radiusAxisId?: string | number; + angle?: number; + tickCount?: number; + ticks?: PolarRadiusAxisTick[]; + orientation?: "left" | "right" | "middle"; + axisLine?: boolean | object; + tick?: boolean | object | React.ReactElement | ContentRenderer; + stroke?: string; + tickFormatter: TickFormatterFunction; + domain?: PolarRadiusAxisDomain[]; + scale?: ScaleType | RechartsFunction; + allowDataOverflow?: boolean; } export class PolarRadiusAxis extends React.Component { } -export interface PolygonProps { - points: any[]; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface PolygonPoint { + x: number; + y: number; +} + +export interface PolygonProps extends EventAttributes, Partial { + className?: string; + points?: PolygonPoint[]; } export class Polygon extends React.Component { } -export interface RadarProps extends Partial { - dataKey: string | number; - points: any[]; - shape: Element | RechartsFunction; - dot?: boolean | any | Element | RechartsFunction; - legendType?: LegendType; - label?: boolean | any | Element | RechartsFunction; - isAnimationActive?: boolean; - animationBegin?: number; - animationEasing?: AnimationEasingType; +export interface RadarPoint { + x: number; + y: number; + cx: number; + cy: number; + angle: number; + radius: number; + value: number; + payload: object; +} + +export interface RadarProps extends EventAttributes, Partial, Animatable { + className?: string; + dataKey: DataKey; // As the source code states, dataKey will replace valueKey in 1.1.0 and it'll be required (it's already required in current implementation). + points?: RadarPoint[]; + shape?: React.ReactElement | ContentRenderer; + activeDot?: object | React.ReactElement | ContentRenderer | boolean; + dot?: object | React.ReactElement | ContentRenderer | boolean; + label?: object | React.ReactElement | Label['content'] | boolean; + legendType?: LegendType; + hide?: boolean; } export class Radar extends React.Component { } -export interface RadarChartProps { - width: number; - height: number; - cx?: Percentage | number; - cy?: Percentage | number; - startAngle?: number; - innerRadius?: Percentage | number; - outerRadius?: Percentage | number; - margin?: Margin; - clockWise?: boolean; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - onClick?: RechartsFunction; +// NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). +export interface RadarChartProps extends EventAttributes, CategoricalChartWrapper<'centric'> { + startAngle?: number; + endAngle?: number; + cx?: number | string; + cy?: number | string; + innerRadius?: number | string; + outerRadius?: number | string; } export class RadarChart extends React.Component { } -export interface RadialBarProps extends Partial { - cx?: number; - cy?: number; - startAngle?: number; - endAngle?: number; - maxAngle?: number; - minAngle?: number; - legendType?: LegendType; - label?: boolean | any | React.ReactElement | RechartsFunction; - background?: boolean | any | React.ReactElement | RechartsFunction; - data: any[]; - isAnimationActive?: boolean; - animationBegin?: number; - animationEasing?: AnimationEasingType; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface RadialBarData { + cx: number; + cy: number; + innerRadius: number; + outerRadius: number; + value: any; +} + +export interface RadialBarProps extends EventAttributes, Partial, Animatable { + className?: string; + dataKey: DataKey; // As the source code states, dataKey will replace valueKey in 1.1.0 and it'll be required (it's already required in current implementation). + angleAxisId?: string | number; + radiusAxisId?: string | number; + shape?: ContentRenderer | React.ReactElement; + activeShape?: object | ContentRenderer | React.ReactElement; + cornerRadius?: number | string; + minPointSize?: number; + maxBarSize?: number; + data?: RadialBarData[]; + legendType?: LegendType; + label?: boolean | React.ReactElement | Label['content'] | object; + background?: boolean | React.ReactElement | ContentRenderer | object; + hide?: boolean; } export class RadialBar extends React.Component { } -export interface RadialBarChartProps { - width?: number; - height?: number; - data?: any[]; - margin?: Margin; - barCategoryGap?: Percentage | number; - barGap?: number; - cx?: Percentage | number; - cy?: Percentage | number; - innerRadius?: Percentage | number; - outerRadius?: Percentage | number; - barSize?: number; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - onClick?: RechartsFunction; +export interface RadialBarChartProps extends CategoricalChartWrapper<'radial'> { + startAngle?: number; + endAngle?: number; + cx?: string | number; + cy?: string | number; + innerRadius?: string | number; + outerRadius?: string | number; } export class RadialBarChart extends React.Component { } -export interface RectangleProps extends Partial { - x?: number; - y?: number; - radius?: number; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface RectangleProps extends EventAttributes, Partial, Animatable { + className?: string; + x?: number; + y?: number; + width?: number; + height?: number; + radius?: number | any[]; } export class Rectangle extends React.Component { } -export interface ReferenceAreaProps extends PartialAndNumber { - xAxisId?: string | number; - yAxisId?: string | number; - x1?: number | string; - x2?: number | string; - y1?: number | string; - y2?: number | string; - alwaysShow?: boolean; - viewBox?: ViewBox; - xAxis?: any; - yAxis?: any; - label?: string | number | React.ReactElement | ContentRenderer; - isFront?: boolean; +export interface ReferenceAreaProps extends Partial { + className?: number | string; + viewBox?: ViewBox; + xAxis?: object; + yAxis?: object; + isFront?: boolean; + alwaysShow?: boolean; + x1?: number | string; + x2?: number | string; + y1?: number | string; + y2?: number | string; + xAxisId?: string | number; + yAxisId?: string | number; + shape?: ContentRenderer | React.ReactElement; } export class ReferenceArea extends React.Component { } -export interface ReferenceDotProps { - xAxisId?: string | number; - yAxisId?: string | number; - x: number | string; - y: number | string; - r: number; - alwaysShow?: boolean; - xAxis: any; - yAxis: any; - label?: string | number | React.ReactElement | ContentRenderer; - isFront?: boolean; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface ReferenceDotProps extends EventAttributes, Partial> { + className?: number | string; + r?: number; + xAxis?: { scale: (x: ReferenceDotProps['x']) => number }; + yAxis?: { scale: (y: ReferenceDotProps['y']) => number }; + isFront?: boolean; + alwaysShow?: boolean; + x?: number | string; + y?: number | string; + xAxisId?: string | number; + yAxisId?: string | number; + shape?: ContentRenderer< + EventAttributes + & Partial> + & { cx: number; cy: number; } + > | React.ReactElement; } export class ReferenceDot extends React.Component { } -export interface ReferenceLineProps extends PartialAndNumber { - xAxisId?: string | number; - yAxisId?: string | number; - x?: number | string; - y?: number | string; - alwaysShow?: boolean; - viewBox?: ViewBox; - xAxis?: any; - yAxis?: any; - label?: string | number | React.ReactElement | ContentRenderer; - isFront?: boolean; +export interface ReferenceLineProps extends Partial> { + className?: number | string; + viewBox?: ViewBox; + xAxis?: object; + yAxis?: object; + isFront?: boolean; + alwaysShow?: boolean; + x?: number | string; + y?: number | string; + xAxisId?: string | number; + yAxisId?: string | number; + shape?: ContentRenderer< + EventAttributes + & Partial> + & { x1: number; y1: number; x2: number; y2: number; } + > | React.ReactElement; } export class ReferenceLine extends React.Component { } export interface ResponsiveContainerProps { - aspect?: number; - width?: Percentage | number; - height?: Percentage | number; - minWidth?: number; - minHeight?: number; - maxHeight?: Percentage | number; - debounce?: number; + aspect?: number; + width?: string | number; + height?: string | number; + minHeight?: string | number; + minWidth?: string | number; + maxHeight?: string | number; + children: React.ReactNode; + debounce?: number; + id?: string | number; } export class ResponsiveContainer extends React.Component { } -export interface ScatterProps extends Partial { - legendType?: LegendType; - xAxisId?: string | number; - yAxisId?: string | number; - zAxisId?: string | number; - line?: boolean | any | React.ReactElement | RechartsFunction; - shape?: 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | React.ReactElement | RechartsFunction; - lineType?: 'joint' | 'fitting'; - points: any[]; - isAnimationActive?: boolean; - animationBegin?: number; - animationEasing?: AnimationEasingType; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface ScatterPoint { + cx?: number; + cy?: number; + size?: number; + node?: { + x?: number | string; + y?: number | string; + z?: number | string; + }; + payload?: any; +} + +export interface ScatterProps extends EventAttributes, Partial, Animatable { + xAxisId?: string | number; + yAxisId?: string | number; + zAxisId?: string | number; + line?: boolean | object | RechartsFunction | React.ReactElement; + lineType?: 'joint' | 'fitting'; + lineJointType?: LineType; + legendType?: LegendType; + activeIndex?: number; + activeShape?: object | RechartsFunction | React.ReactElement; + shape?: 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | React.ReactElement | ContentRenderer; + points?: ScatterPoint[]; + hide?: boolean; } export class Scatter extends React.Component { } -export interface ScatterChartProps { - width: number; - height: number; - margin?: Margin; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; -} +// NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). +export type ScatterChartProps = CategoricalChartWrapper & EventAttributes; export class ScatterChart extends React.Component { } -export interface SectorProps { - cx?: number; - cy?: number; - innerRadius?: number; - outerRadius?: number; - startAngle?: number; - endAngle?: number; - cornerRadius?: number; - fill?: string; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface SectorProps extends EventAttributes, Partial { + className?: string; + cx?: number; + cy?: number; + innerRadius?: number; + outerRadius?: number; + startAngle?: number; + endAngle?: number; + cornerRadius?: number | string; } export class Sector extends React.Component { } -export interface TextProps extends Partial { - scaleToFit?: boolean; - angle?: number; - textAnchor?: 'start' | 'middle' | 'end' | 'inherit'; - verticalAnchor?: 'start' | 'middle' | 'end'; +export interface TextProps extends Partial { + scaleToFit?: boolean; + angle?: number; + textAnchor?: 'start' | 'middle' | 'end' | 'inherit'; + verticalAnchor?: 'start' | 'middle' | 'end'; + style?: object; } export class Text extends React.Component { } export interface ViewBox { - x?: number; - y?: number; - width?: number; - height?: number; + x?: number; + y?: number; + width?: number; + height?: number; } + export interface PolarViewBox { - cx?: number; - cy?: number; - innerRadius?: number; - outerRadius?: number; - startAngle?: number; - endAngle?: number; + cx?: number; + cy?: number; + innerRadius?: number; + outerRadius?: number; + startAngle?: number; + endAngle?: number; } + export interface Coordinate { - x: number; - y: number; + x: number; + y: number; } + export interface TooltipPayload { - name: string; - value: string | number | Array; - unit: string; + name: string; + value: string | number | Array; + unit: string; } -export interface TooltipProps { - separator?: string; - offset?: number; - itemStyle?: any; - wrapperStyle?: any; - labelStyle?: any; - cursor?: boolean | any | React.ReactElement | React.StatelessComponent; - viewBox?: ViewBox; - active?: boolean; - coordinate?: Coordinate; - payload?: TooltipPayload[]; - label?: string | number; - content?: React.ReactElement | React.StatelessComponent | ContentRenderer; - formatter?: TooltipFormatter; - labelFormatter?: LabelFormatter; - itemSorter?: ItemSorter; - isAnimationActive?: boolean; - animationBegin?: number; - animationEasing?: AnimationEasingType; - filterNull?: boolean; + +export interface TooltipProps extends Animatable { + content?: React.ReactElement | React.StatelessComponent | ContentRenderer; + viewBox?: ViewBox; + active?: boolean; + separator?: string; + formatter?: TooltipFormatter; + offset?: number; + itemStyle?: object; + labelStyle?: object; + wrapperStyle?: object; + cursor?: boolean | object | React.ReactElement | React.StatelessComponent; + coordinate?: Coordinate; + position?: Coordinate; + label?: any; + payload?: TooltipPayload[]; + itemSorter?: ItemSorter; + filterNull?: boolean; } export class Tooltip extends React.Component { } -export interface TreemapProps { - data: any[]; - width?: number; - height?: number; - dataKey?: string; - aspectRatio: number; - isAnimationActive?: boolean; - animationBegin?: number; - animationEasing?: AnimationEasingType; -} - -export interface Label { - viewBox?: ViewBox | PolarViewBox; - formatter?: LabelFormatter; - value: string | number; - position?: PositionType; - offset?: number; - content?: React.ReactElement | ContentRenderer

{INLINE_STYLES.map(type => , document.getElementById('target') ); + +const editorState = EditorState.createEmpty(); +const contentState = editorState.getCurrentContent(); +const rawContentState: RawDraftContentState = convertToRaw(contentState); + +rawContentState.blocks.forEach((block: RawDraftContentBlock) => { + block.entityRanges.forEach((entityRange: RawDraftEntityRange) => { + const { key, offset, length } = entityRange; + const entity: RawDraftEntity = rawContentState.entityMap[key]; + const entityType: DraftEntityType = entity.type; + const entityMutability: DraftEntityMutability = entity.mutability; + console.log(entityType, entityMutability, offset, length); + }); + + block.inlineStyleRanges.forEach((inlineStyleRange: RawDraftInlineStyleRange) => { + const { offset, length } = inlineStyleRange + const inlineStyle: DraftInlineStyleType = inlineStyleRange.style; + console.log(inlineStyle, offset, length); + }); +}); diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts index 088d083a7f..0897fb72f9 100644 --- a/types/draft-js/index.d.ts +++ b/types/draft-js/index.d.ts @@ -260,9 +260,10 @@ declare namespace Draft { * or block types. */ "bold" | - "italic" | - "underline" | "code" | + "italic" | + "strikethrough" | + "underline" | /** * Split a block in two. @@ -326,6 +327,60 @@ declare namespace Draft { * another fragment or if the selected fragment shall be replaced */ type DraftInsertionType = "replace" | "before" | "after"; + + /** + * Valid inline styles. + */ + type DraftInlineStyleType = ( + "BOLD" | + "CODE" | + "ITALIC" | + "STRIKETHROUGH" | + "UNDERLINE" + ) + + /** + * Default entity types. + */ + type ComposedEntityType = ( + "LINK" | + "TOKEN" | + "PHOTO" | + "IMAGE" + ) + + /** + * Possible entity types. + */ + type DraftEntityType = string | ComposedEntityType; + + /** + * Possible "mutability" options for an entity. This refers to the behavior + * that should occur when inserting or removing characters in a text range + * with an entity applied to it. + * + * `MUTABLE`: + * The text range can be modified freely. Generally used in cases where + * the text content and the entity do not necessarily have a direct + * relationship. For instance, the text and URI for a link may be completely + * different. The user is allowed to edit the text as needed, and the entity + * is preserved and applied to any characters added within the range. + * + * `IMMUTABLE`: + * Not to be confused with immutable data structures used to represent the + * state of the editor. Immutable entity ranges cannot be modified in any + * way. Adding characters within the range will remove the entity from the + * entire range. Deleting characters will delete the entire range. Example: + * Facebook Page mentions. + * + * `SEGMENTED`: + * Segmented entities allow the removal of partial ranges of text, as + * separated by a delimiter. Adding characters wihin the range will remove + * the entity from the entire range. Deleting characters within a segmented + * entity will delete only the segments affected by the deletion. Example: + * Facebook User mentions. + */ + type DraftEntityMutability = "MUTABLE" | "IMMUTABLE" | "SEGMENTED"; } namespace Decorators { @@ -406,14 +461,24 @@ declare namespace Draft { } namespace Encoding { + import DraftInlineStyleType = Draft.Model.Constants.DraftInlineStyleType; + import DraftBlockType = Draft.Model.Constants.DraftBlockType; + import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; + import DraftEntityType = Draft.Model.Constants.DraftEntityType; + import ContentBlock = Draft.Model.ImmutableData.ContentBlock; import ContentState = Draft.Model.ImmutableData.ContentState; import DraftBlockRenderMap = Draft.Component.Base.DraftBlockRenderMap; - import DraftBlockType = Draft.Model.Constants.DraftBlockType; - import DraftEntityType = Draft.Model.Entity.DraftEntityType; - import DraftEntityMutability = Draft.Model.Entity.DraftEntityMutability; + /** + * A plain object representation of an inline style range. + */ + interface RawDraftInlineStyleRange { + style: DraftInlineStyleType; + offset: number; + length: number; + } /** * A plain object representation of an entity attribution. @@ -421,21 +486,12 @@ declare namespace Draft { * The `key` value corresponds to the key of the entity in the `entityMap` of * a `ComposedText` object, not for use with `DraftEntity.get()`. */ - interface EntityRange { + interface RawDraftEntityRange { key: number, offset: number, length: number, } - /** - * A plain object representation of an inline style range. - */ - interface InlineStyleRange { - style: string; - offset: number; - length: number; - } - /** * A plain object representation of an EntityInstance. */ @@ -454,8 +510,8 @@ declare namespace Draft { type: DraftBlockType; text: string; depth: number; - inlineStyleRanges: Array; - entityRanges: Array; + inlineStyleRanges: Array; + entityRanges: Array; data?: Object; } @@ -479,36 +535,8 @@ declare namespace Draft { } namespace Entity { - type ComposedEntityType = "LINK" | "TOKEN" | "PHOTO"; - type DraftEntityType = string | ComposedEntityType; - - /** - * An enum representing the possible "mutability" options for an entity. - * This refers to the behavior that should occur when inserting or removing - * characters in a text range with an entity applied to it. - * - * `MUTABLE`: - * The text range can be modified freely. Generally used in cases where - * the text content and the entity do not necessarily have a direct - * relationship. For instance, the text and URI for a link may be completely - * different. The user is allowed to edit the text as needed, and the entity - * is preserved and applied to any characters added within the range. - * - * `IMMUTABLE`: - * Not to be confused with immutable data structures used to represent the - * state of the editor. Immutable entity ranges cannot be modified in any - * way. Adding characters within the range will remove the entity from the - * entire range. Deleting characters will delete the entire range. Example: - * Facebook Page mentions. - * - * `SEGMENTED`: - * Segmented entities allow the removal of partial ranges of text, as - * separated by a delimiter. Adding characters wihin the range will remove - * the entity from the entire range. Deleting characters within a segmented - * entity will delete only the segments affected by the deletion. Example: - * Facebook User mentions. - */ - type DraftEntityMutability = "MUTABLE" | "IMMUTABLE" | "SEGMENTED"; + import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; + import DraftEntityType = Draft.Model.Constants.DraftEntityType; /** * A "document entity" is an object containing metadata associated with a @@ -577,10 +605,10 @@ declare namespace Draft { namespace ImmutableData { import DraftBlockType = Draft.Model.Constants.DraftBlockType; - import DraftDecoratorType = Draft.Model.Decorators.DraftDecoratorType; + import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; + import DraftEntityType = Draft.Model.Constants.DraftEntityType; - import DraftEntityType = Draft.Model.Entity.DraftEntityType; - import DraftEntityMutability = Draft.Model.Entity.DraftEntityMutability; + import DraftDecoratorType = Draft.Model.Decorators.DraftDecoratorType; type DraftInlineStyle = Immutable.OrderedSet; type BlockMap = Immutable.OrderedMap; @@ -936,6 +964,10 @@ import RichUtils = Draft.Model.Modifier.RichTextEditorUtil; import DefaultDraftBlockRenderMap = Draft.Model.ImmutableData.DefaultDraftBlockRenderMap; import DefaultDraftInlineStyle = Draft.Model.ImmutableData.DefaultDraftInlineStyle; +import RawDraftInlineStyleRange = Draft.Model.Encoding.RawDraftInlineStyleRange; +import RawDraftEntityRange = Draft.Model.Encoding.RawDraftEntityRange; +import RawDraftEntity = Draft.Model.Encoding.RawDraftEntity; +import RawDraftContentBlock = Draft.Model.Encoding.RawDraftContentBlock; import RawDraftContentState = Draft.Model.Encoding.RawDraftContentState; import convertFromRaw = Draft.Model.Encoding.convertFromRawToDraftState; import convertToRaw = Draft.Model.Encoding.convertFromDraftStateToRaw; @@ -948,6 +980,9 @@ import getVisibleSelectionRect = Draft.Component.Selection.getVisibleSelectionRe import DraftEditorCommand = Draft.Model.Constants.DraftEditorCommand; import DraftDragType = Draft.Model.Constants.DraftDragType; import DraftBlockType = Draft.Model.Constants.DraftBlockType; +import DraftInlineStyleType = Draft.Model.Constants.DraftInlineStyleType; +import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; +import DraftEntityType = Draft.Model.Constants.DraftEntityType; import DraftRemovalDirection = Draft.Model.Constants.DraftRemovalDirection; import DraftHandleValue = Draft.Model.Constants.DraftHandleValue; import DraftInsertionType = Draft.Model.Constants.DraftInsertionType; @@ -977,6 +1012,10 @@ export { DefaultDraftBlockRenderMap, DefaultDraftInlineStyle, + RawDraftInlineStyleRange, + RawDraftEntityRange, + RawDraftEntity, + RawDraftContentBlock, RawDraftContentState, convertFromRaw, convertToRaw, @@ -989,6 +1028,9 @@ export { DraftEditorCommand, DraftDragType, DraftBlockType, + DraftInlineStyleType, + DraftEntityType, + DraftEntityMutability, DraftRemovalDirection, DraftHandleValue, DraftInsertionType, From de379ff573059030c28c86335dc49cad48360f20 Mon Sep 17 00:00:00 2001 From: Brannon Jones Date: Wed, 8 Nov 2017 14:56:26 -0700 Subject: [PATCH 104/495] Add support for Stripe Payouts API --- types/stripe/index.d.ts | 203 ++++++++++++++++++++++++++++++++++- types/stripe/stripe-tests.ts | 112 +++++++++++++++++++ 2 files changed, 314 insertions(+), 1 deletion(-) diff --git a/types/stripe/index.d.ts b/types/stripe/index.d.ts index f0596623ea..f150bb0dd2 100644 --- a/types/stripe/index.d.ts +++ b/types/stripe/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for stripe 4.7 +// Type definitions for stripe 4.8 // Project: https://github.com/stripe/stripe-node/ // Definitions by: William Johnston // Peter Harris // Sampson Oliver // Linus Unnebäck +// Brannon Jones // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -39,6 +40,7 @@ declare class Stripe { events: Stripe.resources.Events; invoices: Stripe.resources.Invoices; invoiceItems: Stripe.resources.InvoiceItems; + payouts: Stripe.resources.Payouts; plans: Stripe.resources.Plans; /** * @deprecated @@ -2594,6 +2596,164 @@ declare namespace Stripe { type OrderStatus = "created" | "paid" | "canceled" | "fulfilled" | "returned"; } + namespace payouts { + interface IPayout extends IResourceObject { + /** + * Value is "payout" + */ + object: "payout"; + + /** + * Amount (in cents) to be transferred to your bank account or debit card + */ + amount: number; + + /** + * Date the payout is expected to arrive in the bank. This factors in delays like weekends or bank holidays + */ + arrival_date: number; + + /** + * Balance transaction that describes the impact of this transfer on your account balance. [Expandable] + */ + balance_transaction: string | balance.IBalanceTransaction; + + /** + * Time at which the object was created. Measured in seconds since the Unix epoch + */ + created: number; + + /** + * Three-letter ISO currency code, in lowercase. Must be a supported currency. + * https://stripe.com/docs/currencies + */ + currency: string; + + /** + * An arbitrary string attached to the object. Often useful for displaying to users + */ + description: string; + + /** + * ID of the bank account or card the payout was sent to. [Expandable] + */ + destination: string | bankAccounts.IBankAccount | cards.ICardHash; + + /** + * If the payout failed or was canceled, this will be the ID of the balance + * transaction that reversed the initial balance transaction, and puts the + * funds from the failed payout back in your balance. [Expandable] + */ + failure_balance_transaction: string | balance.IBalanceTransaction; + + /** + * Error code explaining reason for payout failure if available. See Types of payout failures for a + * list of failure codes: https://stripe.com/docs/api#payout_failures + */ + failure_code: string; + + /** + * Message to user further explaining reason for the payout failure if available + */ + failure_message: string; + + /** + * Flag indicating whether the object exists in live mode or test mode + */ + livemode: boolean; + + /** + * Set of key/value pairs that you can attach to an object. It can be useful for storing additional + * information about the object in a structured format. + */ + metadata: IMetadata; + + /** + * The method used to send this payout, which can be standard or instant. instant is only supported + * for payouts to debit cards. + */ + method: PayoutMethods; + + /** + * The source balance this payout came from. + * One of card, bank_account, bitcoin_receiver, or alipay_account + */ + source_type: "alipay_account" | "bank_account" | "bitcoin_receiver" | "card"; + + /** + * Extra information about a payout to be displayed on the user's bank statement + */ + statement_descriptor: string; + + /** + * Current status of the payout (paid, pending, in_transit, canceled or failed). + * A payout will be pending until it is submitted to the bank, at which point it + * becomes in_transit. It will then change to paid if the transaction goes through. + * If it does not go through successfully, its status will change to failed or canceled. + */ + status: "canceled" | "failed" | "in_transit" | "paid" | "pending"; + + /** + * Can be bank_account or card. + */ + type: PayoutTypes; + } + + interface IPayoutCreationOptions extends IDataOptionsWithMetadata { + /** + * A positive integer in cents representing how much to payout. + */ + amount: number; + + /** + * Three-letter ISO currency code, in lowercase. Must be a supported currency. + * https://stripe.com/docs/currencies + */ + currency: string; + + /** + * An arbitrary string attached to the object. Often useful for displaying to users. + * This can be unset by updating the value to null and then saving. + */ + description?: string; + + /** + * The ID of a bank account or a card to send the payout to. If no destination is supplied, + * the default external account for the specified currency will be used. + */ + destination?: string; + + /** + * The method used to send this payout, which can be standard or instant. + * instant is only supported for payouts to debit cards. + */ + method?: PayoutMethods; + + /** + * The source balance to draw this payout from. Balances for different payment sources are + * kept separately. You can find the amounts with the balances API. + * Valid options are: alipay_account, bank_account, and card. + */ + source_type?: "alipay_account" | "bank_account" | "card"; + + /** + * A string to be displayed on the recipient’s bank or card statement. This may be at most 22 characters. + * Attempting to use a statement_descriptor longer than 22 characters will return an error. + * Note: Most banks will truncate this information and/or display it inconsistently. Some may not display it at all. + */ + statement_descriptor?: string; + } + + interface IPayoutListOptions extends IListOptionsCreated { + arrival_date?: string | IDateFilter; + destination?: string; + status?: "canceled" | "failed" | "paid" | "pending"; + } + + type PayoutMethods = "instant" | "standard"; + type PayoutTypes = "bank_account" | "card"; + } + namespace plans { /** * A subscription plan contains the pricing information for different products and feature levels on your site. @@ -5813,6 +5973,47 @@ declare namespace Stripe { del(invoiceItemId: string, response?: IResponseFn): Promise; } + class Payouts extends StripeResource { + /** + * To send funds to your own bank account, you create a new payout object. Your Stripe balance must be able to cover the payout amount, or you’ll receive an “Insufficient Funds” error. + * + * If your API key is in test mode, money won’t actually be sent, though everything else will occur as if in live mode. + * + * If you are creating a manual payout on a Stripe account that uses multiple payment source types, you’ll need to specify the source type balance that the payout should draw from. + * The balance object details available and pending amounts by source type. + * + */ + create(data: payouts.IPayoutCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; + create(data: payouts.IPayoutCreationOptions, response?: IResponseFn): Promise; + + /** + * Retrieves the details of an existing payout. Supply the unique payout ID from either a payout creation request or the payout list, and Stripe will return the corresponding payout information. + */ + retrieve(payoutId: string, options: HeaderOptions, response?: IResponseFn): Promise; + retrieve(payoutId: string, response?: IResponseFn): Promise; + + /** + * Updates the specified payout by setting the values of the parameters passed. Any parameters not provided will be left unchanged. This request accepts only the metadata as arguments. + */ + update(payoutId: string, data: IDataOptionsWithMetadata, options: HeaderOptions, response?: IResponseFn): Promise; + update(payoutId: string, data: IDataOptionsWithMetadata, response?: IResponseFn): Promise; + + /** + * Returns a list of existing payouts sent to third-party bank accounts or that Stripe has sent you. The payouts are returned in sorted order, with the most recently created payouts appearing first. + */ + list(data: payouts.IPayoutListOptions, options: HeaderOptions, response?: IResponseFn>): Promise>; + list(data: payouts.IPayoutListOptions, response?: IResponseFn>): Promise>; + list(options: HeaderOptions, response?: IResponseFn>): Promise>; + list(response?: IResponseFn>): Promise>; + + /** + * A previously created payout can be canceled if it has not yet been paid out. Funds will be refunded to your available balance, and the fees you were originally charged on the payout will be refunded. + * You may not cancel automatic Stripe payouts. + */ + cancel(payoutId: string, options: HeaderOptions, response?: IResponseFn): Promise; + cancel(payoutId: string, response?: IResponseFn): Promise; + } + class Plans extends StripeResource { /** * You can create plans easily via the plan management page of the Stripe dashboard. Plan creation is also diff --git a/types/stripe/stripe-tests.ts b/types/stripe/stripe-tests.ts index c4b291a7ed..7ac1763f2b 100644 --- a/types/stripe/stripe-tests.ts +++ b/types/stripe/stripe-tests.ts @@ -881,6 +881,118 @@ stripe.invoices.list({ customer: "cus_5rfJKDJkuxzh5Q", limit: 3 }).then(function +//#endregion + +//#region Payouts tests +// ################################################################################## +stripe.payouts.create({ + amount: 2000, + currency: "usd", + description: "The Payout", +}, function(err, payout) {}); +stripe.payouts.create({ + amount: 2000, + currency: "usd", + description: "The Payout", +}).then(function(payout) {}); +stripe.payouts.create({ + amount: 2000, + currency: "usd", + description: "The Payout", +}, { + stripe_account: "acct_abc12345678", +}, function(err, payout) {}); +stripe.payouts.create({ + amount: 2000, + currency: "usd", + description: "The Payout", +}, { + stripe_account: "acct_abc12345678", +}).then(function(payout) {}); + +stripe.payouts.retrieve( + "po_5rfJKDJkuxzh5Q", + function(err, payout) {} +); +stripe.payouts.retrieve("po_5rfJKDJkuxzh5Q").then( + function(payout) {} +); +stripe.payouts.retrieve( + "po_5rfJKDJkuxzh5Q", + { stripe_account: "acct_abc12345678" }, + function(err, payout) {} +); +stripe.payouts.retrieve( + "po_5rfJKDJkuxzh5Q", + { stripe_account: "acct_abc12345678" } +).then(function(payout) {}); + +stripe.payouts.update( + "po_5rfJKDJkuxzh5Q", + { metadata: { key: "value" } }, + function(err: Stripe.IStripeError, payout: Stripe.payouts.IPayout) {} +); +stripe.payouts.update( + "po_5rfJKDJkuxzh5Q", + { metadata: { key: "value" } }, +).then(function(payout) {}); +stripe.payouts.update( + "po_5rfJKDJkuxzh5Q", + { metadata: { key: "value" } }, + { stripe_account: "acct_abc12345678" }, + function(err, payout) {} +); +stripe.payouts.update( + "po_5rfJKDJkuxzh5Q", + { metadata: { key: "value" } }, + { stripe_account: "acct_abc12345678" }, +).then(function(payout) {}); + +stripe.payouts.list( + { limit: 100 }, + { stripe_account: "acct_abc12345678" }, + function(err, payouts) {} +); +stripe.payouts.list( + { limit: 100 }, + { stripe_account: "acct_abc12345678" }, +).then(function(payouts) {}); +stripe.payouts.list( + { limit: 100 }, + function(err, payouts) {} +); +stripe.payouts.list( + { limit: 100 }, +).then(function(payouts) {}); +stripe.payouts.list( + { stripe_account: "acct_abc12345678" }, + function(err, payouts) {} +); +stripe.payouts.list( + { stripe_account: "acct_abc12345678" }, +).then(function(payouts) {}); +stripe.payouts.list( + function(err, payouts) {} +); +stripe.payouts.list().then(function(payouts) {}); + +stripe.payouts.cancel( + "po_5rfJKDJkuxzh5Q", + { stripe_account: "acct_abc12345678" }, + function(err, payout) {} +); +stripe.payouts.cancel( + "po_5rfJKDJkuxzh5Q", + { stripe_account: "acct_abc12345678" }, +).then(function(payout) {}); +stripe.payouts.cancel( + "po_5rfJKDJkuxzh5Q", + function(err, payout) {} +); +stripe.payouts.cancel( + "po_5rfJKDJkuxzh5Q", +).then(function(payout) {}); + //#endregion //#region Plans tests From 81f249f1d3cef16964907954ed1a71540a98c760 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20van=20Br=C3=BCgge?= Date: Thu, 9 Nov 2017 13:12:32 +0100 Subject: [PATCH 105/495] Fix trailing whitespace --- types/ramda/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index 9a611459d2..a5e39f33f3 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -242,7 +242,7 @@ declare namespace R { * the supplied arguments. */ applySpec(obj: any): (...args: any[]) => T; - + /** * Takes a value and applies a function to it. * This function is also known as the thrush combinator. From 06646ec23d8c4c8f84402655690069200fa309fe Mon Sep 17 00:00:00 2001 From: karak Date: Thu, 9 Nov 2017 18:05:53 +0900 Subject: [PATCH 106/495] Fixed custom parsers feature. The return type of actions, so called "Reply", should be different from that of parsers. --- types/parsimmon/index.d.ts | 32 +++++++++++++++++++++++------- types/parsimmon/parsimmon-tests.ts | 7 ++++--- 2 files changed, 29 insertions(+), 10 deletions(-) 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)); From 2ebc8658390a61dd8900ecfe6287aa51f17dbb3a Mon Sep 17 00:00:00 2001 From: Mark Florian Date: Thu, 9 Nov 2017 14:42:35 +0000 Subject: [PATCH 107/495] Fix casing of UMD global --- types/pusher-js/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/pusher-js/index.d.ts b/types/pusher-js/index.d.ts index 30853434a1..383277f121 100644 --- a/types/pusher-js/index.d.ts +++ b/types/pusher-js/index.d.ts @@ -228,6 +228,6 @@ declare namespace pusher { declare var pusher: pusher.PusherStatic; -export as namespace pusher; +export as namespace Pusher; export = pusher; From 1cd172921d4bee322ee2d3220a2c179dfb03be22 Mon Sep 17 00:00:00 2001 From: Sven Kreiss Date: Thu, 9 Nov 2017 13:04:55 -0500 Subject: [PATCH 108/495] make docstring and type consistent --- types/googlemaps/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/googlemaps/index.d.ts b/types/googlemaps/index.d.ts index 66ddb31f5d..57d1c54278 100644 --- a/types/googlemaps/index.d.ts +++ b/types/googlemaps/index.d.ts @@ -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. From 5f773b1a470e06d9f19b36080f1e4796bb90acc0 Mon Sep 17 00:00:00 2001 From: Sven Kreiss Date: Thu, 9 Nov 2017 13:17:14 -0500 Subject: [PATCH 109/495] increase version number --- types/googlemaps/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/googlemaps/index.d.ts b/types/googlemaps/index.d.ts index 57d1c54278..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 /* From 0c3841a9d818b5741dec197c92e5b15e74a39c5b Mon Sep 17 00:00:00 2001 From: Kaelig Deloumeau-Prigent Date: Thu, 9 Nov 2017 13:22:19 -0500 Subject: [PATCH 110/495] React v16: Add crossOrigin html attribute to the link element --- types/react/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 9134406735..6bddb6c379 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -2795,6 +2795,7 @@ declare namespace React { sizes?: string; type?: string; as?: string; + crossOrigin?: string; } interface MapHTMLAttributes extends HTMLAttributes { From 65feecd9a126f0f01ee0a98fbafde6ff439c16d0 Mon Sep 17 00:00:00 2001 From: Kaelig Deloumeau-Prigent Date: Thu, 9 Nov 2017 13:23:37 -0500 Subject: [PATCH 111/495] React v15: Add crossOrigin html attribute to the link element --- types/react/v15/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/react/v15/index.d.ts b/types/react/v15/index.d.ts index 19cd290c7b..3e17e0a9e6 100644 --- a/types/react/v15/index.d.ts +++ b/types/react/v15/index.d.ts @@ -2721,6 +2721,7 @@ declare namespace React { interface LinkHTMLAttributes extends HTMLAttributes { as?: string; + crossOrigin?: string; href?: string; hrefLang?: string; integrity?: string; From 759b981de1d240758692bb50570c81056786d6e2 Mon Sep 17 00:00:00 2001 From: Kaelig Deloumeau-Prigent Date: Thu, 9 Nov 2017 13:26:45 -0500 Subject: [PATCH 112/495] Alphabetically order props in LinkHTMLAttributes --- types/react/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 6bddb6c379..5d25f7eb7f 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -2787,6 +2787,8 @@ declare namespace React { } interface LinkHTMLAttributes extends HTMLAttributes { + as?: string; + crossOrigin?: string; href?: string; hrefLang?: string; integrity?: string; @@ -2794,8 +2796,6 @@ declare namespace React { rel?: string; sizes?: string; type?: string; - as?: string; - crossOrigin?: string; } interface MapHTMLAttributes extends HTMLAttributes { From 215ad5cc183530bc541b9135468334f7719e6786 Mon Sep 17 00:00:00 2001 From: allen1314 <83970162@qq.com> Date: Fri, 10 Nov 2017 07:12:17 +0800 Subject: [PATCH 113/495] add ability to control the piechart size and innerSize for each series items --- types/highcharts/index.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/types/highcharts/index.d.ts b/types/highcharts/index.d.ts index 3ce85ed9e2..f7f3759432 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -5266,6 +5266,9 @@ declare namespace Highcharts { * interfaces (AreaChartSeriesOptions, LineChartSeriesOptions, etc.) */ interface IndividualSeriesOptions { + size?: number | string; + innerSize?: number | string; + type?: string; /** * The main color or the series. In line type series it applies to the line and the point markers unless otherwise From f2b3ff0806950bc198b420139b26c715aef9a12a Mon Sep 17 00:00:00 2001 From: Joseph Roque Date: Thu, 9 Nov 2017 21:06:36 -0500 Subject: [PATCH 114/495] [react-native-fs] Change utime to mtime, make mtime optional --- types/react-native-fs/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/react-native-fs/index.d.ts b/types/react-native-fs/index.d.ts index 8c7945010d..48a7fb6c70 100644 --- a/types/react-native-fs/index.d.ts +++ b/types/react-native-fs/index.d.ts @@ -11,7 +11,7 @@ export interface ReadDirItem { // The creation date of the file (iOS only) ctime: Date | undefined; // The last modified date of the file - mtime: Date; + mtime: Date | undefined; // The name of the item name: string; // The absolute path to the item @@ -36,7 +36,7 @@ export interface StatResult { // Created date ctime: number; // Updated date - utime: number; + mtime: number; // Is the file just a file? isFile(): boolean; // Is the file a directory? From fc8c01431b6164e96b9d38d6d14996946e72a50a Mon Sep 17 00:00:00 2001 From: Adam Date: Thu, 9 Nov 2017 18:39:55 -0800 Subject: [PATCH 115/495] Fix typing for magicline_tabuList Documentation for CKEDITOR.config incorrectly lists magicline_tabuList as type Number (the type assigned in this file was likely based on the documentation). However, magicline source code expects a string array [see source here](https://docs.ckeditor.com/ckeditor4/docs/source/plugin60.html#CKEDITOR-config-cfg-magicline_tabuList). --- types/ckeditor/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/ckeditor/index.d.ts b/types/ckeditor/index.d.ts index 150bc7e7a6..f26a08a725 100644 --- a/types/ckeditor/index.d.ts +++ b/types/ckeditor/index.d.ts @@ -727,7 +727,7 @@ declare namespace CKEDITOR { magicline_holdDistance?: number; magicline_keystrokeNext?: number; magicline_keystrokePrevious?: number; - magicline_tabuList?: number; + magicline_tabuList?: string[]; magicline_triggerOffset?: number; mathJaxLib?: string; menu_groups?: string; From 74e9d5594a459c2622285bcdd51128e006735bc9 Mon Sep 17 00:00:00 2001 From: Konrad Mattheis Date: Fri, 10 Nov 2017 11:08:35 +0100 Subject: [PATCH 116/495] move on / emit out of engine-api Signed-off-by: Konrad Mattheis --- types/qlik-engineapi/index.d.ts | 36 ++++++------------- types/qlik-visualizationextensions/index.d.ts | 20 +++++++++++ 2 files changed, 30 insertions(+), 26 deletions(-) diff --git a/types/qlik-engineapi/index.d.ts b/types/qlik-engineapi/index.d.ts index 19c9274cae..17f7a7892b 100644 --- a/types/qlik-engineapi/index.d.ts +++ b/types/qlik-engineapi/index.d.ts @@ -5070,32 +5070,11 @@ declare namespace EngineAPI { qAttrDims?: INxAttributeDimValues; } - /** - * ImplementOn... - */ - interface IImplementOn { - /** - * register a function for events - * @param event - function called if this event occures - * @param func - function that is called - */ - on(event: "changed" | "closed", func: () => void): void; - - /** - * manual emit an events - * @param event - event that occures - */ - emit(event: "changed" | "closed"): void; - - // ? not in Docu - id: string; - } - /** * This class describes all the methods that apply at generic object level. * The handle member in the JSON request for all methods listed in this section is the handle of the generic object. */ - interface IGenericObject extends IImplementOn { + interface IGenericObject extends enigmaJS.IGeneratedAPI { /** * app describes all the methods that apply at app level. */ @@ -6010,7 +5989,7 @@ declare namespace EngineAPI { interface IGenericDerivedFieldProperties extends IGenericProperties { } - interface IGenericDerivedFields extends IImplementOn { + interface IGenericDerivedFields extends enigmaJS.IGeneratedAPI { /** * Shows the properties of an object. * Returns the identifier and the definition of the derived field. @@ -6054,7 +6033,7 @@ declare namespace EngineAPI { * This class describes all the methods that apply at measure level. * The handle member in the JSON request for all methods listed in this section is the handle of the measure. */ - interface IGenericMeasure extends IImplementOn { + interface IGenericMeasure extends enigmaJS.IGeneratedAPI { /** * Applies a patch to the properties of an object. Allows an update to some of the properties. * @@ -6122,7 +6101,7 @@ declare namespace EngineAPI { * This class describes all the methods that apply at generic variable level. * The handle member in the JSON request for all methods listed in this section is the handle of the generic variable. */ - interface IGenericVariable extends IImplementOn { + interface IGenericVariable extends enigmaJS.IGeneratedAPI { /** * Applies a patch to the properties of a variable. Allows an update to some of the properties. * @@ -6245,7 +6224,7 @@ declare namespace EngineAPI { * * The handle member in the JSON request for all methods listed in this section is the handle of the variable. */ - interface IVariable extends IImplementOn { + interface IVariable extends enigmaJS.IGeneratedAPI { /** * Sets the value of a dual variable overriding any input constraints. * @@ -9714,3 +9693,8 @@ declare namespace EngineAPI { } } //#endregion + +declare namespace enigmaJS { + interface IGeneratedAPI { + } +} diff --git a/types/qlik-visualizationextensions/index.d.ts b/types/qlik-visualizationextensions/index.d.ts index 7e6f3384b4..5d10ff9bcb 100644 --- a/types/qlik-visualizationextensions/index.d.ts +++ b/types/qlik-visualizationextensions/index.d.ts @@ -2565,3 +2565,23 @@ declare module "qvangular" { const e: IQVAngular; export = e; } + +declare namespace enigmaJS { + interface IGeneratedAPI { + /** + * register a function for events + * @param event - function called if this event occures + * @param func - function that is called + */ + on(event: "changed" | "closed", func: () => void): void; + + /** + * manual emit an events + * @param event - event that occures + */ + emit(event: "changed" | "closed"): void; + + // ? not in Docu + id: string; + } +} From 873eb12c02e9a96882da6598a75ae58d6ce386db Mon Sep 17 00:00:00 2001 From: Oliver Joseph Ash Date: Fri, 10 Nov 2017 10:51:55 +0000 Subject: [PATCH 117/495] react-redux: add generic for state parameter --- types/react-redux/index.d.ts | 50 ++++++++++++------------- types/react-redux/react-redux-tests.tsx | 24 ++++++------ 2 files changed, 37 insertions(+), 37 deletions(-) diff --git a/types/react-redux/index.d.ts b/types/react-redux/index.d.ts index 38c880ba3b..022b61bff0 100644 --- a/types/react-redux/index.d.ts +++ b/types/react-redux/index.d.ts @@ -78,67 +78,67 @@ export type InferableComponentEnhancer = export interface Connect { (): InferableComponentEnhancer>; - ( - mapStateToProps: MapStateToPropsParam + ( + mapStateToProps: MapStateToPropsParam ): InferableComponentEnhancerWithProps, TOwnProps>; - ( + ( mapStateToProps: null | undefined, mapDispatchToProps: MapDispatchToPropsParam ): InferableComponentEnhancerWithProps; - ( - mapStateToProps: MapStateToPropsParam, + ( + mapStateToProps: MapStateToPropsParam, mapDispatchToProps: MapDispatchToPropsParam ): InferableComponentEnhancerWithProps; - ( - mapStateToProps: MapStateToPropsParam, + ( + mapStateToProps: MapStateToPropsParam, mapDispatchToProps: null | undefined, mergeProps: MergeProps, ): InferableComponentEnhancerWithProps; - ( + ( mapStateToProps: null | undefined, mapDispatchToProps: MapDispatchToPropsParam, mergeProps: MergeProps, ): InferableComponentEnhancerWithProps; - ( + ( mapStateToProps: null | undefined, mapDispatchToProps: null | undefined, mergeProps: MergeProps, ): InferableComponentEnhancerWithProps; - ( - mapStateToProps: MapStateToPropsParam, + ( + mapStateToProps: MapStateToPropsParam, mapDispatchToProps: MapDispatchToPropsParam, mergeProps: MergeProps, ): InferableComponentEnhancerWithProps; - ( - mapStateToProps: MapStateToPropsParam, + ( + mapStateToProps: MapStateToPropsParam, mapDispatchToProps: null | undefined, mergeProps: null | undefined, options: Options ): InferableComponentEnhancerWithProps & TStateProps, TOwnProps>; - ( + ( mapStateToProps: null | undefined, mapDispatchToProps: MapDispatchToPropsParam, mergeProps: null | undefined, options: Options ): InferableComponentEnhancerWithProps; - ( - mapStateToProps: MapStateToPropsParam, + ( + mapStateToProps: MapStateToPropsParam, mapDispatchToProps: MapDispatchToPropsParam, mergeProps: null | undefined, options: Options ): InferableComponentEnhancerWithProps; - ( - mapStateToProps: MapStateToPropsParam, + ( + mapStateToProps: MapStateToPropsParam, mapDispatchToProps: MapDispatchToPropsParam, mergeProps: MergeProps, options: Options @@ -150,15 +150,15 @@ export interface Connect { */ export declare const connect: Connect; -interface MapStateToProps { - (state: any, ownProps: TOwnProps): TStateProps; +interface MapStateToProps { + (state: State, ownProps: TOwnProps): TStateProps; } -interface MapStateToPropsFactory { - (initialState: any, ownProps: TOwnProps): MapStateToProps; +interface MapStateToPropsFactory { + (initialState: State, ownProps: TOwnProps): MapStateToProps; } -type MapStateToPropsParam = MapStateToPropsFactory | MapStateToProps | null | undefined; +type MapStateToPropsParam = MapStateToPropsFactory | MapStateToProps | null | undefined; interface MapDispatchToPropsFunction { (dispatch: Dispatch, ownProps: TOwnProps): TDispatchProps; @@ -177,7 +177,7 @@ interface MergeProps { (stateProps: TStateProps, dispatchProps: TDispatchProps, ownProps: TOwnProps): TMergedProps; } -interface Options extends ConnectOptions { +interface Options extends ConnectOptions { /** * If true, implements shouldComponentUpdate and shallowly compares the result of mergeProps, * preventing unnecessary updates, assuming that the component is a “pure” component @@ -191,7 +191,7 @@ interface Options extends C * When pure, compares incoming store state to its previous value. * @default strictEqual */ - areStatesEqual?: (nextState: any, prevState: any) => boolean; + areStatesEqual?: (nextState: State, prevState: State) => boolean; /** * When pure, compares incoming props to its previous value. diff --git a/types/react-redux/react-redux-tests.tsx b/types/react-redux/react-redux-tests.tsx index e726bf104f..a95d9a6074 100644 --- a/types/react-redux/react-redux-tests.tsx +++ b/types/react-redux/react-redux-tests.tsx @@ -316,12 +316,12 @@ interface ICounterDispatchProps { onIncrement: () => void } // with higher order functions -connect( +connect( () => mapStateToProps, () => mapDispatchToProps )(Counter); // with higher order functions using parameters -connect( +connect( (initialState: CounterState, ownProps) => mapStateToProps, (dispatch: Dispatch, ownProps) => mapDispatchToProps )(Counter); @@ -330,12 +330,12 @@ connect( () => mapStateToProps )(Counter); // wrap only one argument -connect( +connect( mapStateToProps, () => mapDispatchToProps )(Counter); // with extra arguments -connect( +connect( () => mapStateToProps, () => mapDispatchToProps, (s: ICounterStateProps, d: ICounterDispatchProps) => @@ -621,7 +621,7 @@ namespace TestTOwnPropsInference { const ConnectedWithoutOwnProps = connect(mapStateToPropsWithoutOwnProps)(OwnPropsComponent); const ConnectedWithOwnProps = connect(mapStateToPropsWithOwnProps)(OwnPropsComponent); - const ConnectedWithTypeHint = connect(mapStateToPropsWithoutOwnProps)(OwnPropsComponent); + const ConnectedWithTypeHint = connect(mapStateToPropsWithoutOwnProps)(OwnPropsComponent); // This should not compile, which is good. // React.createElement(ConnectedWithoutOwnProps, { anything: 'goes!' }); @@ -652,7 +652,7 @@ namespace TestTOwnPropsInference { type PickedOwnProps = Pick type PickedStateProps = Pick - const mapStateToPropsForPicked: MapStateToProps = (state: any): PickedStateProps => { + const mapStateToPropsForPicked: MapStateToProps = (state: any): PickedStateProps => { return { state: "string" } } const ConnectedWithPickedOwnProps = connect(mapStateToPropsForPicked)(AllPropsComponent); @@ -691,7 +691,7 @@ namespace TestMergedPropsInference { return { dispatch: 'string' }; } - const ConnectedWithOwnAndState: React.ComponentClass = connect( + const ConnectedWithOwnAndState: React.ComponentClass = connect( mapStateToProps, undefined, (stateProps: StateProps) => ({ @@ -699,7 +699,7 @@ namespace TestMergedPropsInference { }), )(MergedPropsComponent); - const ConnectedWithOwnAndDispatch: React.ComponentClass = connect( + const ConnectedWithOwnAndDispatch: React.ComponentClass = connect( undefined, mapDispatchToProps, (stateProps: undefined, dispatchProps: DispatchProps) => ({ @@ -707,7 +707,7 @@ namespace TestMergedPropsInference { }), )(MergedPropsComponent); - const ConnectedWithOwn: React.ComponentClass = connect( + const ConnectedWithOwn: React.ComponentClass = connect( undefined, undefined, () => ({ @@ -733,7 +733,7 @@ namespace Issue16652 { }; }; - const ConnectedCommentList = connect(mapStateToProps)( + const ConnectedCommentList = connect(mapStateToProps)( CommentList ); @@ -878,8 +878,8 @@ namespace TestCreateProvider { interface AProps { a: number }; const A = (props: AProps) => (

A is {props.a}

); - const A1 = connect(state => state)(A); - const A2 = myStoreConnect(state => state)(A); + const A1 = connect(state => state)(A); + const A2 = myStoreConnect(state => state)(A); const Combined = () => ( From 8a10f48cbe561f3f51a836e538a8b4556686778c Mon Sep 17 00:00:00 2001 From: Piotr Roszatycki Date: Fri, 10 Nov 2017 14:19:22 +0100 Subject: [PATCH 118/495] SMTPError.responseCode is number --- types/nodemailer/lib/smtp-connection.d.ts | 2 +- types/nodemailer/nodemailer-tests.ts | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/types/nodemailer/lib/smtp-connection.d.ts b/types/nodemailer/lib/smtp-connection.d.ts index 49b1adef8e..a02defb461 100644 --- a/types/nodemailer/lib/smtp-connection.d.ts +++ b/types/nodemailer/lib/smtp-connection.d.ts @@ -76,7 +76,7 @@ declare namespace SMTPConnection { /** the last response received from the server (if the error is caused by an error response from the server) */ response: string; /** the numeric response code of the response string (if available) */ - responseCode: string; + responseCode: number; } interface SentMessageInfo { diff --git a/types/nodemailer/nodemailer-tests.ts b/types/nodemailer/nodemailer-tests.ts index 6bf4935e0a..ea7bb3cc5b 100644 --- a/types/nodemailer/nodemailer-tests.ts +++ b/types/nodemailer/nodemailer-tests.ts @@ -1035,7 +1035,12 @@ namespace smtp_connection_test { connection.login({ user: 'user', pass: 'pass' }, (err) => { if (err) throw err; connection.send({ from: 'a@example.com', to: 'b@example.net' }, 'message', (err, info) => { - if (err) throw err; + if (err) { + const code: string = err.code; + const response: string = err.response; + const responseCode: number = err.responseCode; + throw err; + } connection.reset(() => { if (err) throw err; connection.quit(); From 2570679b2bf029c303f6ff4b0ac7dd8d11bc1a41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Steve=20Fr=C3=A9cinaux?= Date: Fri, 10 Nov 2017 14:23:32 +0100 Subject: [PATCH 119/495] sip.js: fix typing of SIP.NameAddrHeader According to sip.js source code, the "uri" parameter and member are never a string, they are always SIP.URI instances. https://github.com/onsip/SIP.js/blob/master/src/NameAddrHeader.js#L22 --- types/sip.js/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/sip.js/index.d.ts b/types/sip.js/index.d.ts index ca679979f1..2513f7f585 100644 --- a/types/sip.js/index.d.ts +++ b/types/sip.js/index.d.ts @@ -336,10 +336,10 @@ export interface IncomingMessage extends Request { /* Header */ export class NameAddrHeader { - uri: string | URI; + uri: URI; displayName: string; - constructor(uri: string | sipjs.URI, displayName: string, parameters: Array<{ key: string, value: string }>); + constructor(uri: sipjs.URI, displayName: string, parameters: Array<{ key: string, value: string }>); static parse(name_addr_header: string): sipjs.NameAddrHeader; setParam(key: string, value?: string): void; From fb8bac85f5d4fe1bbd38df4f53637a87444674f2 Mon Sep 17 00:00:00 2001 From: Piotr Roszatycki Date: Fri, 10 Nov 2017 14:37:25 +0100 Subject: [PATCH 120/495] SMTPError is a rather an interface than real class --- types/nodemailer/lib/smtp-connection.d.ts | 10 ++++++---- types/nodemailer/nodemailer-tests.ts | 7 ++++--- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/types/nodemailer/lib/smtp-connection.d.ts b/types/nodemailer/lib/smtp-connection.d.ts index a02defb461..1215409b46 100644 --- a/types/nodemailer/lib/smtp-connection.d.ts +++ b/types/nodemailer/lib/smtp-connection.d.ts @@ -70,13 +70,15 @@ declare namespace SMTPConnection { dsn?: DSNOptions; } - class SMTPError extends Error { + interface SMTPError extends NodeJS.ErrnoException { /** string code identifying the error, for example ‘EAUTH’ is returned when authentication */ - code: string; + code?: string; /** the last response received from the server (if the error is caused by an error response from the server) */ - response: string; + response?: string; /** the numeric response code of the response string (if available) */ - responseCode: number; + responseCode?: number; + /** command which provoked an error */ + command?: string; } interface SentMessageInfo { diff --git a/types/nodemailer/nodemailer-tests.ts b/types/nodemailer/nodemailer-tests.ts index ea7bb3cc5b..00238d2d5c 100644 --- a/types/nodemailer/nodemailer-tests.ts +++ b/types/nodemailer/nodemailer-tests.ts @@ -1036,9 +1036,10 @@ namespace smtp_connection_test { if (err) throw err; connection.send({ from: 'a@example.com', to: 'b@example.net' }, 'message', (err, info) => { if (err) { - const code: string = err.code; - const response: string = err.response; - const responseCode: number = err.responseCode; + const code: string = err.code || '???'; + const response: string = err.response || '???'; + const responseCode: number = err.responseCode || 0; + const command: string = err.command || '???'; throw err; } connection.reset(() => { From 632e081d9b55c58a8bd61d499e9fc3bc9d1d3f3d Mon Sep 17 00:00:00 2001 From: Thomas Chandelle Date: Fri, 10 Nov 2017 14:53:59 +0100 Subject: [PATCH 121/495] Fixes tooltip callbacks, set return and data type http://www.chartjs.org/docs/latest/configuration/tooltip.html#tooltip-callbacks All functions are called with the same arguments: a tooltip item and the data object passed to the chart. All functions must return either a string or an array of strings --- types/chart.js/index.d.ts | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index ef9e8b0675..54e9f4ddda 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -115,17 +115,17 @@ declare namespace Chart { } interface ChartTooltipCallback { - beforeTitle?(item?: ChartTooltipItem[], data?: any): void; - title?(item?: ChartTooltipItem[], data?: any): void; - afterTitle?(item?: ChartTooltipItem[], data?: any): void; - beforeBody?(item?: ChartTooltipItem[], data?: any): void; - beforeLabel?(tooltipItem?: ChartTooltipItem, data?: any): void; - label?(tooltipItem?: ChartTooltipItem, data?: any): void; - afterLabel?(tooltipItem?: ChartTooltipItem, data?: any): void; - afterBody?(item?: ChartTooltipItem[], data?: any): void; - beforeFooter?(item?: ChartTooltipItem[], data?: any): void; - footer?(item?: ChartTooltipItem[], data?: any): void; - afterFooter?(item?: ChartTooltipItem[], data?: any): void; + beforeTitle?(item?: ChartTooltipItem[], data?: ChartData): string | string[]; + title?(item?: ChartTooltipItem[], data?: ChartData): string | string[]; + afterTitle?(item?: ChartTooltipItem[], data?: ChartData): string | string[]; + beforeBody?(item?: ChartTooltipItem[], data?: ChartData): string | string[]; + beforeLabel?(tooltipItem?: ChartTooltipItem, data?: ChartData): string | string[]; + label?(tooltipItem?: ChartTooltipItem, data?: ChartData): string | string[]; + afterLabel?(tooltipItem?: ChartTooltipItem, data?: ChartData): string | string[]; + afterBody?(item?: ChartTooltipItem[], data?: ChartData): string | string[]; + beforeFooter?(item?: ChartTooltipItem[], data?: ChartData): string | string[]; + footer?(item?: ChartTooltipItem[], data?: ChartData): string | string[]; + afterFooter?(item?: ChartTooltipItem[], data?: ChartData): string | string[]; } interface ChartAnimationParameter { From f8d259f70be796b8d35791f736f456b66e9fdd50 Mon Sep 17 00:00:00 2001 From: Miloslav Nenadal Date: Fri, 10 Nov 2017 14:59:14 +0100 Subject: [PATCH 122/495] [express-cluster]: Add types --- .../express-cluster/express-cluster-tests.ts | 6 +++++ types/express-cluster/index.d.ts | 26 +++++++++++++++++++ types/express-cluster/tsconfig.json | 22 ++++++++++++++++ types/express-cluster/tslint.json | 1 + 4 files changed, 55 insertions(+) create mode 100644 types/express-cluster/express-cluster-tests.ts create mode 100644 types/express-cluster/index.d.ts create mode 100644 types/express-cluster/tsconfig.json create mode 100644 types/express-cluster/tslint.json diff --git a/types/express-cluster/express-cluster-tests.ts b/types/express-cluster/express-cluster-tests.ts new file mode 100644 index 0000000000..1a530a01c2 --- /dev/null +++ b/types/express-cluster/express-cluster-tests.ts @@ -0,0 +1,6 @@ +import * as cluster from '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..a89aafc724 --- /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 * as cluster from '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/express-cluster/tsconfig.json b/types/express-cluster/tsconfig.json new file mode 100644 index 0000000000..26563cb1b6 --- /dev/null +++ b/types/express-cluster/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "express-cluster-tests.ts" + ] +} 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" } From c3b8d5b4cf2c3de51a9a43805c0d5f474de96671 Mon Sep 17 00:00:00 2001 From: karak Date: Sat, 11 Nov 2017 00:59:21 +0900 Subject: [PATCH 123/495] Fixed return types of on(), off(). The methods on, off returns this, Benchmark or Benchmark.Suite respectively. --- types/benchmark/benchmark-tests.ts | 21 +++++++++++++++++++++ types/benchmark/index.d.ts | 8 ++++---- 2 files changed, 25 insertions(+), 4 deletions(-) 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; From 000a9bfcda01e18892b4b7d52bbf1b25a4dd394a Mon Sep 17 00:00:00 2001 From: Oliver Joseph Ash Date: Fri, 10 Nov 2017 20:50:34 +0000 Subject: [PATCH 124/495] Move state generic to last position and improve tests --- types/react-redux/index.d.ts | 44 ++++++++++++------------- types/react-redux/react-redux-tests.tsx | 26 +++++++-------- 2 files changed, 35 insertions(+), 35 deletions(-) diff --git a/types/react-redux/index.d.ts b/types/react-redux/index.d.ts index 022b61bff0..8e2556ec6c 100644 --- a/types/react-redux/index.d.ts +++ b/types/react-redux/index.d.ts @@ -78,67 +78,67 @@ export type InferableComponentEnhancer = export interface Connect { (): InferableComponentEnhancer>; - ( - mapStateToProps: MapStateToPropsParam + ( + mapStateToProps: MapStateToPropsParam ): InferableComponentEnhancerWithProps, TOwnProps>; - ( + ( mapStateToProps: null | undefined, mapDispatchToProps: MapDispatchToPropsParam ): InferableComponentEnhancerWithProps; - ( - mapStateToProps: MapStateToPropsParam, + ( + mapStateToProps: MapStateToPropsParam, mapDispatchToProps: MapDispatchToPropsParam ): InferableComponentEnhancerWithProps; - ( - mapStateToProps: MapStateToPropsParam, + ( + mapStateToProps: MapStateToPropsParam, mapDispatchToProps: null | undefined, mergeProps: MergeProps, ): InferableComponentEnhancerWithProps; - ( + ( mapStateToProps: null | undefined, mapDispatchToProps: MapDispatchToPropsParam, mergeProps: MergeProps, ): InferableComponentEnhancerWithProps; - ( + ( mapStateToProps: null | undefined, mapDispatchToProps: null | undefined, mergeProps: MergeProps, ): InferableComponentEnhancerWithProps; - ( - mapStateToProps: MapStateToPropsParam, + ( + mapStateToProps: MapStateToPropsParam, mapDispatchToProps: MapDispatchToPropsParam, mergeProps: MergeProps, ): InferableComponentEnhancerWithProps; - ( - mapStateToProps: MapStateToPropsParam, + ( + mapStateToProps: MapStateToPropsParam, mapDispatchToProps: null | undefined, mergeProps: null | undefined, options: Options ): InferableComponentEnhancerWithProps & TStateProps, TOwnProps>; - ( + ( mapStateToProps: null | undefined, mapDispatchToProps: MapDispatchToPropsParam, mergeProps: null | undefined, options: Options ): InferableComponentEnhancerWithProps; - ( - mapStateToProps: MapStateToPropsParam, + ( + mapStateToProps: MapStateToPropsParam, mapDispatchToProps: MapDispatchToPropsParam, mergeProps: null | undefined, options: Options ): InferableComponentEnhancerWithProps; - ( - mapStateToProps: MapStateToPropsParam, + ( + mapStateToProps: MapStateToPropsParam, mapDispatchToProps: MapDispatchToPropsParam, mergeProps: MergeProps, options: Options @@ -150,15 +150,15 @@ export interface Connect { */ export declare const connect: Connect; -interface MapStateToProps { +interface MapStateToProps { (state: State, ownProps: TOwnProps): TStateProps; } -interface MapStateToPropsFactory { - (initialState: State, ownProps: TOwnProps): MapStateToProps; +interface MapStateToPropsFactory { + (initialState: State, ownProps: TOwnProps): MapStateToProps; } -type MapStateToPropsParam = MapStateToPropsFactory | MapStateToProps | null | undefined; +type MapStateToPropsParam = MapStateToPropsFactory | MapStateToProps | null | undefined; interface MapDispatchToPropsFunction { (dispatch: Dispatch, ownProps: TOwnProps): TDispatchProps; diff --git a/types/react-redux/react-redux-tests.tsx b/types/react-redux/react-redux-tests.tsx index a95d9a6074..af77473473 100644 --- a/types/react-redux/react-redux-tests.tsx +++ b/types/react-redux/react-redux-tests.tsx @@ -316,26 +316,26 @@ interface ICounterDispatchProps { onIncrement: () => void } // with higher order functions -connect( +connect( () => mapStateToProps, () => mapDispatchToProps )(Counter); // with higher order functions using parameters -connect( +connect( (initialState: CounterState, ownProps) => mapStateToProps, (dispatch: Dispatch, ownProps) => mapDispatchToProps )(Counter); // only first argument -connect( +connect( () => mapStateToProps )(Counter); // wrap only one argument -connect( +connect( mapStateToProps, () => mapDispatchToProps )(Counter); // with extra arguments -connect( +connect( () => mapStateToProps, () => mapDispatchToProps, (s: ICounterStateProps, d: ICounterDispatchProps) => @@ -621,7 +621,7 @@ namespace TestTOwnPropsInference { const ConnectedWithoutOwnProps = connect(mapStateToPropsWithoutOwnProps)(OwnPropsComponent); const ConnectedWithOwnProps = connect(mapStateToPropsWithOwnProps)(OwnPropsComponent); - const ConnectedWithTypeHint = connect(mapStateToPropsWithoutOwnProps)(OwnPropsComponent); + const ConnectedWithTypeHint = connect(mapStateToPropsWithoutOwnProps)(OwnPropsComponent); // This should not compile, which is good. // React.createElement(ConnectedWithoutOwnProps, { anything: 'goes!' }); @@ -652,7 +652,7 @@ namespace TestTOwnPropsInference { type PickedOwnProps = Pick type PickedStateProps = Pick - const mapStateToPropsForPicked: MapStateToProps = (state: any): PickedStateProps => { + const mapStateToPropsForPicked: MapStateToProps = (state: any): PickedStateProps => { return { state: "string" } } const ConnectedWithPickedOwnProps = connect(mapStateToPropsForPicked)(AllPropsComponent); @@ -691,7 +691,7 @@ namespace TestMergedPropsInference { return { dispatch: 'string' }; } - const ConnectedWithOwnAndState: React.ComponentClass = connect( + const ConnectedWithOwnAndState: React.ComponentClass = connect( mapStateToProps, undefined, (stateProps: StateProps) => ({ @@ -699,7 +699,7 @@ namespace TestMergedPropsInference { }), )(MergedPropsComponent); - const ConnectedWithOwnAndDispatch: React.ComponentClass = connect( + const ConnectedWithOwnAndDispatch: React.ComponentClass = connect( undefined, mapDispatchToProps, (stateProps: undefined, dispatchProps: DispatchProps) => ({ @@ -707,7 +707,7 @@ namespace TestMergedPropsInference { }), )(MergedPropsComponent); - const ConnectedWithOwn: React.ComponentClass = connect( + const ConnectedWithOwn: React.ComponentClass = connect( undefined, undefined, () => ({ @@ -733,7 +733,7 @@ namespace Issue16652 { }; }; - const ConnectedCommentList = connect(mapStateToProps)( + const ConnectedCommentList = connect(mapStateToProps)( CommentList ); @@ -878,8 +878,8 @@ namespace TestCreateProvider { interface AProps { a: number }; const A = (props: AProps) => (

A is {props.a}

); - const A1 = connect(state => state)(A); - const A2 = myStoreConnect(state => state)(A); + const A1 = connect(state => state)(A); + const A2 = myStoreConnect(state => state)(A); const Combined = () => ( From 112b361c313dbd4b754eaf08473668082b85a7e6 Mon Sep 17 00:00:00 2001 From: Steven Date: Fri, 10 Nov 2017 16:31:07 -0500 Subject: [PATCH 125/495] Add width property on ColHTMLAttributes in react --- types/react/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 9134406735..ad5ada5e0a 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -2656,6 +2656,7 @@ declare namespace React { interface ColHTMLAttributes extends HTMLAttributes { span?: number; + width?: number | string; } interface ColgroupHTMLAttributes extends HTMLAttributes { From db5e11dc792e6a4842428c0e86e39745768039b7 Mon Sep 17 00:00:00 2001 From: Erik Vullings Date: Fri, 10 Nov 2017 23:05:50 +0100 Subject: [PATCH 126/495] Added two missing properties in OptionDefinition Missing options: description and typeLabel. Also changed documentation style (using 'Document-this') and changed version from 4.0.6 to 4.0.7. --- types/command-line-args/index.d.ts | 131 +++++++++++++++++++---------- 1 file changed, 88 insertions(+), 43 deletions(-) diff --git a/types/command-line-args/index.d.ts b/types/command-line-args/index.d.ts index 442ee5cb93..f5545f6514 100644 --- a/types/command-line-args/index.d.ts +++ b/types/command-line-args/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for command-line-args 4.0.6 +// Type definitions for command-line-args 4.0.7 // Project: https://github.com/75lb/command-line-args // Definitions by: CzBuCHi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -25,50 +25,95 @@ */ declare function commandLineArgs(optionDefinitions: commandLineArgs.OptionDefinition[], options?: commandLineArgs.Options): any; -declare module commandLineArgs { +declare module commandLineArgs { - export interface OptionDefinition { - /** - * The only required definition property is name, the value of each option will be either a Boolean or string. - */ - name: string, - /** - * The type value is a setter function (you receive the output from this), enabling you to be specific about the type and value received. - */ - type?: (arg: string) => any, - /** - * getopt-style short option names. Can be any single character (unicode included) except a digit or hypen. - */ - alias?: string, - /** - * Set this flag if the option takes a list of values. You will receive an array of values, each passed through the type function (if specified). - */ - multiple?: boolean, - /** - * Any unclaimed command-line args will be set on this option. This flag is typically set on the most commonly-used option to make for more concise usage (i.e. $ myapp *.js instead of $ myapp --files *.js). - */ - defaultOption?: boolean, - /** - * An initial value for the option. - */ - defaultValue?: any, - /** - * When your app has a large amount of options it makes sense to organise them in groups. - * There are two automatic groups: _all (contains all options) and _none (contains options without a group specified in their definition). - */ - group?: string | string[], - } + export interface OptionDefinition { + /** + * The only required definition property is name, the value of each option will be either a Boolean or string. + * + * @type {string} + * @memberof OptionDefinition + */ + name: string, + /** + * The type value is a setter function (you receive the output from this), + * enabling you to be specific about the type and value received. + * + * @memberof OptionDefinition + */ + type?: (arg: string) => any, + /** + * getopt-style short option names. Can be any single character (unicode included) except a digit or hypen. + * + * @type {string} + * @memberof OptionDefinition + */ + alias?: string, + /** + * Set this flag if the option takes a list of values. You will receive an array of values, each passed + * through the type function (if specified). + * + * @type {boolean} + * @memberof OptionDefinition + */ + multiple?: boolean, + /** + * Any unclaimed command-line args will be set on this option. This flag is typically set on + * the most commonly-used option to make for more concise usage + * (i.e. $ myapp *.js instead of $ myapp --files *.js). + * + * @type {boolean} + * @memberof OptionDefinition + */ + defaultOption?: boolean, + /** + * An initial value for the option. + * + * @type {*} + * @memberof OptionDefinition + */ + defaultValue?: any, + /** + * When your app has a large amount of options it makes sense to organise them in groups. + * There are two automatic groups: _all (contains all options) and _none (contains options + * without a group specified in their definition). + * + * @type {(string | string[])} + * @memberof OptionDefinition + */ + group?: string | string[], + /** + * Describes the option. + * + * @type {string} + * @memberof OptionDefinition + */ + description?: string, + /** + * A label for the type, e.g. . + * + * @type {string} + * @memberof OptionDefinition + */ + typeLabel?: string; + } - export interface Options { - /** - * An array of strings, which if passed will be parsed instead of `process.argv`. - */ - argv?: string[]; - /** - * If `true`, an array of unknown arguments is returned in the `_unknown` property of the output. - */ - partial?: boolean; - } + export interface Options { + /** + * An array of strings, which if passed will be parsed instead of `process.argv`. + * + * @type {string[]} + * @memberof Options + */ + argv?: string[]; + /** + * If `true`, an array of unknown arguments is returned in the `_unknown` property of the output. + * + * @type {boolean} + * @memberof Options + */ + partial?: boolean; + } } export = commandLineArgs; From 80ba4dd2650bb3c841c3123ee9f49f345c29f6b4 Mon Sep 17 00:00:00 2001 From: Kewei Li Date: Fri, 10 Nov 2017 16:21:08 -0800 Subject: [PATCH 127/495] forgot a static method --- types/winrt-uwp/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/winrt-uwp/index.d.ts b/types/winrt-uwp/index.d.ts index 348ca65c55..2e1eb9391d 100644 --- a/types/winrt-uwp/index.d.ts +++ b/types/winrt-uwp/index.d.ts @@ -49396,7 +49396,7 @@ declare namespace Windows { * @param parametersAsJson A JSON-formatted string that contains the arguments to pass to the request. * @return An asynchronous operation that, on successful completion, returns a StoreSendRequestResult object that provides status and error info about the request. */ - sendRequestAsync(context: StoreContext, requestKind: number, parametersAsJson: string): Windows.Foundation.IPromiseWithIAsyncOperation; + static sendRequestAsync(context: StoreContext, requestKind: number, parametersAsJson: string): Windows.Foundation.IPromiseWithIAsyncOperation; } /** Provides response data for a request that is sent to the Windows Store. */ From effa795f85687dc303b3787b32e65f447dd938f1 Mon Sep 17 00:00:00 2001 From: Kewei Li Date: Fri, 10 Nov 2017 16:46:38 -0800 Subject: [PATCH 128/495] making IPromise compatible with ES6 PromiseLike --- types/winrt-uwp/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/winrt-uwp/index.d.ts b/types/winrt-uwp/index.d.ts index 2e1eb9391d..6e0a460e33 100644 --- a/types/winrt-uwp/index.d.ts +++ b/types/winrt-uwp/index.d.ts @@ -20,7 +20,7 @@ declare namespace Windows { } declare namespace Windows.Foundation { - interface IPromise { + interface IPromise extends PromiseLike { then(success?: (value: TResult) => IPromise, error?: (error: any) => IPromise, progress?: (progress: any) => void): IPromise; then(success?: (value: TResult) => IPromise, error?: (error: any) => U, progress?: (progress: any) => void): IPromise; then(success?: (value: TResult) => U, error?: (error: any) => IPromise, progress?: (progress: any) => void): IPromise; From 01d17fcb390ed1da239f97b91ba53e36ad2ac098 Mon Sep 17 00:00:00 2001 From: rcannon Date: Fri, 10 Nov 2017 23:29:21 -0800 Subject: [PATCH 129/495] [hystrixjs] Strengthen type hints This adds type hints for builders, commands and their respective callbacks functions out to seven arity, while leaving the nonspecific versions for backwards compatibility. This allows `commandFactory.getOrCreate()` to create fully type hinted callback signatures, both for the builder and the command. ```js const command = commandFactory. getOrCreate(); ``` I also replaced all references to `Q` with `PromiseLike`, and added the missing `hystrix.promise.implementation` configuration option, which allows changing the underlying promise implementation. This allows things like: ```js const Bluebird = require("bluebird"); HystrixConfig.init({ "hystrix.promise.implementation": Bluebird }); (command.execute() as Bluebird).catch(() => true); ``` ...although I couldn't figure out how to more elegantly express that Bluebird type. Also made the fallback signature match the implementation. --- types/hystrixjs/hystrixjs-tests.ts | 2 +- types/hystrixjs/index.d.ts | 206 ++++++++++++++++++++++++++++- types/hystrixjs/tsconfig.json | 8 +- 3 files changed, 202 insertions(+), 14 deletions(-) diff --git a/types/hystrixjs/hystrixjs-tests.ts b/types/hystrixjs/hystrixjs-tests.ts index 676015be06..7ed7819fb7 100644 --- a/types/hystrixjs/hystrixjs-tests.ts +++ b/types/hystrixjs/hystrixjs-tests.ts @@ -4,7 +4,7 @@ import q = require('q'); var commandFactory = hystrixjs.commandFactory; var command = commandFactory - .getOrCreate('testCommand', 'testGroup') + .getOrCreate('testCommand', 'testGroup') .circuitBreakerSleepWindowInMilliseconds(5000) .errorHandler((error) => { return false; diff --git a/types/hystrixjs/index.d.ts b/types/hystrixjs/index.d.ts index 865f2b3916..b49cd40ba4 100644 --- a/types/hystrixjs/index.d.ts +++ b/types/hystrixjs/index.d.ts @@ -4,7 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import * as Q from "q"; import * as RX from "rx"; export as namespace hystrixjs; @@ -23,7 +22,8 @@ export interface HystrixProperties { "hystrix.metrics.statistical.window.bucketsNumber"?: number, "hystrix.metrics.percentile.window.timeInMilliseconds"?: number, "hystrix.metrics.percentile.window.bucketsNumber"?: number, - "hystrix.request.volume.rejectionThreshold"?: number + "hystrix.request.volume.rejectionThreshold"?: number, + "hystrix.promise.implementation"?: PromiseConstructorLike, } export interface HystrixConfig { @@ -46,7 +46,39 @@ export interface HystrixConfig { } export interface Command { - execute(...args: any[]): Q.Promise; + execute(...args: any[]): PromiseLike +} + +export interface CommandA0 { + execute(): PromiseLike +} + +export interface CommandA1 { + execute(t: T): PromiseLike +} + +export interface CommandA2 { + execute(t: T, u: U): PromiseLike +} + +export interface CommandA3 { + execute(t: T, u: U, v: V): PromiseLike +} + +export interface CommandA4 { + execute(t: T, u: U, v: V, w: W): PromiseLike +} + +export interface CommandA5 { + execute(t: T, u: U, v: V, w: W, x: X): PromiseLike +} + +export interface CommandA6 { + execute(t: T, u: U, v: V, w: W, x: X, y: Y): PromiseLike +} + +export interface CommandA7 { + execute(t: T, u: U, v: V, w: W, x: X, y: Y, z: Z): PromiseLike } export interface CommandBuilder { @@ -62,14 +94,174 @@ export interface CommandBuilder { percentileWindowNumberOfBuckets(value: number): CommandBuilder; percentileWindowLength(value: number): CommandBuilder; circuitBreakerErrorThresholdPercentage(value: number): CommandBuilder; - run(value: (args: any) => Q.Promise): CommandBuilder; - fallbackTo(value: (...args: any[]) => Q.Promise): CommandBuilder; context(value: any): CommandBuilder; - build(): Command; + run(value: (...args: any[]) => PromiseLike): CommandBuilder; + fallbackTo(value: (error: Error, args ?: any[]) => PromiseLike): CommandBuilder; + build() : Command; +} + +export interface CommandBuilderA0 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA0; + errorHandler(value: (error: any) => boolean): CommandBuilderA0; + timeout(value: number): CommandBuilderA0; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA0; + requestVolumeRejectionThreshold(value: number): CommandBuilderA0; + circuitBreakerForceOpened(value: boolean): CommandBuilderA0; + circuitBreakerForceClosed(value: boolean): CommandBuilderA0; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA0; + statisticalWindowLength(value: number): CommandBuilderA0; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA0; + percentileWindowLength(value: number): CommandBuilderA0; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA0; + context(value: any): CommandBuilderA0; + run(value: () => PromiseLike): CommandBuilderA0; + fallbackTo(value: (error: Error) => PromiseLike): CommandBuilderA0; + build() : CommandA0; +} + +export interface CommandBuilderA1 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA1; + errorHandler(value: (error: any) => boolean): CommandBuilderA1; + timeout(value: number): CommandBuilderA1; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA1; + requestVolumeRejectionThreshold(value: number): CommandBuilderA1; + circuitBreakerForceOpened(value: boolean): CommandBuilderA1; + circuitBreakerForceClosed(value: boolean): CommandBuilderA1; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA1; + statisticalWindowLength(value: number): CommandBuilderA1; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA1; + percentileWindowLength(value: number): CommandBuilderA1; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA1; + context(value: any): CommandBuilderA1; + run(value: (t: T) => PromiseLike): CommandBuilderA1; + fallbackTo(value: (error: Error, args : [T]) => PromiseLike): CommandBuilderA1; + build(): CommandA1; +} + +export interface CommandBuilderA2 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA2; + errorHandler(value: (error: any) => boolean): CommandBuilderA2; + timeout(value: number): CommandBuilderA2; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA2; + requestVolumeRejectionThreshold(value: number): CommandBuilderA2; + circuitBreakerForceOpened(value: boolean): CommandBuilderA2; + circuitBreakerForceClosed(value: boolean): CommandBuilderA2; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA2; + statisticalWindowLength(value: number): CommandBuilderA2; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA2; + percentileWindowLength(value: number): CommandBuilderA2; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA2; + context(value: any): CommandBuilderA2; + run(value: (t: T, u: U) => PromiseLike): CommandBuilderA2; + fallbackTo(value: (error: Error, args: [T, U]) => PromiseLike): CommandBuilderA2; + build(): CommandA2; +} + +export interface CommandBuilderA3 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA3; + errorHandler(value: (error: any) => boolean): CommandBuilderA3; + timeout(value: number): CommandBuilderA3; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA3; + requestVolumeRejectionThreshold(value: number): CommandBuilderA3; + circuitBreakerForceOpened(value: boolean): CommandBuilderA3; + circuitBreakerForceClosed(value: boolean): CommandBuilderA3; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA3; + statisticalWindowLength(value: number): CommandBuilderA3; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA3; + percentileWindowLength(value: number): CommandBuilderA3; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA3; + context(value: any): CommandBuilderA3; + run(value: (t: T, u: U, v: V) => PromiseLike): CommandBuilderA3; + fallbackTo(value: (error: Error, args: [T, U, V]) => PromiseLike): CommandBuilderA3; + build(): CommandA3; +} + +export interface CommandBuilderA4 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA4; + errorHandler(value: (error: any) => boolean): CommandBuilderA4; + timeout(value: number): CommandBuilderA4; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA4; + requestVolumeRejectionThreshold(value: number): CommandBuilderA4; + circuitBreakerForceOpened(value: boolean): CommandBuilderA4; + circuitBreakerForceClosed(value: boolean): CommandBuilderA4; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA4; + statisticalWindowLength(value: number): CommandBuilderA4; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA4; + percentileWindowLength(value: number): CommandBuilderA4; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA4; + context(value: any): CommandBuilderA4; + run(value: (t: T, u: U, v: V, w: W) => PromiseLike): CommandBuilderA4; + fallbackTo(value: (error: Error, args: [T, U, V, W]) => PromiseLike): CommandBuilderA4; + build(): CommandA4; +} + +export interface CommandBuilderA5 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA5; + errorHandler(value: (error: any) => boolean): CommandBuilderA5; + timeout(value: number): CommandBuilderA5; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA5; + requestVolumeRejectionThreshold(value: number): CommandBuilderA5; + circuitBreakerForceOpened(value: boolean): CommandBuilderA5; + circuitBreakerForceClosed(value: boolean): CommandBuilderA5; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA5; + statisticalWindowLength(value: number): CommandBuilderA5; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA5; + percentileWindowLength(value: number): CommandBuilderA5; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA5; + context(value: any): CommandBuilderA5; + run(value: (t: T, u: U, v: V, w: W, x: X) => PromiseLike): CommandBuilderA5; + fallbackTo(value: (error: Error, args: [T, U, V, W, X]) => PromiseLike): CommandBuilderA5; + build(): CommandA5; +} + +export interface CommandBuilderA6 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA6; + errorHandler(value: (error: any) => boolean): CommandBuilderA6; + timeout(value: number): CommandBuilderA6; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA6; + requestVolumeRejectionThreshold(value: number): CommandBuilderA6; + circuitBreakerForceOpened(value: boolean): CommandBuilderA6; + circuitBreakerForceClosed(value: boolean): CommandBuilderA6; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA6; + statisticalWindowLength(value: number): CommandBuilderA6; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA6; + percentileWindowLength(value: number): CommandBuilderA6; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA6; + context(value: any): CommandBuilderA6; + run(value: (t: T, u: U, v: V, w: W, x: X, y: Y) => PromiseLike): CommandBuilderA6; + fallbackTo(value: (error: Error, args: [T, U, V, W, X, Y]) => PromiseLike): CommandBuilderA6; + build(): CommandA6; +} + +export interface CommandBuilderA7 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA7; + errorHandler(value: (error: any) => boolean): CommandBuilderA7; + timeout(value: number): CommandBuilderA7; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA7; + requestVolumeRejectionThreshold(value: number): CommandBuilderA7; + circuitBreakerForceOpened(value: boolean): CommandBuilderA7; + circuitBreakerForceClosed(value: boolean): CommandBuilderA7; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA7; + statisticalWindowLength(value: number): CommandBuilderA7; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA7; + percentileWindowLength(value: number): CommandBuilderA7; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA7; + context(value: any): CommandBuilderA7; + run(value: (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z) => PromiseLike): CommandBuilderA7; + fallbackTo(value: (error: Error, args: [T, U, V, W, X, Y, Z]) => PromiseLike): CommandBuilderA7; + build(): CommandA7; } export interface CommandFactory { getOrCreate(commandKey: string, commandGroup?: string): CommandBuilder; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA0; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA1; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA2; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA3; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA4; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA5; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA6; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA7; resetCache(): void; } @@ -141,4 +333,4 @@ export var commandFactory: CommandFactory; export var metricsFactory: MetricsFactory; export var circuitFactory: CircuitFactory; export var hystrixSSEStream: HystrixSSEStream; -export var hystrixConfig: HystrixConfig; \ No newline at end of file +export var hystrixConfig: HystrixConfig; diff --git a/types/hystrixjs/tsconfig.json b/types/hystrixjs/tsconfig.json index 0cf5de7b81..480476e8d1 100644 --- a/types/hystrixjs/tsconfig.json +++ b/types/hystrixjs/tsconfig.json @@ -13,11 +13,7 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, + "paths": {}, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true @@ -26,4 +22,4 @@ "index.d.ts", "hystrixjs-tests.ts" ] -} \ No newline at end of file +} From 39eb487630e124e3718f6a32158c9046405f5409 Mon Sep 17 00:00:00 2001 From: Evan Moran Date: Sat, 11 Nov 2017 10:47:23 -0500 Subject: [PATCH 130/495] Initial dynogels changes. More to come --- types/dynogels/dynogels-tests.ts | 30 ++++++ types/dynogels/index.d.ts | 163 +++++++++++++++++++++++++++++++ types/dynogels/package.json | 7 ++ types/dynogels/tsconfig.json | 24 +++++ types/dynogels/tslint.json | 1 + 5 files changed, 225 insertions(+) create mode 100644 types/dynogels/dynogels-tests.ts create mode 100644 types/dynogels/index.d.ts create mode 100644 types/dynogels/package.json create mode 100644 types/dynogels/tsconfig.json create mode 100644 types/dynogels/tslint.json diff --git a/types/dynogels/dynogels-tests.ts b/types/dynogels/dynogels-tests.ts new file mode 100644 index 0000000000..90e8184900 --- /dev/null +++ b/types/dynogels/dynogels-tests.ts @@ -0,0 +1,30 @@ +/// +import * as dynogels from "dynogels"; +import { DynamoDB } from "aws-sdk"; +dynogels.AWS; + +dynogels.log.info("test", "123", {}); +dynogels.log.warn("test", "123", {}); + +var dynamoDb = new DynamoDB(); +dynamoDb.getItem() +dynogels.dynamoDriver(dynamoDb); +dynogels.reset(); +var model = dynogels.define("asdfas", { + hashKey: "Asdf", schema: { + + } +}); + +let a = new model({ test: 12312 }); + + +model.get("asdfas,", (err, test) => { + +}); + +model.create({}, (err, data) => { + var a = data.get("hello"); + a.asdfs = 1; + data.set({ test: "12312" }); +}) diff --git a/types/dynogels/index.d.ts b/types/dynogels/index.d.ts new file mode 100644 index 0000000000..2e05fb0c61 --- /dev/null +++ b/types/dynogels/index.d.ts @@ -0,0 +1,163 @@ +// Type definitions for dynogels 8.0 +// Project: https://github.com/clarkie/dynogels#readme +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export import AWS = require("aws-sdk"); +import stream = require("stream"); +export namespace log { + function info(...args: any[]): void; + function warn(...args: any[]): void; +} +export let models: { [key: string]: any }; +export function dynamoDriver(dynamoDB: AWS.DynamoDB): AWS.DynamoDB; +export function reset(): void; +export function define(modelName: string, config: ModelConfiguration): Model; +export function createTables(callback: (err: string) => void): any; + +type DynogelsItemCallback = (err: Error, data: Item) => void; + +export interface Model { + new(attrs: { [key: string]: any }): Item; + + get(hashKey: any, rangeKey: any, options: AWS.DynamoDB.GetItemInput, callback: DynogelsItemCallback): void; + get(haskKey: any, options: AWS.DynamoDB.GetItemInput, callback: DynogelsItemCallback): void; + get(hashKey: any, callback: DynogelsItemCallback): void; + get(hashKey: any, rangeKey: any, callback: DynogelsItemCallback): void; + create(item: any, options: AWS.DynamoDB.CreateTableInput, callback: DynogelsItemCallback): void; + create(item: any, callback: DynogelsItemCallback): void; + update(item: any, options: AWS.DynamoDB.UpdateItemInput, callback: DynogelsItemCallback): void; + update(item: any, callback: DynogelsItemCallback): void; + destroy(hashKey: any, rangeKey: any, options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; + destroy(haskKey: any, options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; + destroy(hashKey: any, callback: DynogelsItemCallback): void; + destroy(hashKey: any, rangeKey: any, callback: DynogelsItemCallback): void; + destroy(item: any, options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; + destroy(item: any, callback: DynogelsItemCallback): void; + query(hashKey: any): Query; + scan(): void; + parallelScan(): void; + getItems(): void; + batchGetItems(): void; + createTable(): void; + updateTable(): void; + describeTable(): void; + deleteTable(): void; + tableName(): void; + + after(): void; + before(): void; + config(): void; +} + +export interface Item { + get(key: string): { [key: string]: any }; + set(params: {}): void; + save(callback: DynogelsItemCallback): void; + update(options: AWS.DynamoDB.UpdateItemInput, callback: DynogelsItemCallback): void; + update(callback: DynogelsItemCallback): void; + destroy(options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; + destroy(callback: DynogelsItemCallback): void; + toJSON(): any; + toPlainObject(): any; +} + +export interface Query { + limit(number: number): Query; + filterExpression(expression: any): Query; + expressionAttributeNames(data: any): Query; + expressionAttributeValues(data: any): Query; + projectionExpression(data: any): Query; + usingIndex(name: string): Query; + consistentRead(read: boolean): Query; + addKeyCondition(condition: any): Query; + addFilterCondition(condition: any): Query; + startKey(hashKey: any, rangeKey: any): Query; + attributes(attrs: any): Query; + ascending(): Query; + descending(): Query; + select(value: any): Query; + returnConsumedCapacity(value: any): Query; + loadAll(): Query; + where(keyName: string): { + equals(value: any): Query; + eq(value: any): Query; + lte(value: any): Query; + lt(value: any): Query; + gte(value: any): Query; + gt(value: any): Query; + beginsWith(value: any): Query; + between(value1: any, value2: any): Query; + }; + filter(keyName: string): { + equals(value: any): Query; + eq(value: any): Query; + ne(value: any): Query; + lte(value: any): Query; + lt(value: any): Query; + gte(value: any): Query; + gt(value: any): Query; + null(): Query; + exists(): Query; + contains(value: any): Query; + notContains(value: any): Query; + in(values: any[]): Query; + beginsWith(value: any): Query; + between(value1: any, value2: any): Query; + }; + exec(): stream.Readable; + exec(callback: () => void): void; +} + +export interface Scan { + limit(number: number): Scan; + addFilterCondition(condition: any): Scan; + startKey(hashKey: any, rangeKey: any): Scan; + attributes(attrs: any): Scan; + select(value: any): Scan; + segments(segment: any, totalSegments: number): Scan; + where(keyName: string): { + equals(value: any): Scan; + eq(value: any): Scan; + ne(value: any): Scan; + lte(value: any): Scan; + lt(value: any): Scan; + gte(value: any): Scan; + gt(value: any): Scan; + null(): Scan; + exists(): Scan; + contains(value: any): Scan; + notContains(value: any): Scan; + in(values: any[]): Scan; + beginsWith(value: any): Scan; + between(value1: any, value2: any): Scan; + }; + filterExpression(expression: any): Scan; + expressionAttributeNames(data: any): Scan; + expressionAttributeValues(data: any): Scan; + projectionExpression(data: any): Scan; + exec(): stream.Readable; + exec(callback: () => void): void; + loadAll(): Scan; +} + +type tableResolve = () => string; + +export interface ModelConfiguration { + hashKey: string, + rangeKey?: string, + timestamps?: boolean, + createdAt?: boolean, + updatedAtField?: string, + schema: { [key: string]: any }, + tableName?: string | tableResolve; +} +interface Document { + [key: string]: any; +} + +export interface DocumentCollection { + Items: Document[], + Count: number, + ScannedCount: number +} diff --git a/types/dynogels/package.json b/types/dynogels/package.json new file mode 100644 index 0000000000..903b5d2531 --- /dev/null +++ b/types/dynogels/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "dependencies": { + "@types/node": "^8.0.51", + "aws-sdk": "^2.58.0" + } +} \ No newline at end of file diff --git a/types/dynogels/tsconfig.json b/types/dynogels/tsconfig.json new file mode 100644 index 0000000000..9b5f6a4e52 --- /dev/null +++ b/types/dynogels/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [ + "node" + ], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dynogels-tests.ts" + ] +} \ No newline at end of file diff --git a/types/dynogels/tslint.json b/types/dynogels/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dynogels/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 66b805edf20a32416537adc161f1857817aca04e Mon Sep 17 00:00:00 2001 From: Shaun Luttin Date: Sat, 11 Nov 2017 08:27:36 -0800 Subject: [PATCH 131/495] Update Resource.js typings --- types/resourcejs/index.d.ts | 2 +- types/resourcejs/resourcejs-tests.ts | 12 +++++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/types/resourcejs/index.d.ts b/types/resourcejs/index.d.ts index bb4bffa197..ec5e938745 100644 --- a/types/resourcejs/index.d.ts +++ b/types/resourcejs/index.d.ts @@ -94,7 +94,7 @@ declare namespace resourcejs { interface Resource { status: number; error: Error; - item: mongoose.Document | mongoose.Document[]; + item: any; } interface Error { diff --git a/types/resourcejs/resourcejs-tests.ts b/types/resourcejs/resourcejs-tests.ts index b3d2604933..603d31c255 100644 --- a/types/resourcejs/resourcejs-tests.ts +++ b/types/resourcejs/resourcejs-tests.ts @@ -11,7 +11,17 @@ const model = mongoose.model(resourceName, schema); resourcejs(app, route, resourceName, model) .get() - .post() + .post({ + after(req: resourcejs.Request, res: resourcejs.Response, next: express.NextFunction) { + res.resource.item = { + foo: "foo", + bar: "bar", + baz: "baz", + }; + + next(); + }, + }) .delete() .put() .patch() From f4b539d95334d5c0be91409f5fc7465020b3d1e9 Mon Sep 17 00:00:00 2001 From: Konrad Mattheis Date: Sat, 11 Nov 2017 20:47:34 +0100 Subject: [PATCH 132/495] add new types for enigma.js Signed-off-by: Konrad Mattheis --- types/enigma.js/index.d.ts | 196 ++++++++++++++++++++++++++++++++++ types/enigma.js/tsconfig.json | 23 ++++ types/enigma.js/tslint.json | 10 ++ 3 files changed, 229 insertions(+) create mode 100644 types/enigma.js/index.d.ts create mode 100644 types/enigma.js/tsconfig.json create mode 100644 types/enigma.js/tslint.json diff --git a/types/enigma.js/index.d.ts b/types/enigma.js/index.d.ts new file mode 100644 index 0000000000..5a316b669c --- /dev/null +++ b/types/enigma.js/index.d.ts @@ -0,0 +1,196 @@ +// Type definitions for enigma.js 2.2 +// Project: https://github.com/qlik-oss/enigma.js/ +// Definitions by: Konrad Mattheis +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +declare module "enigma.js" { + const e: IEnigmaJSClass; + export = e; +} + +interface IEnigmaJSClass { + /** + * Create a session object. + * @returns - Returns a session. + * Note: See Configuration for the configuration options. + */ + create(config: enigmaJS.IConfig): enigmaJS.ISession; +} + +declare namespace enigmaJS { + type MixinType = "Doc"| "GenericObject"| "GenericBookmark" | string; + + interface IMixin { + /** + * QIX Engine types like for example GenericObject, Doc, GenericBookmark, are supported but also custom GenericObject + * types such as barchart, story and myCustomType. + * An API will get both their generic type as well as custom type mixins applied. + */ + types: [MixinType]; + + init(args: {config: any, api: IGeneratedAPI}): void; + + /** + * mixin.extend is an object containing methods to extend the generated API with. These method names cannot already exist or enigma.js will throw an error. + */ + extend?: [any]; + + /** + * mixin.override is an object containing methods that overrides existing API methods. + * These method names needs to exist already* or engima.js will throw an error. + * Be careful when overriding, you may break expected behaviors in other mixins or your application. + * base is a reference to the previous mixin method, can be used to invoke the mixin chain before this mixin method. + */ + override?: [any]; + } + + interface IProtocol { + // Set to false to disable the use of the bandwidth-reducing delta protocol. + delta?: boolean; + } + + /** + * This section describes the configuration object that is sent into enigma.create(config). + */ + interface IConfig { + /** + * Object containing the specification for the API to generate. Corresponds to a specific version of the QIX Engine API. + */ + schema: object; + /** + * String containing a proper websocket URL to QIX Engine. + */ + url: string; + /** + * A function to use when instantiating the WebSocket, mandatory for Node.js. + */ + createSocket?: any; + /** + * ES6-compatible Promise library. + */ + Promise?: any; + /** + * Set to true if the session should be suspended instead of closed when the websocket is closed. + */ + suspendOnClose?: boolean; + /** + * Mixins to extend/augment the QIX Engine API. + * See Mixins section for more information how each entry in this array should look like. + * Mixins are applied in the array order. + */ + mixins?: [any]; + /** + * Interceptors for augmenting responses before they are passed into mixins and end-users. + * See Interceptors section for more information how each entry in this array should look like. + * Interceptors are applied in the array order. + */ + interceptors?: [any]; + /** + * An object containing additional JSON-RPC request parameters. + * protocol.delta : Set to false to disable the use of the bandwidth-reducing delta protocol. + */ + protocol?: any; + } + + interface ISession { + /** + * Establishes the websocket against the configured URL. Eventually resolved with the QIX global interface when the connection has been established. + * @return Promise. + */ + open(): Promise; + + /** + * Establishes the websocket against the configured URL. Eventually resolved with the QIX global interface when the connection has been established. + * @return Promise. + */ + open(): Promise; + + /** + * Closes the websocket and cleans up internal caches, also triggers the closed event on all generated APIs. + * Eventually resolved when the websocket has been closed. + * + * Note: you need to manually invoke this when you want to close a session and config.suspendOnClose is true. + * @return Promise. + */ + close(): Promise; + + /** + * Suspends the enigma.js session by closing the websocket and rejecting all method calls until it has been resumed again. + * @return Promise. + */ + suspend(): Promise; + + /** + * Resume a previously suspended enigma.js session by re-creating the websocket and, if possible, re-open the document + * as well as refreshing the internal caches. If successful, changed events will be triggered on all generated APIs, + * and on the ones it was unable to restore, the closed event will be triggered. + * @param onlyIfAttached onlyIfAttached can be used to only allow resuming if the QIX Engine session was reattached properly. + * @return Promise. + * Note: Eventually resolved when the websocket (and potentially the previously opened document, and generated APIs) has been restored, + * rejected when it fails any of those steps, or when onlyIfAttached is true and a new QIX Engine session was created. + */ + resume(onlyIfAttached?: boolean): Promise; + + /** + * Handle opened state. This event is triggered whenever the websocket is connected and ready for communication. + * + * Handle closed state. This event is triggered when the underlying websocket is closed and config.suspendOnClose is false. + * + * Handle suspended state. This event is triggered in two cases (listed below). It is useful in scenarios where you for example + * want to block interaction in your application until you are resumed again. + * If config.suspendOnClose is true and there was a network disconnect (socked closed) + * If you ran session.suspend() + * The evt.initiator value is a string indicating what triggered the suspended state. Possible values: network, manual. + * + * Handle resumed state. This event is triggered when the session was properly resumed. + * It is useful in scenarios where you for example can close blocking modal dialogs and allow the user to interact with your application again. + * + * notification:* + * @param event - Event that triggers the function + * @param func - Called function + */ + on(event: "opened" | "close" | "suspended" | "resumed" | string, func: any): void; + } + + interface IGeneratedAPI { + /** + * This property contains the unique identifier for this API. + */ + id: string; + + /** + * This property contains the schema class name for this API. + */ + type: string; + + /** + * Despite the name, this property corresponds to the qInfo.qType property on your generic object's properties object. + */ + genericType: string; + + /** + * This property contains a reference to the session that this API belongs to. + */ + session: ISession; + + /** + * This property contains the handle QIX Engine assigned to the API. + * Used internally in enigma.js for caches and JSON-RPC + */ + handle: number; + + /** + * register a function for events + * @param event - function called if this event occures + * @param func - function that is called + */ + on(event: "changed" | "closed", func: () => void): void; + + /** + * manual emit an events + * @param event - event that occures + */ + emit(event: "changed" | "closed"): void; + } +} diff --git a/types/enigma.js/tsconfig.json b/types/enigma.js/tsconfig.json new file mode 100644 index 0000000000..2eae92bb60 --- /dev/null +++ b/types/enigma.js/tsconfig.json @@ -0,0 +1,23 @@ +{ + "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" + ] +} \ No newline at end of file diff --git a/types/enigma.js/tslint.json b/types/enigma.js/tslint.json new file mode 100644 index 0000000000..5d8cce7b04 --- /dev/null +++ b/types/enigma.js/tslint.json @@ -0,0 +1,10 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // TODOs + "interface-name": false, + "no-unnecessary-generics": false, + "no-single-declare-module": false, + "no-declare-current-package": false + } +} From 0d5a1ef2696bf64ce1fcf8083b65bb3f723cad3b Mon Sep 17 00:00:00 2001 From: Konrad Mattheis Date: Sat, 11 Nov 2017 20:47:50 +0100 Subject: [PATCH 133/495] fix small issues --- types/qlik-engineapi/index.d.ts | 2 +- types/qlik-visualizationextensions/index.d.ts | 28 +++++++++++++++++-- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/types/qlik-engineapi/index.d.ts b/types/qlik-engineapi/index.d.ts index 17f7a7892b..d908d5a313 100644 --- a/types/qlik-engineapi/index.d.ts +++ b/types/qlik-engineapi/index.d.ts @@ -6911,7 +6911,7 @@ declare namespace EngineAPI { * This class describes all the methods that apply at global level. * The handle member in the JSON request for all methods listed in this section is -1. */ - interface IGlobal { + interface IGlobal extends enigmaJS.IGeneratedAPI { /** * Sets an abort flag on all pending and ongoing requests in the current engine session. * If an abort flag is set on a pending request, the request is aborted. diff --git a/types/qlik-visualizationextensions/index.d.ts b/types/qlik-visualizationextensions/index.d.ts index 5d10ff9bcb..6baee98c1b 100644 --- a/types/qlik-visualizationextensions/index.d.ts +++ b/types/qlik-visualizationextensions/index.d.ts @@ -2566,8 +2566,33 @@ declare module "qvangular" { export = e; } +/** + * This section is added because the Qlik Sense Client after > 3.2 contains a engineapi + * an this makes the handling more fluent for users of that files. + */ declare namespace enigmaJS { interface IGeneratedAPI { + /** + * This property contains the unique identifier for this API. + */ + id: string; + + /** + * This property contains the schema class name for this API. + */ + type: string; + + /** + * Despite the name, this property corresponds to the qInfo.qType property on your generic object's properties object. + */ + genericType: string; + + /** + * This property contains the handle QIX Engine assigned to the API. + * Used internally in enigma.js for caches and JSON-RPC + */ + handle: number; + /** * register a function for events * @param event - function called if this event occures @@ -2580,8 +2605,5 @@ declare namespace enigmaJS { * @param event - event that occures */ emit(event: "changed" | "closed"): void; - - // ? not in Docu - id: string; } } From ba3f92e99ce8bd1c0d8e42f1767144da06b66086 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomek=20=C5=81aziuk?= Date: Sun, 12 Nov 2017 01:33:41 +0100 Subject: [PATCH 134/495] html-webpack-plugin 2.30 --- types/html-webpack-plugin/index.d.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/types/html-webpack-plugin/index.d.ts b/types/html-webpack-plugin/index.d.ts index b08a69faa5..dc23e020d7 100644 --- a/types/html-webpack-plugin/index.d.ts +++ b/types/html-webpack-plugin/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for html-webpack-plugin 2.28 +// Type definitions for html-webpack-plugin 2.30 // Project: https://github.com/ampedandwired/html-webpack-plugin -// Definitions by: Simon Hartcher , Benjamin Lim +// Definitions by: Simon Hartcher +// Benjamin Lim +// Tomek Łaziuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import { Plugin } from 'webpack'; @@ -35,9 +37,9 @@ declare namespace HtmlWebpackPlugin { cache?: boolean; /** * Allows to control how chunks should be sorted before they are included to the html. - * Allowed values: `'none' | 'auto' | 'dependency' | {function}` - default: `'auto'` + * Allowed values: 'none' | 'auto' | 'dependency' |'manual' | {function} - default: 'auto' */ - chunksSortMode?: 'none' | 'auto' | 'dependency' | ChunkComparator; + chunksSortMode?: 'none' | 'auto' | 'dependency' | 'manual' | ChunkComparator; /** Allows you to add only some chunks (e.g. only the unit-test chunk) */ chunks?: string[]; /** Allows you to skip some chunks (e.g. don't add the unit-test chunk) */ From 49f2d7ce15bcbda133440a1687569a80328aa44f Mon Sep 17 00:00:00 2001 From: AJ Richardson Date: Sat, 11 Nov 2017 21:18:26 -0500 Subject: [PATCH 135/495] Trying to make strictFunctionTypes work (#21206). Wrapper assignability is fixed, but tests are failing due to GC error. --- types/lodash/index.d.ts | 12 ++++++++---- types/lodash/tsconfig.json | 2 +- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/types/lodash/index.d.ts b/types/lodash/index.d.ts index f038846d22..fafa7f6b5c 100644 --- a/types/lodash/index.d.ts +++ b/types/lodash/index.d.ts @@ -10723,7 +10723,7 @@ declare namespace _ { /** * @see _.toArray */ - toArray(): LoDashImplicitWrapper>; + //toArray(): LoDashImplicitWrapper>; } interface LoDashExplicitWrapper { @@ -10735,7 +10735,7 @@ declare namespace _ { /** * @see _.toArray */ - toArray(): LoDashExplicitWrapper>; + //toArray(): LoDashExplicitWrapper>; } //_.toPlainObject @@ -16078,14 +16078,18 @@ declare namespace _ { /** * @see _.constant */ - constant(): LoDashImplicitWrapper<() => TValue>; + constant(this: LoDashImplicitWrapper): LoDashImplicitWrapper<() => T>; + // Note: we can't use TValue here because of an issue with dtslint. Using T as a workaround; change back to TValue once dtsLint is working. + // constant(): LoDashImplicitWrapper<() => TValue>; } interface LoDashExplicitWrapper { /** * @see _.constant */ - constant(): LoDashExplicitWrapper<() => TValue>; + constant(this: LoDashExplicitWrapper): LoDashExplicitWrapper<() => T>; + // Note: we can't use TValue here because of an issue with dtslint. Using T as a workaround; change back to TValue once dtsLint is working. + // constant(): LoDashExplicitWrapper<() => TValue>; } //_.defaultTo diff --git a/types/lodash/tsconfig.json b/types/lodash/tsconfig.json index 2c4aa57c54..8bd56c0b87 100644 --- a/types/lodash/tsconfig.json +++ b/types/lodash/tsconfig.json @@ -7,7 +7,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "strictFunctionTypes": false, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" From 58e1da1771935181ed91cadf85497b6ce8ca3006 Mon Sep 17 00:00:00 2001 From: Evan Moran Date: Sat, 11 Nov 2017 23:54:48 -0500 Subject: [PATCH 136/495] Added all examples from documentation for testing/added more typings --- types/dynogels/dynogels-tests.ts | 844 ++++++++++++++++++++++++++++++- types/dynogels/index.d.ts | 130 ++++- 2 files changed, 939 insertions(+), 35 deletions(-) diff --git a/types/dynogels/dynogels-tests.ts b/types/dynogels/dynogels-tests.ts index 90e8184900..756977d066 100644 --- a/types/dynogels/dynogels-tests.ts +++ b/types/dynogels/dynogels-tests.ts @@ -1,30 +1,840 @@ /// -import * as dynogels from "dynogels"; +import dynogels = require("dynogels"); import { DynamoDB } from "aws-sdk"; -dynogels.AWS; +import * as Joi from "joi"; -dynogels.log.info("test", "123", {}); -dynogels.log.warn("test", "123", {}); +//AWS Configs +dynogels.AWS.config.loadFromPath('credentials.json'); +dynogels.AWS.config.update({ region: "REGION" }); -var dynamoDb = new DynamoDB(); -dynamoDb.getItem() -dynogels.dynamoDriver(dynamoDb); -dynogels.reset(); -var model = dynogels.define("asdfas", { - hashKey: "Asdf", schema: { +//Define a Model +var Account = dynogels.define('Account', { + hashKey: 'email', + + // add the timestamp attributes (updatedAt, createdAt) + timestamps: true, + + schema: { + email: Joi.string().email(), + name: Joi.string(), + age: Joi.number(), + roles: dynogels.types.stringSet(), + settings: { + nickname: Joi.string(), + acceptedTerms: Joi.boolean().default(false), + test: { + evan: Joi.string() + } + } } }); -let a = new model({ test: 12312 }); +var BlogPost = dynogels.define('BlogPost', { + hashKey: 'email', + rangeKey: 'title', + schema: { + email: Joi.string().email(), + title: Joi.string(), + content: Joi.binary(), + tags: dynogels.types.stringSet(), + } +}); +var BlogPost = dynogels.define('BlogPost', { + hashKey: 'email', + rangeKey: 'title', + schema: { + email: Joi.string().email(), + title: Joi.string() + }, + validation: { + // allow properties not defined in the schema + allowUnknown: true + } +}); -model.get("asdfas,", (err, test) => { +//Create Tables +dynogels.createTables(function (err) { + if (err) { + console.log('Error creating tables: ', err); + } else { + console.log('Tables has been created'); + } +}); + +dynogels.createTables({ + 'BlogPost': { readCapacity: 5, writeCapacity: 10 }, + 'Account': { + readCapacity: 20, + writeCapacity: 4, + streamSpecification: { + streamEnabled: true, + streamViewType: 'NEW_IMAGE' + } + } +}, function (err) { + if (err) { + console.log('Error creating tables: ', err); + } else { + console.log('Tables has been created'); + } +}); + +dynogels.createTables({ + $dynogels: { pollingInterval: 100 } +}, function (err) { + if (err) { + console.log('Error creating tables: ', err); + } else { + console.log('Tables has been created'); + } +}); + +// Delete Table +BlogPost.deleteTable(function (err) { + if (err) { + console.log('Error deleting table: ', err); + } else { + console.log('Table has been deleted'); + } +}); + +//UUID +var Tweet = dynogels.define('Tweet', { + hashKey: 'TweetID', + timestamps: true, + schema: { + TweetID: dynogels.types.uuid(), + content: Joi.string(), + } +}); + +//Configuration +var Account = dynogels.define('Account', { + hashKey: 'email', + + // add the timestamp attributes (updatedAt, createdAt) + timestamps: true, + + schema: { + email: Joi.string().email(), + } +}); + +var Account = dynogels.define('Account', { + hashKey: 'email', + + // enable timestamps support + timestamps: true, + + // I don't want createdAt + createdAt: false, + + // I want updatedAt to actually be called updateTimestamp + updatedAt: 'updateTimestamp', + + schema: { + email: Joi.string().email(), + } +}); + +var Event = dynogels.define('Event', { + hashKey: 'name', + schema: { + name: Joi.string(), + total: Joi.number() + }, + + tableName: 'deviceEvents' +}); + +var Event = dynogels.define('Event', { + hashKey: 'name', + schema: { + name: Joi.string(), + total: Joi.number() + }, + + // store monthly event data + tableName: function () { + var d = new Date(); + return ['events', d.getFullYear(), d.getMonth() + 1].join('_'); + } +}); + +Account.config({ tableName: 'AccountsTable' }); + +var dynamodb = new DynamoDB(); +Account.config({ dynamodb: dynamodb }); + +// or globally use custom DynamoDB instance +// all defined models will now use this driver +dynogels.dynamoDriver(dynamodb); + +// Saving Models To DynamoDB +Account.create({ email: 'foo@example.com', name: 'Foo Bar', age: 21 }, function (err, acc) { + console.log('created account in DynamoDB', acc.get('email')); +}); + +var acc = new Account({ email: 'test@example.com', name: 'Test Example' }); +acc.save(function (err) { + console.log('created account in DynamoDB', acc.get('email')); +}); + +BlogPost.create({ + email: 'werner@example.com', + title: 'Expanding the Cloud', + content: 'Today, we are excited to announce the limited preview...' +}, function (err, post) { + console.log('created blog post', post.get('title')); +}); + +var item1 = { email: 'foo1@example.com', name: 'Foo 1', age: 10 }; +var item2 = { email: 'foo2@example.com', name: 'Foo 2', age: 20 }; +var item3 = { email: 'foo3@example.com', name: 'Foo 3', age: 30 }; + +Account.create([item1, item2, item3], function (err, accounts) { + console.log('created 3 accounts in DynamoDB', accounts); +}); + +var params: dynogels.CreateItemOptions = { + +}; +params.ConditionExpression = '#i <> :x'; +params.ExpressionAttributeNames = { '#i': 'id' }; +params.ExpressionAttributeValues = { ':x': 123 }; + +Account.create({ id: 123, name: 'Kurt Warner' }, params, function (error, acc) { }); -model.create({}, (err, data) => { - var a = data.get("hello"); - a.asdfs = 1; - data.set({ test: "12312" }); -}) +// setting overwrite to false will generate +// the same Condition Expression as in the previous example +Account.create({ id: 123, name: 'Kurt Warner' }, { overwrite: false }, function (error, acc) { }); + +// Updating +Account.update({ email: 'foo@example.com', name: 'Bar Tester' }, function (err, acc) { + console.log('update account', acc.get('name')); +}); + +Account.update({ email: 'foo@example.com', name: 'Bar Tester' }, { ReturnValues: 'ALL_OLD' }, function (err, acc) { + console.log('update account', acc.get('name')); // prints the old account name +}); + +// Only update the account if the current age of the account is 22 +Account.update({ email: 'foo@example.com', name: 'Bar Tester' }, { expected: { age: 22 } }, function (err, acc) { + console.log('update account', acc.get('name')); +}); + +// setting an attribute to null will delete the attribute from DynamoDB +Account.update({ email: 'foo@example.com', age: null }, function (err, acc) { + console.log('update account', acc.get('age')); // prints null +}); + +Account.update( + { email: 'foo@example.com', name: 'FooBar Testers' }, + { expected: { email: { Exists: true } } }, + (err, acc) => { + console.log(acc.get('name')); // FooBar Testers + } +); + +Account.update( + { email: 'baz@example.com', name: 'Bar Tester' }, + { expected: { email: { Exists: true } } }, + (err, acc) => { + console.log(err); // Condition Expression failed: no Account with that hash key + } +); + +Account.update({ email: 'foo@example.com', age: { $add: 1 } }, function (err, acc) { + console.log('incremented age by 1', acc.get('age')); +}); + +BlogPost.update({ + email: 'werner@example.com', + title: 'Expanding the Cloud', + tags: { $add: 'cloud' } +}, function (err, post) { + console.log('added single tag to blog post', post.get('tags')); +}); + +BlogPost.update({ + email: 'werner@example.com', + title: 'Expanding the Cloud', + tags: { $add: ['cloud', 'dynamodb'] } +}, function (err, post) { + console.log('added tags to blog post', post.get('tags')); +}); + +BlogPost.update({ + email: 'werner@example.com', + title: 'Expanding the Cloud', + tags: { $del: 'cloud' } +}, function (err, post) { + console.log('removed cloud tag from blog post', post.get('tags')); +}); + +BlogPost.update({ + email: 'werner@example.com', + title: 'Expanding the Cloud', + tags: { $del: ['aws', 'node'] } +}, function (err, post) { + console.log('removed multiple tags', post.get('tags')); +}); + +var params1: dynogels.UpdateItemOptions = {}; +params1.UpdateExpression = 'SET #year = #year + :inc, #dir.titles = list_append(#dir.titles, :title), #act[0].firstName = :firstName ADD tags :tag'; +params1.ConditionExpression = '#year = :current'; +params1.ExpressionAttributeNames = { + '#year': 'releaseYear', + '#dir': 'director', + '#act': 'actors' +}; + +params1.ExpressionAttributeValues = { + ':inc': 1, + ':current': 2001, + ':title': ['The Man'], + ':firstName': 'Rob', + ':tag': dynogels.Set(['Sports', 'Horror'], 'S') +}; + +BlogPost.update({ title: 'Movie 0', description: 'This is a description' }, params1, function (err, mov) { }); + +//Deleting +Account.destroy('foo@example.com', function (err) { + console.log('account deleted'); +}); + +// Destroy model using hash and range key +BlogPost.destroy('foo@example.com', 'Hello World!', function (err) { + console.log('post deleted') +}); + +BlogPost.destroy({ email: 'foo@example.com', title: 'Another Post' }, function (err) { + console.log('another post deleted') +}); + +Account.destroy('foo@example.com', { ReturnValues: 'ALL_OLD' }, function (err, acc) { + console.log('account deleted'); + console.log('deleted account name', acc.get('name')); +}); + +Account.destroy('foo@example.com', { expected: { age: 22 } }, function (err) { + console.log('account deleted if the age was 22'); +}); + +var params2: dynogels.DestroyItemOptions = {}; +params2.ConditionExpression = '#v = :x'; +params2.ExpressionAttributeNames = { '#v': 'version' }; +params2.ExpressionAttributeValues = { ':x': '2' }; + +Account.destroy({ id: 123 }, params2, function (err, acc) { }); + +//Loading Models from DynamoDB +Account.get('test@example.com', function (err, acc) { + console.log('got account', acc.get('email')); +}); + +Account.get('test@example.com', { ConsistentRead: true }, function (err, acc) { + console.log('got account', acc.get('email')); +}); + +Account.get('test@example.com', { ConsistentRead: true, AttributesToGet: ['name', 'age'] }, function (err, acc) { + console.log('got account', acc.get('email')) + console.log(acc.get('name')); + console.log(acc.get('age')); + console.log(acc.get('email')); // prints null +}); + +BlogPost.get('werner@example.com', 'dynamodb-keeps-getting-better-and-cheaper', function (err, post) { + console.log('loaded post by range and hash key', post.get('content')); +}); + +BlogPost.get({ email: 'werner@example.com', title: 'Expanding the Cloud' }, function (err, post) { + console.log('loded post', post.get('content')); +}); + +BlogPost.get({ id: '123456789' }, { ProjectionExpression: 'email, age, settings.nickname' }, function (err, acc) { }); + +// Query + +var callback = () => { }; +// query for blog posts by werner@example.com +BlogPost + .query('werner@example.com') + .exec(callback); + +// same as above, but load all results +BlogPost + .query('werner@example.com') + .loadAll() + .exec(callback); + +// only load the first 5 posts by werner +BlogPost + .query('werner@example.com') + .limit(5) + .exec(callback); + +// query for posts by werner where the tile begins with 'Expanding' +BlogPost + .query('werner@example.com') + .where('title').beginsWith('Expanding') + .exec(callback); + +// return only the count of documents that begin with the title Expanding +BlogPost + .query('werner@example.com') + .where('title').beginsWith('Expanding') + .select('COUNT') + .exec(callback); + +// query the first 10 posts by werner@example.com but only return +// the title and content from posts where the title starts with 'Expanding' +// WARNING: See notes below on the implementation of limit in DynamoDB +BlogPost + .query('werner@example.com') + .where('title').beginsWith('Expanding') + .attributes(['title', 'content']) + .limit(10) + .exec(callback); + +// sorting by title ascending +BlogPost + .query('werner@example.com') + .ascending() + .exec(callback) + +// sorting by title descending +BlogPost + .query('werner@example.com') + .descending() + .exec(callback) + +// All query options are chainable +BlogPost + .query('werner@example.com') + .where('title').gt('Expanding') + .attributes(['title', 'content']) + .limit(10) + .ascending() + .loadAll() + .exec(callback); + +// Traversing Map Data Types +Account + .query('werner@example.com') + .filter('settings.acceptedTerms').equals(true) + .exec(callback); + +BlogPost + .query('werner@example.com') + .where('title').equals('Expanding') + .exec(); + +// less than equals +BlogPost + .query('werner@example.com') + .where('title').lte('Expanding') + .exec(); + +// less than +BlogPost + .query('werner@example.com') + .where('title').lt('Expanding') + .exec(); + +// greater than +BlogPost + .query('werner@example.com') + .where('title').gt('Expanding') + .exec(); + +// greater than equals +BlogPost + .query('werner@example.com') + .where('title').gte('Expanding') + .exec(); + +// attribute doesn't exist +BlogPost + .query('werner@example.com') + .where('title').null() + .exec(); + +// attribute exists +BlogPost + .query('werner@example.com') + .where('title').exists() + .exec(); + +BlogPost + .query('werner@example.com') + .where('title').beginsWith('Expanding') + .exec(); + +BlogPost + .query('werner@example.com') + .where('title').between('foo@example.com', 'test@example.com') + .exec(); + +BlogPost + .query('werner@example.com') + .where('title').equals('Expanding') + .filter('tags').contains('cloud') + .exec(); + +BlogPost + .query('werner@example.com') + .filterExpression('#title < :t') + .expressionAttributeValues({ ':t': 'Expanding' }) + .expressionAttributeNames({ '#title': 'title' }) + .projectionExpression('#title, tag') + .exec(); + +var GameScore = dynogels.define('GameScore', { + hashKey: 'userId', + rangeKey: 'gameTitle', + schema: { + userId: Joi.string(), + gameTitle: Joi.string(), + topScore: Joi.number(), + topScoreDateTime: Joi.date(), + wins: Joi.number(), + losses: Joi.number() + }, + indexes: [{ + hashKey: 'gameTitle', rangeKey: 'topScore', name: 'GameTitleIndex', type: 'global' + }] +}); + +GameScore + .query('Galaxy Invaders') + .usingIndex('GameTitleIndex') + .descending() + .exec(callback); + +var GameScore = dynogels.define('GameScore', { + hashKey: 'userId', + rangeKey: 'gameTitle', + schema: { + userId: Joi.string(), + gameTitle: Joi.string(), + topScore: Joi.number(), + topScoreDateTime: Joi.date(), + wins: Joi.number(), + losses: Joi.number() + }, + indexes: [{ + hashKey: 'gameTitle', + rangeKey: 'topScore', + name: 'GameTitleIndex', + type: 'global', + projection: { NonKeyAttributes: ['wins'], ProjectionType: 'INCLUDE' } //optional, defaults to ALL + + }] +}); + +GameScore + .query('Galaxy Invaders') + .usingIndex('GameTitleIndex') + .where('topScore').gt(1000) + .descending() + .exec((err, data) => { + + }); + +var BlogPost = dynogels.define('Account', { + hashKey: 'email', + rangeKey: 'title', + schema: { + email: Joi.string().email(), + title: Joi.string(), + content: Joi.binary(), + PublishedDateTime: Joi.date() + }, + + indexes: [{ + hashKey: 'email', rangeKey: 'PublishedDateTime', type: 'local', name: 'PublishedIndex' + }] +}); + +BlogPost + .query('werner@example.com') + .usingIndex('PublishedIndex') + .descending() + .exec(callback); + +BlogPost + .query('werner@example.com') + .usingIndex('PublishedIndex') + .ascending() + .exec(callback); + +BlogPost + .query('werner@example.com') + .usingIndex('PublishedIndex') + .descending() + .loadAll() + .exec(callback); + +// scan all accounts, returning the first page or results +Account.scan().exec(callback); + +// scan all accounts, this time loading all results +// note this will potentially make several calls to DynamoDB +// in order to load all results +Account + .scan() + .loadAll() + .exec(callback); + +// Load 20 accounts +Account + .scan() + .limit(20) + .exec(); + +// Load All accounts, 20 at a time per request +Account + .scan() + .limit(20) + .loadAll() + .exec(); + +// Load accounts which match a filter +// only return email and created attributes +// and return back the consumed capacity the request took +Account + .scan() + .where('email').gte('f@example.com') + .attributes(['email', 'created']) + .returnConsumedCapacity() + .exec(); + +// Load All accounts, if settings.acceptedTerms is true +Account + .scan() + .where('settings.acceptedTerms').equals(true) + .exec(); + +// Returns number of matching accounts, rather than the matching accounts themselves +Account + .scan() + .where('age').gte(21) + .select('COUNT') + .exec(); + +// Start scan using start key +Account + .scan() + .where('age').notNull() + .startKey('foo@example.com') + .exec() + +// equals +Account + .scan() + .where('name').equals('Werner') + .exec(); + +// not equals +Account + .scan() + .where('name').ne('Werner') + .exec(); + +// less than equals +Account + .scan() + .where('name').lte('Werner') + .exec(); + +// less than +Account + .scan() + .where('name').lt('Werner') + .exec(); + +// greater than equals +Account + .scan() + .where('name').gte('Werner') + .exec(); + +// greater than +Account + .scan() + .where('name').gt('Werner') + .exec(); + +// name attribute doesn't exist +Account + .scan() + .where('name').null() + .exec(); + +// name attribute exists +Account + .scan() + .where('name').notNull() + .exec(); + +// contains +Account + .scan() + .where('name').contains('ner') + .exec(); + +// not contains +Account + .scan() + .where('name').notContains('ner') + .exec(); + +// in +Account + .scan() + .where('name').in(['foo@example.com', 'bar@example.com']) + .exec(); + +// begins with +Account + .scan() + .where('name').beginsWith('Werner') + .exec(); + +// between +Account + .scan() + .where('name').between('Bar', 'Foo') + .exec(); + +// multiple filters +Account + .scan() + .where('name').equals('Werner') + .where('age').notNull() + .exec(); + +Account.scan() + .filterExpression('#age BETWEEN :low AND :high AND begins_with(#email, :e)') + .expressionAttributeValues({ ':low': 18, ':high': 22, ':e': 'test1' }) + .expressionAttributeNames({ '#age': 'age', '#email': 'email' }) + .projectionExpression('#age, #email') + .exec(); + +var totalSegments = 8; + +Account.parallelScan(totalSegments) + .where('age').gte(18) + .attributes('age') + .exec(callback); + +// Load All accounts +Account + .parallelScan(totalSegments) + .exec() + +Account.getItems(['foo@example.com', 'bar@example.com', 'test@example.com'], function (err, accounts) { + console.log('loaded ' + accounts.length + ' accounts'); // prints loaded 3 accounts +}); + +// Get both accounts, using a consistent read +Account.getItems(['foo@example.com', 'bar@example.com'], { ConsistentRead: true }, function (err, accounts) { + console.log('loaded ' + accounts.length + ' accounts'); // prints loaded 2 accounts +}); + +//Streaming API + +var stream = Account.parallelScan(4).exec(); + +stream.on('readable', function () { + console.log('single parallel scan response', stream.read()); +}); + +stream.on('end', function () { + console.log('Parallel scan of accounts finished'); +}); + +var querystream = BlogPost.query('werner@dynogels.com').loadAll().exec(); + +querystream.on('readable', function () { + console.log('single query response', stream.read()); +}); + +querystream.on('end', function () { + console.log('query for blog posts finished'); +}); + +//Dynamic Table Names + +var Event = dynogels.define('Event', { + hashKey: 'name', + schema: { + name: Joi.string(), + total: Joi.number() + }, + + // store monthly event data + tableName: function () { + var d = new Date(); + return ['events', d.getFullYear(), d.getMonth() + 1].join('_'); + } +}); + +// Logging + +const accountLogger = { + info: (...args: any[]) => { + + }, + warn: (...args: any[]) => { + + } +} + +dynogels.log = accountLogger; + +var Account = dynogels.define('Account', { + hashKey: 'email', + log: accountLogger +}); // INFO level on account table + +var Account = dynogels.define('Account', { + hashKey : 'email', + + // add the timestamp attributes (updatedAt, createdAt) + timestamps : true, + + schema : { + email : Joi.string().email(), + name : Joi.string().required(), + age : Joi.number(), + } +}); + +Account.create({email: 'test@example.com', name : 'Test Account'}, function (err, acc) { + console.log('created account at', acc.get('created')); // prints created Date + + acc.set({age: 22}); + + acc.update(function (err) { + console.log('updated account age'); + }); + +}); + +// For models with range keys you must pass in objects of hash and range key attributes +var postKey1 = { email: 'test@example.com', title: 'Hello World!' }; +var postKey2 = { email: 'test@example.com', title: 'Another Post' }; + +BlogPost.getItems([postKey1, postKey2], function (err, posts) { + console.log('loaded posts'); +}); + +dynogels.log.info("test", "123", {}); +dynogels.log.warn("test", "123", {}); diff --git a/types/dynogels/index.d.ts b/types/dynogels/index.d.ts index 2e05fb0c61..9772fe33b2 100644 --- a/types/dynogels/index.d.ts +++ b/types/dynogels/index.d.ts @@ -4,29 +4,59 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export import AWS = require("aws-sdk"); +import * as joi from "joi"; import stream = require("stream"); -export namespace log { - function info(...args: any[]): void; - function warn(...args: any[]): void; + +export let log: Log; + +interface Log { + info(...args: any[]): void; + warn(...args: any[]): void; } + export let models: { [key: string]: any }; export function dynamoDriver(dynamoDB: AWS.DynamoDB): AWS.DynamoDB; export function reset(): void; export function define(modelName: string, config: ModelConfiguration): Model; -export function createTables(callback: (err: string) => void): any; +export function createTables(callback: (err: string) => void): void; +export function createTables(options: { [key: string]: CreateTablesOptions } | DynogelsGlobalOptions, callback: (err: string) => void): void; +export function Set(...args: any[]): any; + +type DynogelsGlobalOptions = { + $dynogels: { + pollingInterval: number; + } +}; + +interface CreateTablesOptions { + readCapacity?: number; + writeCapacity?: number; + streamSpecification?: { + streamEnabled: boolean; + streamViewType: string; + }; +} + +export let types: { + stringSet(): joi.AnySchema; + numberSet(): joi.AnySchema; + binarySet(): joi.AnySchema; + uuid(): joi.AnySchema; + timeUUID(): joi.AnySchema; +}; type DynogelsItemCallback = (err: Error, data: Item) => void; export interface Model { new(attrs: { [key: string]: any }): Item; - get(hashKey: any, rangeKey: any, options: AWS.DynamoDB.GetItemInput, callback: DynogelsItemCallback): void; - get(haskKey: any, options: AWS.DynamoDB.GetItemInput, callback: DynogelsItemCallback): void; + get(hashKey: any, rangeKey: any, options: GetItemOptions, callback: DynogelsItemCallback): void; + get(haskKey: any, options: GetItemOptions, callback: DynogelsItemCallback): void; get(hashKey: any, callback: DynogelsItemCallback): void; get(hashKey: any, rangeKey: any, callback: DynogelsItemCallback): void; - create(item: any, options: AWS.DynamoDB.CreateTableInput, callback: DynogelsItemCallback): void; + create(item: any, options: CreateItemOptions, callback: DynogelsItemCallback): void; create(item: any, callback: DynogelsItemCallback): void; - update(item: any, options: AWS.DynamoDB.UpdateItemInput, callback: DynogelsItemCallback): void; + update(item: any, options: UpdateItemOptions, callback: DynogelsItemCallback): void; update(item: any, callback: DynogelsItemCallback): void; destroy(hashKey: any, rangeKey: any, options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; destroy(haskKey: any, options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; @@ -35,19 +65,74 @@ export interface Model { destroy(item: any, options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; destroy(item: any, callback: DynogelsItemCallback): void; query(hashKey: any): Query; - scan(): void; - parallelScan(): void; - getItems(): void; + scan(): Scan; + parallelScan(totalSegments: number): Scan; + getItems(items: string[] | { [key: string]: string }[], callback: (err: Error, items: any[]) => void): void; + getItems(items: string[] | { [key: string]: string }[], options: GetItemOptions, callback: (err: Error, items: any[]) => void): void; batchGetItems(): void; createTable(): void; updateTable(): void; describeTable(): void; - deleteTable(): void; + deleteTable(callback: (err: Error) => void): void; tableName(): void; after(): void; before(): void; - config(): void; + config(config: ModelConfig): void; +} + +interface CreateItemOptions { + expected?: { [key: string]: any }; + overwrite?: boolean; + + Expected?: AWS.DynamoDB.ExpectedAttributeMap; + ReturnValues?: AWS.DynamoDB.ReturnValue; + ReturnConsumedCapacity?: AWS.DynamoDB.ReturnConsumedCapacity; + ReturnItemCollectionMetrics?: AWS.DynamoDB.ReturnItemCollectionMetrics; + ConditionalOperator?: AWS.DynamoDB.ConditionalOperator; + ConditionExpression?: AWS.DynamoDB.ConditionExpression; + ExpressionAttributeNames?: AWS.DynamoDB.ExpressionAttributeNameMap; + ExpressionAttributeValues?: { [key: string]: any }; +} + +interface UpdateItemOptions { + expected?: { [key: string]: any }; + + AttributeUpdates?: AWS.DynamoDB.AttributeUpdates; + Expected?: AWS.DynamoDB.ExpectedAttributeMap; + ConditionalOperator?: AWS.DynamoDB.ConditionalOperator; + ReturnValues?: AWS.DynamoDB.ReturnValue; + ReturnConsumedCapacity?: AWS.DynamoDB.ReturnConsumedCapacity; + ReturnItemCollectionMetrics?: AWS.DynamoDB.ReturnItemCollectionMetrics; + UpdateExpression?: AWS.DynamoDB.UpdateExpression; + ConditionExpression?: AWS.DynamoDB.ConditionExpression; + ExpressionAttributeNames?: AWS.DynamoDB.ExpressionAttributeNameMap; + ExpressionAttributeValues?: { [key: string]: any }; +} + +interface DestroyItemOptions { + Expected?: AWS.DynamoDB.ExpectedAttributeMap; + ConditionalOperator?: AWS.DynamoDB.ConditionalOperator; + ReturnValues?: AWS.DynamoDB.ReturnValue; + ReturnConsumedCapacity?: AWS.DynamoDB.ReturnConsumedCapacity; + ReturnItemCollectionMetrics?: AWS.DynamoDB.ReturnItemCollectionMetrics; + ConditionExpression?: AWS.DynamoDB.ConditionExpression; + ExpressionAttributeNames?: AWS.DynamoDB.ExpressionAttributeNameMap; + ExpressionAttributeValues?: { [key: string]: any }; +} + +interface GetItemOptions { + AttributesToGet?: AWS.DynamoDB.AttributeNameList; + ConsistentRead?: AWS.DynamoDB.ConsistentRead; + ReturnConsumedCapacity?: AWS.DynamoDB.ReturnConsumedCapacity; + ProjectionExpression?: AWS.DynamoDB.ProjectionExpression; + ExpressionAttributeNames?: AWS.DynamoDB.ExpressionAttributeNameMap; +} + +interface ModelConfig { + tableName?: string; + docClient?: any; + dynamodb?: AWS.DynamoDB; } export interface Item { @@ -86,6 +171,8 @@ export interface Query { lt(value: any): Query; gte(value: any): Query; gt(value: any): Query; + null(): Query; + exists(): Query; beginsWith(value: any): Query; between(value1: any, value2: any): Query; }; @@ -106,15 +193,16 @@ export interface Query { between(value1: any, value2: any): Query; }; exec(): stream.Readable; - exec(callback: () => void): void; + exec(callback: (err: Error, data: any) => void): void; } export interface Scan { limit(number: number): Scan; addFilterCondition(condition: any): Scan; - startKey(hashKey: any, rangeKey: any): Scan; + startKey(hashKey: any, rangeKey?: any): Scan; attributes(attrs: any): Scan; select(value: any): Scan; + returnConsumedCapacity(): Scan; segments(segment: any, totalSegments: number): Scan; where(keyName: string): { equals(value: any): Scan; @@ -131,26 +219,32 @@ export interface Scan { in(values: any[]): Scan; beginsWith(value: any): Scan; between(value1: any, value2: any): Scan; + notNull(): Scan; }; filterExpression(expression: any): Scan; expressionAttributeNames(data: any): Scan; expressionAttributeValues(data: any): Scan; projectionExpression(data: any): Scan; exec(): stream.Readable; - exec(callback: () => void): void; + exec(callback: (err: Error, data: any) => void): void; loadAll(): Scan; } type tableResolve = () => string; +type schemaType = { [key: string]: joi.AnySchema | schemaType }; + export interface ModelConfiguration { hashKey: string, rangeKey?: string, timestamps?: boolean, createdAt?: boolean, - updatedAtField?: string, - schema: { [key: string]: any }, + updatedAt?: string, + schema?: schemaType, + validation?: joi.ValidationOptions, tableName?: string | tableResolve; + indexes?: any[]; + log?: Log; } interface Document { [key: string]: any; From 904f3cc6c6780b9c07c960abb67b8f674b0916f1 Mon Sep 17 00:00:00 2001 From: Thomas Chandelle Date: Sun, 12 Nov 2017 14:48:44 +0100 Subject: [PATCH 137/495] Add labelColor and labelTextColor in tooltip callbacks --- types/chart.js/index.d.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index 54e9f4ddda..51bbc3b49e 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Chart.js 2.6 +// Type definitions for Chart.js 2.7 // Project: https://github.com/nnnick/Chart.js // Definitions by: Alberto Nuti // Fabien Lavocat @@ -114,6 +114,11 @@ declare namespace Chart { index?: number; } + interface ChartTooltipLabelColor { + borderColor: ChartColor; + backgroundColor: ChartColor; + } + interface ChartTooltipCallback { beforeTitle?(item?: ChartTooltipItem[], data?: ChartData): string | string[]; title?(item?: ChartTooltipItem[], data?: ChartData): string | string[]; @@ -121,6 +126,8 @@ declare namespace Chart { beforeBody?(item?: ChartTooltipItem[], data?: ChartData): string | string[]; beforeLabel?(tooltipItem?: ChartTooltipItem, data?: ChartData): string | string[]; label?(tooltipItem?: ChartTooltipItem, data?: ChartData): string | string[]; + labelColor?(tooltipItem?: ChartTooltipItem, chart?: Chart): ChartTooltipLabelColor; + labelTextColor?(tooltipItem?: ChartTooltipItem, chart?: Chart): string; afterLabel?(tooltipItem?: ChartTooltipItem, data?: ChartData): string | string[]; afterBody?(item?: ChartTooltipItem[], data?: ChartData): string | string[]; beforeFooter?(item?: ChartTooltipItem[], data?: ChartData): string | string[]; From 10039c9342c25ac1409049e45fd51b2f618a8bc4 Mon Sep 17 00:00:00 2001 From: Evan Moran Date: Sun, 12 Nov 2017 09:56:29 -0500 Subject: [PATCH 138/495] Added some more typings. Think it's done except for event emitter stuff --- types/dynogels/dynogels-tests.ts | 29 ++++---- types/dynogels/index.d.ts | 110 +++++++++++++++++-------------- 2 files changed, 76 insertions(+), 63 deletions(-) diff --git a/types/dynogels/dynogels-tests.ts b/types/dynogels/dynogels-tests.ts index 756977d066..72d9e5e0f4 100644 --- a/types/dynogels/dynogels-tests.ts +++ b/types/dynogels/dynogels-tests.ts @@ -8,7 +8,6 @@ dynogels.AWS.config.loadFromPath('credentials.json'); dynogels.AWS.config.update({ region: "REGION" }); //Define a Model - var Account = dynogels.define('Account', { hashKey: 'email', @@ -805,26 +804,26 @@ var Account = dynogels.define('Account', { }); // INFO level on account table var Account = dynogels.define('Account', { - hashKey : 'email', + hashKey: 'email', - // add the timestamp attributes (updatedAt, createdAt) - timestamps : true, + // add the timestamp attributes (updatedAt, createdAt) + timestamps: true, - schema : { - email : Joi.string().email(), - name : Joi.string().required(), - age : Joi.number(), - } + schema: { + email: Joi.string().email(), + name: Joi.string().required(), + age: Joi.number(), + } }); -Account.create({email: 'test@example.com', name : 'Test Account'}, function (err, acc) { - console.log('created account at', acc.get('created')); // prints created Date +Account.create({ email: 'test@example.com', name: 'Test Account' }, function (err, acc) { + console.log('created account at', acc.get('created')); // prints created Date - acc.set({age: 22}); + acc.set({ age: 22 }); - acc.update(function (err) { - console.log('updated account age'); - }); + acc.update(function (err) { + console.log('updated account age'); + }); }); diff --git a/types/dynogels/index.d.ts b/types/dynogels/index.d.ts index 9772fe33b2..b62098ec2c 100644 --- a/types/dynogels/index.d.ts +++ b/types/dynogels/index.d.ts @@ -7,36 +7,9 @@ export import AWS = require("aws-sdk"); import * as joi from "joi"; import stream = require("stream"); +// Dynogels Data Members export let log: Log; - -interface Log { - info(...args: any[]): void; - warn(...args: any[]): void; -} - -export let models: { [key: string]: any }; -export function dynamoDriver(dynamoDB: AWS.DynamoDB): AWS.DynamoDB; -export function reset(): void; -export function define(modelName: string, config: ModelConfiguration): Model; -export function createTables(callback: (err: string) => void): void; -export function createTables(options: { [key: string]: CreateTablesOptions } | DynogelsGlobalOptions, callback: (err: string) => void): void; -export function Set(...args: any[]): any; - -type DynogelsGlobalOptions = { - $dynogels: { - pollingInterval: number; - } -}; - -interface CreateTablesOptions { - readCapacity?: number; - writeCapacity?: number; - streamSpecification?: { - streamEnabled: boolean; - streamViewType: string; - }; -} - +export let models: { [key: string]: Model }; export let types: { stringSet(): joi.AnySchema; numberSet(): joi.AnySchema; @@ -45,8 +18,35 @@ export let types: { timeUUID(): joi.AnySchema; }; -type DynogelsItemCallback = (err: Error, data: Item) => void; +export interface Log { + info(...args: any[]): void; + warn(...args: any[]): void; +} +//Dynogels global functions +export function dynamoDriver(dynamoDB: AWS.DynamoDB): AWS.DynamoDB; +export function reset(): void; +export function define(modelName: string, config: ModelConfiguration): Model; +export function createTables(callback: (err: string) => void): void; +export function createTables(options: { [key: string]: CreateTablesOptions } | DynogelsGlobalOptions, callback: (err: string) => void): void; +export function Set(...args: any[]): any; + +export interface DynogelsGlobalOptions { + $dynogels: { + pollingInterval: number; + } +} + +export interface CreateTablesOptions { + readCapacity?: number; + writeCapacity?: number; + streamSpecification?: { + streamEnabled: boolean; + streamViewType: string; + }; +} + +//Dynogels Model export interface Model { new(attrs: { [key: string]: any }): Item; @@ -58,30 +58,40 @@ export interface Model { create(item: any, callback: DynogelsItemCallback): void; update(item: any, options: UpdateItemOptions, callback: DynogelsItemCallback): void; update(item: any, callback: DynogelsItemCallback): void; - destroy(hashKey: any, rangeKey: any, options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; - destroy(haskKey: any, options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; + destroy(hashKey: any, rangeKey: any, options: DestroyItemOptions, callback: DynogelsItemCallback): void; + destroy(haskKey: any, options: DestroyItemOptions, callback: DynogelsItemCallback): void; destroy(hashKey: any, callback: DynogelsItemCallback): void; destroy(hashKey: any, rangeKey: any, callback: DynogelsItemCallback): void; - destroy(item: any, options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; + destroy(item: any, options: DestroyItemOptions, callback: DynogelsItemCallback): void; destroy(item: any, callback: DynogelsItemCallback): void; query(hashKey: any): Query; scan(): Scan; parallelScan(totalSegments: number): Scan; getItems(items: string[] | { [key: string]: string }[], callback: (err: Error, items: any[]) => void): void; getItems(items: string[] | { [key: string]: string }[], options: GetItemOptions, callback: (err: Error, items: any[]) => void): void; - batchGetItems(): void; - createTable(): void; - updateTable(): void; - describeTable(): void; + batchGetItems(items: string[] | { [key: string]: string }[], callback: (err: Error, items: any[]) => void): void; + batchGetItems(items: string[] | { [key: string]: string }[], options: GetItemOptions, callback: (err: Error, items: any[]) => void): void; + createTable(options: { [key: string]: CreateTablesOptions } | DynogelsGlobalOptions, callback: (err: Error, data: AWS.DynamoDB.CreateTableOutput) => void): void; + createTable(callback: (err: Error, data: AWS.DynamoDB.CreateTableOutput) => void): void; + updateTable(throughput: Throughput, callback: (err: Error, data: AWS.DynamoDB.UpdateTableOutput) => void): void; + updateTable(callback: (err: Error, data: AWS.DynamoDB.UpdateTableOutput) => void): void; + describeTable(callback: (err: Error, data: AWS.DynamoDB.DescribeTableOutput) => void): void; deleteTable(callback: (err: Error) => void): void; - tableName(): void; + tableName(): string; after(): void; before(): void; - config(config: ModelConfig): void; + config(config: ModelConfig): { name: string }; } -interface CreateItemOptions { +type DynogelsItemCallback = (err: Error, data: Item) => void; + +export interface Throughput { + readCapacity: number; + writeCapacity: number; +} + +export interface CreateItemOptions { expected?: { [key: string]: any }; overwrite?: boolean; @@ -95,7 +105,7 @@ interface CreateItemOptions { ExpressionAttributeValues?: { [key: string]: any }; } -interface UpdateItemOptions { +export interface UpdateItemOptions { expected?: { [key: string]: any }; AttributeUpdates?: AWS.DynamoDB.AttributeUpdates; @@ -110,7 +120,7 @@ interface UpdateItemOptions { ExpressionAttributeValues?: { [key: string]: any }; } -interface DestroyItemOptions { +export interface DestroyItemOptions { Expected?: AWS.DynamoDB.ExpectedAttributeMap; ConditionalOperator?: AWS.DynamoDB.ConditionalOperator; ReturnValues?: AWS.DynamoDB.ReturnValue; @@ -121,7 +131,7 @@ interface DestroyItemOptions { ExpressionAttributeValues?: { [key: string]: any }; } -interface GetItemOptions { +export interface GetItemOptions { AttributesToGet?: AWS.DynamoDB.AttributeNameList; ConsistentRead?: AWS.DynamoDB.ConsistentRead; ReturnConsumedCapacity?: AWS.DynamoDB.ReturnConsumedCapacity; @@ -129,24 +139,26 @@ interface GetItemOptions { ExpressionAttributeNames?: AWS.DynamoDB.ExpressionAttributeNameMap; } -interface ModelConfig { +export interface ModelConfig { tableName?: string; docClient?: any; dynamodb?: AWS.DynamoDB; } +//Dynogels Item export interface Item { get(key: string): { [key: string]: any }; - set(params: {}): void; + set(params: {}): Item; save(callback: DynogelsItemCallback): void; - update(options: AWS.DynamoDB.UpdateItemInput, callback: DynogelsItemCallback): void; + update(options: UpdateItemOptions, callback: DynogelsItemCallback): void; update(callback: DynogelsItemCallback): void; - destroy(options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; + destroy(options: DestroyItemOptions, callback: DynogelsItemCallback): void; destroy(callback: DynogelsItemCallback): void; toJSON(): any; toPlainObject(): any; } +//Dynogels Query export interface Query { limit(number: number): Query; filterExpression(expression: any): Query; @@ -196,6 +208,7 @@ export interface Query { exec(callback: (err: Error, data: any) => void): void; } +//Dynogels Scan export interface Scan { limit(number: number): Scan; addFilterCondition(condition: any): Scan; @@ -246,7 +259,8 @@ export interface ModelConfiguration { indexes?: any[]; log?: Log; } -interface Document { + +export interface Document { [key: string]: any; } From b616961d2704336d3162230d326f139fd90730b7 Mon Sep 17 00:00:00 2001 From: Evan Moran Date: Sun, 12 Nov 2017 10:06:19 -0500 Subject: [PATCH 139/495] Updated github name --- types/dynogels/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/dynogels/index.d.ts b/types/dynogels/index.d.ts index b62098ec2c..80ad3d26e4 100644 --- a/types/dynogels/index.d.ts +++ b/types/dynogels/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for dynogels 8.0 // Project: https://github.com/clarkie/dynogels#readme -// Definitions by: My Self +// Definitions by: Spartan Labs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export import AWS = require("aws-sdk"); From 08d7674c3e68e572c78476ec7fa48f0a9f7c20cc Mon Sep 17 00:00:00 2001 From: Evan Moran Date: Sat, 11 Nov 2017 10:47:23 -0500 Subject: [PATCH 140/495] Initial dynogels changes. More to come --- types/dynogels/dynogels-tests.ts | 30 ++++++ types/dynogels/index.d.ts | 163 +++++++++++++++++++++++++++++++ types/dynogels/package.json | 7 ++ types/dynogels/tsconfig.json | 24 +++++ types/dynogels/tslint.json | 1 + 5 files changed, 225 insertions(+) create mode 100644 types/dynogels/dynogels-tests.ts create mode 100644 types/dynogels/index.d.ts create mode 100644 types/dynogels/package.json create mode 100644 types/dynogels/tsconfig.json create mode 100644 types/dynogels/tslint.json diff --git a/types/dynogels/dynogels-tests.ts b/types/dynogels/dynogels-tests.ts new file mode 100644 index 0000000000..90e8184900 --- /dev/null +++ b/types/dynogels/dynogels-tests.ts @@ -0,0 +1,30 @@ +/// +import * as dynogels from "dynogels"; +import { DynamoDB } from "aws-sdk"; +dynogels.AWS; + +dynogels.log.info("test", "123", {}); +dynogels.log.warn("test", "123", {}); + +var dynamoDb = new DynamoDB(); +dynamoDb.getItem() +dynogels.dynamoDriver(dynamoDb); +dynogels.reset(); +var model = dynogels.define("asdfas", { + hashKey: "Asdf", schema: { + + } +}); + +let a = new model({ test: 12312 }); + + +model.get("asdfas,", (err, test) => { + +}); + +model.create({}, (err, data) => { + var a = data.get("hello"); + a.asdfs = 1; + data.set({ test: "12312" }); +}) diff --git a/types/dynogels/index.d.ts b/types/dynogels/index.d.ts new file mode 100644 index 0000000000..2e05fb0c61 --- /dev/null +++ b/types/dynogels/index.d.ts @@ -0,0 +1,163 @@ +// Type definitions for dynogels 8.0 +// Project: https://github.com/clarkie/dynogels#readme +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export import AWS = require("aws-sdk"); +import stream = require("stream"); +export namespace log { + function info(...args: any[]): void; + function warn(...args: any[]): void; +} +export let models: { [key: string]: any }; +export function dynamoDriver(dynamoDB: AWS.DynamoDB): AWS.DynamoDB; +export function reset(): void; +export function define(modelName: string, config: ModelConfiguration): Model; +export function createTables(callback: (err: string) => void): any; + +type DynogelsItemCallback = (err: Error, data: Item) => void; + +export interface Model { + new(attrs: { [key: string]: any }): Item; + + get(hashKey: any, rangeKey: any, options: AWS.DynamoDB.GetItemInput, callback: DynogelsItemCallback): void; + get(haskKey: any, options: AWS.DynamoDB.GetItemInput, callback: DynogelsItemCallback): void; + get(hashKey: any, callback: DynogelsItemCallback): void; + get(hashKey: any, rangeKey: any, callback: DynogelsItemCallback): void; + create(item: any, options: AWS.DynamoDB.CreateTableInput, callback: DynogelsItemCallback): void; + create(item: any, callback: DynogelsItemCallback): void; + update(item: any, options: AWS.DynamoDB.UpdateItemInput, callback: DynogelsItemCallback): void; + update(item: any, callback: DynogelsItemCallback): void; + destroy(hashKey: any, rangeKey: any, options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; + destroy(haskKey: any, options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; + destroy(hashKey: any, callback: DynogelsItemCallback): void; + destroy(hashKey: any, rangeKey: any, callback: DynogelsItemCallback): void; + destroy(item: any, options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; + destroy(item: any, callback: DynogelsItemCallback): void; + query(hashKey: any): Query; + scan(): void; + parallelScan(): void; + getItems(): void; + batchGetItems(): void; + createTable(): void; + updateTable(): void; + describeTable(): void; + deleteTable(): void; + tableName(): void; + + after(): void; + before(): void; + config(): void; +} + +export interface Item { + get(key: string): { [key: string]: any }; + set(params: {}): void; + save(callback: DynogelsItemCallback): void; + update(options: AWS.DynamoDB.UpdateItemInput, callback: DynogelsItemCallback): void; + update(callback: DynogelsItemCallback): void; + destroy(options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; + destroy(callback: DynogelsItemCallback): void; + toJSON(): any; + toPlainObject(): any; +} + +export interface Query { + limit(number: number): Query; + filterExpression(expression: any): Query; + expressionAttributeNames(data: any): Query; + expressionAttributeValues(data: any): Query; + projectionExpression(data: any): Query; + usingIndex(name: string): Query; + consistentRead(read: boolean): Query; + addKeyCondition(condition: any): Query; + addFilterCondition(condition: any): Query; + startKey(hashKey: any, rangeKey: any): Query; + attributes(attrs: any): Query; + ascending(): Query; + descending(): Query; + select(value: any): Query; + returnConsumedCapacity(value: any): Query; + loadAll(): Query; + where(keyName: string): { + equals(value: any): Query; + eq(value: any): Query; + lte(value: any): Query; + lt(value: any): Query; + gte(value: any): Query; + gt(value: any): Query; + beginsWith(value: any): Query; + between(value1: any, value2: any): Query; + }; + filter(keyName: string): { + equals(value: any): Query; + eq(value: any): Query; + ne(value: any): Query; + lte(value: any): Query; + lt(value: any): Query; + gte(value: any): Query; + gt(value: any): Query; + null(): Query; + exists(): Query; + contains(value: any): Query; + notContains(value: any): Query; + in(values: any[]): Query; + beginsWith(value: any): Query; + between(value1: any, value2: any): Query; + }; + exec(): stream.Readable; + exec(callback: () => void): void; +} + +export interface Scan { + limit(number: number): Scan; + addFilterCondition(condition: any): Scan; + startKey(hashKey: any, rangeKey: any): Scan; + attributes(attrs: any): Scan; + select(value: any): Scan; + segments(segment: any, totalSegments: number): Scan; + where(keyName: string): { + equals(value: any): Scan; + eq(value: any): Scan; + ne(value: any): Scan; + lte(value: any): Scan; + lt(value: any): Scan; + gte(value: any): Scan; + gt(value: any): Scan; + null(): Scan; + exists(): Scan; + contains(value: any): Scan; + notContains(value: any): Scan; + in(values: any[]): Scan; + beginsWith(value: any): Scan; + between(value1: any, value2: any): Scan; + }; + filterExpression(expression: any): Scan; + expressionAttributeNames(data: any): Scan; + expressionAttributeValues(data: any): Scan; + projectionExpression(data: any): Scan; + exec(): stream.Readable; + exec(callback: () => void): void; + loadAll(): Scan; +} + +type tableResolve = () => string; + +export interface ModelConfiguration { + hashKey: string, + rangeKey?: string, + timestamps?: boolean, + createdAt?: boolean, + updatedAtField?: string, + schema: { [key: string]: any }, + tableName?: string | tableResolve; +} +interface Document { + [key: string]: any; +} + +export interface DocumentCollection { + Items: Document[], + Count: number, + ScannedCount: number +} diff --git a/types/dynogels/package.json b/types/dynogels/package.json new file mode 100644 index 0000000000..903b5d2531 --- /dev/null +++ b/types/dynogels/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "dependencies": { + "@types/node": "^8.0.51", + "aws-sdk": "^2.58.0" + } +} \ No newline at end of file diff --git a/types/dynogels/tsconfig.json b/types/dynogels/tsconfig.json new file mode 100644 index 0000000000..9b5f6a4e52 --- /dev/null +++ b/types/dynogels/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [ + "node" + ], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dynogels-tests.ts" + ] +} \ No newline at end of file diff --git a/types/dynogels/tslint.json b/types/dynogels/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dynogels/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From afb9a5f9d3cffb04430ce93064dc95f9efdf31b8 Mon Sep 17 00:00:00 2001 From: Evan Moran Date: Sat, 11 Nov 2017 23:54:48 -0500 Subject: [PATCH 141/495] Added all examples from documentation for testing/added more typings --- types/dynogels/dynogels-tests.ts | 844 ++++++++++++++++++++++++++++++- types/dynogels/index.d.ts | 130 ++++- 2 files changed, 939 insertions(+), 35 deletions(-) diff --git a/types/dynogels/dynogels-tests.ts b/types/dynogels/dynogels-tests.ts index 90e8184900..756977d066 100644 --- a/types/dynogels/dynogels-tests.ts +++ b/types/dynogels/dynogels-tests.ts @@ -1,30 +1,840 @@ /// -import * as dynogels from "dynogels"; +import dynogels = require("dynogels"); import { DynamoDB } from "aws-sdk"; -dynogels.AWS; +import * as Joi from "joi"; -dynogels.log.info("test", "123", {}); -dynogels.log.warn("test", "123", {}); +//AWS Configs +dynogels.AWS.config.loadFromPath('credentials.json'); +dynogels.AWS.config.update({ region: "REGION" }); -var dynamoDb = new DynamoDB(); -dynamoDb.getItem() -dynogels.dynamoDriver(dynamoDb); -dynogels.reset(); -var model = dynogels.define("asdfas", { - hashKey: "Asdf", schema: { +//Define a Model +var Account = dynogels.define('Account', { + hashKey: 'email', + + // add the timestamp attributes (updatedAt, createdAt) + timestamps: true, + + schema: { + email: Joi.string().email(), + name: Joi.string(), + age: Joi.number(), + roles: dynogels.types.stringSet(), + settings: { + nickname: Joi.string(), + acceptedTerms: Joi.boolean().default(false), + test: { + evan: Joi.string() + } + } } }); -let a = new model({ test: 12312 }); +var BlogPost = dynogels.define('BlogPost', { + hashKey: 'email', + rangeKey: 'title', + schema: { + email: Joi.string().email(), + title: Joi.string(), + content: Joi.binary(), + tags: dynogels.types.stringSet(), + } +}); +var BlogPost = dynogels.define('BlogPost', { + hashKey: 'email', + rangeKey: 'title', + schema: { + email: Joi.string().email(), + title: Joi.string() + }, + validation: { + // allow properties not defined in the schema + allowUnknown: true + } +}); -model.get("asdfas,", (err, test) => { +//Create Tables +dynogels.createTables(function (err) { + if (err) { + console.log('Error creating tables: ', err); + } else { + console.log('Tables has been created'); + } +}); + +dynogels.createTables({ + 'BlogPost': { readCapacity: 5, writeCapacity: 10 }, + 'Account': { + readCapacity: 20, + writeCapacity: 4, + streamSpecification: { + streamEnabled: true, + streamViewType: 'NEW_IMAGE' + } + } +}, function (err) { + if (err) { + console.log('Error creating tables: ', err); + } else { + console.log('Tables has been created'); + } +}); + +dynogels.createTables({ + $dynogels: { pollingInterval: 100 } +}, function (err) { + if (err) { + console.log('Error creating tables: ', err); + } else { + console.log('Tables has been created'); + } +}); + +// Delete Table +BlogPost.deleteTable(function (err) { + if (err) { + console.log('Error deleting table: ', err); + } else { + console.log('Table has been deleted'); + } +}); + +//UUID +var Tweet = dynogels.define('Tweet', { + hashKey: 'TweetID', + timestamps: true, + schema: { + TweetID: dynogels.types.uuid(), + content: Joi.string(), + } +}); + +//Configuration +var Account = dynogels.define('Account', { + hashKey: 'email', + + // add the timestamp attributes (updatedAt, createdAt) + timestamps: true, + + schema: { + email: Joi.string().email(), + } +}); + +var Account = dynogels.define('Account', { + hashKey: 'email', + + // enable timestamps support + timestamps: true, + + // I don't want createdAt + createdAt: false, + + // I want updatedAt to actually be called updateTimestamp + updatedAt: 'updateTimestamp', + + schema: { + email: Joi.string().email(), + } +}); + +var Event = dynogels.define('Event', { + hashKey: 'name', + schema: { + name: Joi.string(), + total: Joi.number() + }, + + tableName: 'deviceEvents' +}); + +var Event = dynogels.define('Event', { + hashKey: 'name', + schema: { + name: Joi.string(), + total: Joi.number() + }, + + // store monthly event data + tableName: function () { + var d = new Date(); + return ['events', d.getFullYear(), d.getMonth() + 1].join('_'); + } +}); + +Account.config({ tableName: 'AccountsTable' }); + +var dynamodb = new DynamoDB(); +Account.config({ dynamodb: dynamodb }); + +// or globally use custom DynamoDB instance +// all defined models will now use this driver +dynogels.dynamoDriver(dynamodb); + +// Saving Models To DynamoDB +Account.create({ email: 'foo@example.com', name: 'Foo Bar', age: 21 }, function (err, acc) { + console.log('created account in DynamoDB', acc.get('email')); +}); + +var acc = new Account({ email: 'test@example.com', name: 'Test Example' }); +acc.save(function (err) { + console.log('created account in DynamoDB', acc.get('email')); +}); + +BlogPost.create({ + email: 'werner@example.com', + title: 'Expanding the Cloud', + content: 'Today, we are excited to announce the limited preview...' +}, function (err, post) { + console.log('created blog post', post.get('title')); +}); + +var item1 = { email: 'foo1@example.com', name: 'Foo 1', age: 10 }; +var item2 = { email: 'foo2@example.com', name: 'Foo 2', age: 20 }; +var item3 = { email: 'foo3@example.com', name: 'Foo 3', age: 30 }; + +Account.create([item1, item2, item3], function (err, accounts) { + console.log('created 3 accounts in DynamoDB', accounts); +}); + +var params: dynogels.CreateItemOptions = { + +}; +params.ConditionExpression = '#i <> :x'; +params.ExpressionAttributeNames = { '#i': 'id' }; +params.ExpressionAttributeValues = { ':x': 123 }; + +Account.create({ id: 123, name: 'Kurt Warner' }, params, function (error, acc) { }); -model.create({}, (err, data) => { - var a = data.get("hello"); - a.asdfs = 1; - data.set({ test: "12312" }); -}) +// setting overwrite to false will generate +// the same Condition Expression as in the previous example +Account.create({ id: 123, name: 'Kurt Warner' }, { overwrite: false }, function (error, acc) { }); + +// Updating +Account.update({ email: 'foo@example.com', name: 'Bar Tester' }, function (err, acc) { + console.log('update account', acc.get('name')); +}); + +Account.update({ email: 'foo@example.com', name: 'Bar Tester' }, { ReturnValues: 'ALL_OLD' }, function (err, acc) { + console.log('update account', acc.get('name')); // prints the old account name +}); + +// Only update the account if the current age of the account is 22 +Account.update({ email: 'foo@example.com', name: 'Bar Tester' }, { expected: { age: 22 } }, function (err, acc) { + console.log('update account', acc.get('name')); +}); + +// setting an attribute to null will delete the attribute from DynamoDB +Account.update({ email: 'foo@example.com', age: null }, function (err, acc) { + console.log('update account', acc.get('age')); // prints null +}); + +Account.update( + { email: 'foo@example.com', name: 'FooBar Testers' }, + { expected: { email: { Exists: true } } }, + (err, acc) => { + console.log(acc.get('name')); // FooBar Testers + } +); + +Account.update( + { email: 'baz@example.com', name: 'Bar Tester' }, + { expected: { email: { Exists: true } } }, + (err, acc) => { + console.log(err); // Condition Expression failed: no Account with that hash key + } +); + +Account.update({ email: 'foo@example.com', age: { $add: 1 } }, function (err, acc) { + console.log('incremented age by 1', acc.get('age')); +}); + +BlogPost.update({ + email: 'werner@example.com', + title: 'Expanding the Cloud', + tags: { $add: 'cloud' } +}, function (err, post) { + console.log('added single tag to blog post', post.get('tags')); +}); + +BlogPost.update({ + email: 'werner@example.com', + title: 'Expanding the Cloud', + tags: { $add: ['cloud', 'dynamodb'] } +}, function (err, post) { + console.log('added tags to blog post', post.get('tags')); +}); + +BlogPost.update({ + email: 'werner@example.com', + title: 'Expanding the Cloud', + tags: { $del: 'cloud' } +}, function (err, post) { + console.log('removed cloud tag from blog post', post.get('tags')); +}); + +BlogPost.update({ + email: 'werner@example.com', + title: 'Expanding the Cloud', + tags: { $del: ['aws', 'node'] } +}, function (err, post) { + console.log('removed multiple tags', post.get('tags')); +}); + +var params1: dynogels.UpdateItemOptions = {}; +params1.UpdateExpression = 'SET #year = #year + :inc, #dir.titles = list_append(#dir.titles, :title), #act[0].firstName = :firstName ADD tags :tag'; +params1.ConditionExpression = '#year = :current'; +params1.ExpressionAttributeNames = { + '#year': 'releaseYear', + '#dir': 'director', + '#act': 'actors' +}; + +params1.ExpressionAttributeValues = { + ':inc': 1, + ':current': 2001, + ':title': ['The Man'], + ':firstName': 'Rob', + ':tag': dynogels.Set(['Sports', 'Horror'], 'S') +}; + +BlogPost.update({ title: 'Movie 0', description: 'This is a description' }, params1, function (err, mov) { }); + +//Deleting +Account.destroy('foo@example.com', function (err) { + console.log('account deleted'); +}); + +// Destroy model using hash and range key +BlogPost.destroy('foo@example.com', 'Hello World!', function (err) { + console.log('post deleted') +}); + +BlogPost.destroy({ email: 'foo@example.com', title: 'Another Post' }, function (err) { + console.log('another post deleted') +}); + +Account.destroy('foo@example.com', { ReturnValues: 'ALL_OLD' }, function (err, acc) { + console.log('account deleted'); + console.log('deleted account name', acc.get('name')); +}); + +Account.destroy('foo@example.com', { expected: { age: 22 } }, function (err) { + console.log('account deleted if the age was 22'); +}); + +var params2: dynogels.DestroyItemOptions = {}; +params2.ConditionExpression = '#v = :x'; +params2.ExpressionAttributeNames = { '#v': 'version' }; +params2.ExpressionAttributeValues = { ':x': '2' }; + +Account.destroy({ id: 123 }, params2, function (err, acc) { }); + +//Loading Models from DynamoDB +Account.get('test@example.com', function (err, acc) { + console.log('got account', acc.get('email')); +}); + +Account.get('test@example.com', { ConsistentRead: true }, function (err, acc) { + console.log('got account', acc.get('email')); +}); + +Account.get('test@example.com', { ConsistentRead: true, AttributesToGet: ['name', 'age'] }, function (err, acc) { + console.log('got account', acc.get('email')) + console.log(acc.get('name')); + console.log(acc.get('age')); + console.log(acc.get('email')); // prints null +}); + +BlogPost.get('werner@example.com', 'dynamodb-keeps-getting-better-and-cheaper', function (err, post) { + console.log('loaded post by range and hash key', post.get('content')); +}); + +BlogPost.get({ email: 'werner@example.com', title: 'Expanding the Cloud' }, function (err, post) { + console.log('loded post', post.get('content')); +}); + +BlogPost.get({ id: '123456789' }, { ProjectionExpression: 'email, age, settings.nickname' }, function (err, acc) { }); + +// Query + +var callback = () => { }; +// query for blog posts by werner@example.com +BlogPost + .query('werner@example.com') + .exec(callback); + +// same as above, but load all results +BlogPost + .query('werner@example.com') + .loadAll() + .exec(callback); + +// only load the first 5 posts by werner +BlogPost + .query('werner@example.com') + .limit(5) + .exec(callback); + +// query for posts by werner where the tile begins with 'Expanding' +BlogPost + .query('werner@example.com') + .where('title').beginsWith('Expanding') + .exec(callback); + +// return only the count of documents that begin with the title Expanding +BlogPost + .query('werner@example.com') + .where('title').beginsWith('Expanding') + .select('COUNT') + .exec(callback); + +// query the first 10 posts by werner@example.com but only return +// the title and content from posts where the title starts with 'Expanding' +// WARNING: See notes below on the implementation of limit in DynamoDB +BlogPost + .query('werner@example.com') + .where('title').beginsWith('Expanding') + .attributes(['title', 'content']) + .limit(10) + .exec(callback); + +// sorting by title ascending +BlogPost + .query('werner@example.com') + .ascending() + .exec(callback) + +// sorting by title descending +BlogPost + .query('werner@example.com') + .descending() + .exec(callback) + +// All query options are chainable +BlogPost + .query('werner@example.com') + .where('title').gt('Expanding') + .attributes(['title', 'content']) + .limit(10) + .ascending() + .loadAll() + .exec(callback); + +// Traversing Map Data Types +Account + .query('werner@example.com') + .filter('settings.acceptedTerms').equals(true) + .exec(callback); + +BlogPost + .query('werner@example.com') + .where('title').equals('Expanding') + .exec(); + +// less than equals +BlogPost + .query('werner@example.com') + .where('title').lte('Expanding') + .exec(); + +// less than +BlogPost + .query('werner@example.com') + .where('title').lt('Expanding') + .exec(); + +// greater than +BlogPost + .query('werner@example.com') + .where('title').gt('Expanding') + .exec(); + +// greater than equals +BlogPost + .query('werner@example.com') + .where('title').gte('Expanding') + .exec(); + +// attribute doesn't exist +BlogPost + .query('werner@example.com') + .where('title').null() + .exec(); + +// attribute exists +BlogPost + .query('werner@example.com') + .where('title').exists() + .exec(); + +BlogPost + .query('werner@example.com') + .where('title').beginsWith('Expanding') + .exec(); + +BlogPost + .query('werner@example.com') + .where('title').between('foo@example.com', 'test@example.com') + .exec(); + +BlogPost + .query('werner@example.com') + .where('title').equals('Expanding') + .filter('tags').contains('cloud') + .exec(); + +BlogPost + .query('werner@example.com') + .filterExpression('#title < :t') + .expressionAttributeValues({ ':t': 'Expanding' }) + .expressionAttributeNames({ '#title': 'title' }) + .projectionExpression('#title, tag') + .exec(); + +var GameScore = dynogels.define('GameScore', { + hashKey: 'userId', + rangeKey: 'gameTitle', + schema: { + userId: Joi.string(), + gameTitle: Joi.string(), + topScore: Joi.number(), + topScoreDateTime: Joi.date(), + wins: Joi.number(), + losses: Joi.number() + }, + indexes: [{ + hashKey: 'gameTitle', rangeKey: 'topScore', name: 'GameTitleIndex', type: 'global' + }] +}); + +GameScore + .query('Galaxy Invaders') + .usingIndex('GameTitleIndex') + .descending() + .exec(callback); + +var GameScore = dynogels.define('GameScore', { + hashKey: 'userId', + rangeKey: 'gameTitle', + schema: { + userId: Joi.string(), + gameTitle: Joi.string(), + topScore: Joi.number(), + topScoreDateTime: Joi.date(), + wins: Joi.number(), + losses: Joi.number() + }, + indexes: [{ + hashKey: 'gameTitle', + rangeKey: 'topScore', + name: 'GameTitleIndex', + type: 'global', + projection: { NonKeyAttributes: ['wins'], ProjectionType: 'INCLUDE' } //optional, defaults to ALL + + }] +}); + +GameScore + .query('Galaxy Invaders') + .usingIndex('GameTitleIndex') + .where('topScore').gt(1000) + .descending() + .exec((err, data) => { + + }); + +var BlogPost = dynogels.define('Account', { + hashKey: 'email', + rangeKey: 'title', + schema: { + email: Joi.string().email(), + title: Joi.string(), + content: Joi.binary(), + PublishedDateTime: Joi.date() + }, + + indexes: [{ + hashKey: 'email', rangeKey: 'PublishedDateTime', type: 'local', name: 'PublishedIndex' + }] +}); + +BlogPost + .query('werner@example.com') + .usingIndex('PublishedIndex') + .descending() + .exec(callback); + +BlogPost + .query('werner@example.com') + .usingIndex('PublishedIndex') + .ascending() + .exec(callback); + +BlogPost + .query('werner@example.com') + .usingIndex('PublishedIndex') + .descending() + .loadAll() + .exec(callback); + +// scan all accounts, returning the first page or results +Account.scan().exec(callback); + +// scan all accounts, this time loading all results +// note this will potentially make several calls to DynamoDB +// in order to load all results +Account + .scan() + .loadAll() + .exec(callback); + +// Load 20 accounts +Account + .scan() + .limit(20) + .exec(); + +// Load All accounts, 20 at a time per request +Account + .scan() + .limit(20) + .loadAll() + .exec(); + +// Load accounts which match a filter +// only return email and created attributes +// and return back the consumed capacity the request took +Account + .scan() + .where('email').gte('f@example.com') + .attributes(['email', 'created']) + .returnConsumedCapacity() + .exec(); + +// Load All accounts, if settings.acceptedTerms is true +Account + .scan() + .where('settings.acceptedTerms').equals(true) + .exec(); + +// Returns number of matching accounts, rather than the matching accounts themselves +Account + .scan() + .where('age').gte(21) + .select('COUNT') + .exec(); + +// Start scan using start key +Account + .scan() + .where('age').notNull() + .startKey('foo@example.com') + .exec() + +// equals +Account + .scan() + .where('name').equals('Werner') + .exec(); + +// not equals +Account + .scan() + .where('name').ne('Werner') + .exec(); + +// less than equals +Account + .scan() + .where('name').lte('Werner') + .exec(); + +// less than +Account + .scan() + .where('name').lt('Werner') + .exec(); + +// greater than equals +Account + .scan() + .where('name').gte('Werner') + .exec(); + +// greater than +Account + .scan() + .where('name').gt('Werner') + .exec(); + +// name attribute doesn't exist +Account + .scan() + .where('name').null() + .exec(); + +// name attribute exists +Account + .scan() + .where('name').notNull() + .exec(); + +// contains +Account + .scan() + .where('name').contains('ner') + .exec(); + +// not contains +Account + .scan() + .where('name').notContains('ner') + .exec(); + +// in +Account + .scan() + .where('name').in(['foo@example.com', 'bar@example.com']) + .exec(); + +// begins with +Account + .scan() + .where('name').beginsWith('Werner') + .exec(); + +// between +Account + .scan() + .where('name').between('Bar', 'Foo') + .exec(); + +// multiple filters +Account + .scan() + .where('name').equals('Werner') + .where('age').notNull() + .exec(); + +Account.scan() + .filterExpression('#age BETWEEN :low AND :high AND begins_with(#email, :e)') + .expressionAttributeValues({ ':low': 18, ':high': 22, ':e': 'test1' }) + .expressionAttributeNames({ '#age': 'age', '#email': 'email' }) + .projectionExpression('#age, #email') + .exec(); + +var totalSegments = 8; + +Account.parallelScan(totalSegments) + .where('age').gte(18) + .attributes('age') + .exec(callback); + +// Load All accounts +Account + .parallelScan(totalSegments) + .exec() + +Account.getItems(['foo@example.com', 'bar@example.com', 'test@example.com'], function (err, accounts) { + console.log('loaded ' + accounts.length + ' accounts'); // prints loaded 3 accounts +}); + +// Get both accounts, using a consistent read +Account.getItems(['foo@example.com', 'bar@example.com'], { ConsistentRead: true }, function (err, accounts) { + console.log('loaded ' + accounts.length + ' accounts'); // prints loaded 2 accounts +}); + +//Streaming API + +var stream = Account.parallelScan(4).exec(); + +stream.on('readable', function () { + console.log('single parallel scan response', stream.read()); +}); + +stream.on('end', function () { + console.log('Parallel scan of accounts finished'); +}); + +var querystream = BlogPost.query('werner@dynogels.com').loadAll().exec(); + +querystream.on('readable', function () { + console.log('single query response', stream.read()); +}); + +querystream.on('end', function () { + console.log('query for blog posts finished'); +}); + +//Dynamic Table Names + +var Event = dynogels.define('Event', { + hashKey: 'name', + schema: { + name: Joi.string(), + total: Joi.number() + }, + + // store monthly event data + tableName: function () { + var d = new Date(); + return ['events', d.getFullYear(), d.getMonth() + 1].join('_'); + } +}); + +// Logging + +const accountLogger = { + info: (...args: any[]) => { + + }, + warn: (...args: any[]) => { + + } +} + +dynogels.log = accountLogger; + +var Account = dynogels.define('Account', { + hashKey: 'email', + log: accountLogger +}); // INFO level on account table + +var Account = dynogels.define('Account', { + hashKey : 'email', + + // add the timestamp attributes (updatedAt, createdAt) + timestamps : true, + + schema : { + email : Joi.string().email(), + name : Joi.string().required(), + age : Joi.number(), + } +}); + +Account.create({email: 'test@example.com', name : 'Test Account'}, function (err, acc) { + console.log('created account at', acc.get('created')); // prints created Date + + acc.set({age: 22}); + + acc.update(function (err) { + console.log('updated account age'); + }); + +}); + +// For models with range keys you must pass in objects of hash and range key attributes +var postKey1 = { email: 'test@example.com', title: 'Hello World!' }; +var postKey2 = { email: 'test@example.com', title: 'Another Post' }; + +BlogPost.getItems([postKey1, postKey2], function (err, posts) { + console.log('loaded posts'); +}); + +dynogels.log.info("test", "123", {}); +dynogels.log.warn("test", "123", {}); diff --git a/types/dynogels/index.d.ts b/types/dynogels/index.d.ts index 2e05fb0c61..9772fe33b2 100644 --- a/types/dynogels/index.d.ts +++ b/types/dynogels/index.d.ts @@ -4,29 +4,59 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export import AWS = require("aws-sdk"); +import * as joi from "joi"; import stream = require("stream"); -export namespace log { - function info(...args: any[]): void; - function warn(...args: any[]): void; + +export let log: Log; + +interface Log { + info(...args: any[]): void; + warn(...args: any[]): void; } + export let models: { [key: string]: any }; export function dynamoDriver(dynamoDB: AWS.DynamoDB): AWS.DynamoDB; export function reset(): void; export function define(modelName: string, config: ModelConfiguration): Model; -export function createTables(callback: (err: string) => void): any; +export function createTables(callback: (err: string) => void): void; +export function createTables(options: { [key: string]: CreateTablesOptions } | DynogelsGlobalOptions, callback: (err: string) => void): void; +export function Set(...args: any[]): any; + +type DynogelsGlobalOptions = { + $dynogels: { + pollingInterval: number; + } +}; + +interface CreateTablesOptions { + readCapacity?: number; + writeCapacity?: number; + streamSpecification?: { + streamEnabled: boolean; + streamViewType: string; + }; +} + +export let types: { + stringSet(): joi.AnySchema; + numberSet(): joi.AnySchema; + binarySet(): joi.AnySchema; + uuid(): joi.AnySchema; + timeUUID(): joi.AnySchema; +}; type DynogelsItemCallback = (err: Error, data: Item) => void; export interface Model { new(attrs: { [key: string]: any }): Item; - get(hashKey: any, rangeKey: any, options: AWS.DynamoDB.GetItemInput, callback: DynogelsItemCallback): void; - get(haskKey: any, options: AWS.DynamoDB.GetItemInput, callback: DynogelsItemCallback): void; + get(hashKey: any, rangeKey: any, options: GetItemOptions, callback: DynogelsItemCallback): void; + get(haskKey: any, options: GetItemOptions, callback: DynogelsItemCallback): void; get(hashKey: any, callback: DynogelsItemCallback): void; get(hashKey: any, rangeKey: any, callback: DynogelsItemCallback): void; - create(item: any, options: AWS.DynamoDB.CreateTableInput, callback: DynogelsItemCallback): void; + create(item: any, options: CreateItemOptions, callback: DynogelsItemCallback): void; create(item: any, callback: DynogelsItemCallback): void; - update(item: any, options: AWS.DynamoDB.UpdateItemInput, callback: DynogelsItemCallback): void; + update(item: any, options: UpdateItemOptions, callback: DynogelsItemCallback): void; update(item: any, callback: DynogelsItemCallback): void; destroy(hashKey: any, rangeKey: any, options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; destroy(haskKey: any, options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; @@ -35,19 +65,74 @@ export interface Model { destroy(item: any, options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; destroy(item: any, callback: DynogelsItemCallback): void; query(hashKey: any): Query; - scan(): void; - parallelScan(): void; - getItems(): void; + scan(): Scan; + parallelScan(totalSegments: number): Scan; + getItems(items: string[] | { [key: string]: string }[], callback: (err: Error, items: any[]) => void): void; + getItems(items: string[] | { [key: string]: string }[], options: GetItemOptions, callback: (err: Error, items: any[]) => void): void; batchGetItems(): void; createTable(): void; updateTable(): void; describeTable(): void; - deleteTable(): void; + deleteTable(callback: (err: Error) => void): void; tableName(): void; after(): void; before(): void; - config(): void; + config(config: ModelConfig): void; +} + +interface CreateItemOptions { + expected?: { [key: string]: any }; + overwrite?: boolean; + + Expected?: AWS.DynamoDB.ExpectedAttributeMap; + ReturnValues?: AWS.DynamoDB.ReturnValue; + ReturnConsumedCapacity?: AWS.DynamoDB.ReturnConsumedCapacity; + ReturnItemCollectionMetrics?: AWS.DynamoDB.ReturnItemCollectionMetrics; + ConditionalOperator?: AWS.DynamoDB.ConditionalOperator; + ConditionExpression?: AWS.DynamoDB.ConditionExpression; + ExpressionAttributeNames?: AWS.DynamoDB.ExpressionAttributeNameMap; + ExpressionAttributeValues?: { [key: string]: any }; +} + +interface UpdateItemOptions { + expected?: { [key: string]: any }; + + AttributeUpdates?: AWS.DynamoDB.AttributeUpdates; + Expected?: AWS.DynamoDB.ExpectedAttributeMap; + ConditionalOperator?: AWS.DynamoDB.ConditionalOperator; + ReturnValues?: AWS.DynamoDB.ReturnValue; + ReturnConsumedCapacity?: AWS.DynamoDB.ReturnConsumedCapacity; + ReturnItemCollectionMetrics?: AWS.DynamoDB.ReturnItemCollectionMetrics; + UpdateExpression?: AWS.DynamoDB.UpdateExpression; + ConditionExpression?: AWS.DynamoDB.ConditionExpression; + ExpressionAttributeNames?: AWS.DynamoDB.ExpressionAttributeNameMap; + ExpressionAttributeValues?: { [key: string]: any }; +} + +interface DestroyItemOptions { + Expected?: AWS.DynamoDB.ExpectedAttributeMap; + ConditionalOperator?: AWS.DynamoDB.ConditionalOperator; + ReturnValues?: AWS.DynamoDB.ReturnValue; + ReturnConsumedCapacity?: AWS.DynamoDB.ReturnConsumedCapacity; + ReturnItemCollectionMetrics?: AWS.DynamoDB.ReturnItemCollectionMetrics; + ConditionExpression?: AWS.DynamoDB.ConditionExpression; + ExpressionAttributeNames?: AWS.DynamoDB.ExpressionAttributeNameMap; + ExpressionAttributeValues?: { [key: string]: any }; +} + +interface GetItemOptions { + AttributesToGet?: AWS.DynamoDB.AttributeNameList; + ConsistentRead?: AWS.DynamoDB.ConsistentRead; + ReturnConsumedCapacity?: AWS.DynamoDB.ReturnConsumedCapacity; + ProjectionExpression?: AWS.DynamoDB.ProjectionExpression; + ExpressionAttributeNames?: AWS.DynamoDB.ExpressionAttributeNameMap; +} + +interface ModelConfig { + tableName?: string; + docClient?: any; + dynamodb?: AWS.DynamoDB; } export interface Item { @@ -86,6 +171,8 @@ export interface Query { lt(value: any): Query; gte(value: any): Query; gt(value: any): Query; + null(): Query; + exists(): Query; beginsWith(value: any): Query; between(value1: any, value2: any): Query; }; @@ -106,15 +193,16 @@ export interface Query { between(value1: any, value2: any): Query; }; exec(): stream.Readable; - exec(callback: () => void): void; + exec(callback: (err: Error, data: any) => void): void; } export interface Scan { limit(number: number): Scan; addFilterCondition(condition: any): Scan; - startKey(hashKey: any, rangeKey: any): Scan; + startKey(hashKey: any, rangeKey?: any): Scan; attributes(attrs: any): Scan; select(value: any): Scan; + returnConsumedCapacity(): Scan; segments(segment: any, totalSegments: number): Scan; where(keyName: string): { equals(value: any): Scan; @@ -131,26 +219,32 @@ export interface Scan { in(values: any[]): Scan; beginsWith(value: any): Scan; between(value1: any, value2: any): Scan; + notNull(): Scan; }; filterExpression(expression: any): Scan; expressionAttributeNames(data: any): Scan; expressionAttributeValues(data: any): Scan; projectionExpression(data: any): Scan; exec(): stream.Readable; - exec(callback: () => void): void; + exec(callback: (err: Error, data: any) => void): void; loadAll(): Scan; } type tableResolve = () => string; +type schemaType = { [key: string]: joi.AnySchema | schemaType }; + export interface ModelConfiguration { hashKey: string, rangeKey?: string, timestamps?: boolean, createdAt?: boolean, - updatedAtField?: string, - schema: { [key: string]: any }, + updatedAt?: string, + schema?: schemaType, + validation?: joi.ValidationOptions, tableName?: string | tableResolve; + indexes?: any[]; + log?: Log; } interface Document { [key: string]: any; From 1f27507135409c6bf3b416b3a38000f69b7654f9 Mon Sep 17 00:00:00 2001 From: Evan Moran Date: Sun, 12 Nov 2017 09:56:29 -0500 Subject: [PATCH 142/495] Added some more typings. Think it's done except for event emitter stuff --- types/dynogels/dynogels-tests.ts | 29 ++++---- types/dynogels/index.d.ts | 110 +++++++++++++++++-------------- 2 files changed, 76 insertions(+), 63 deletions(-) diff --git a/types/dynogels/dynogels-tests.ts b/types/dynogels/dynogels-tests.ts index 756977d066..72d9e5e0f4 100644 --- a/types/dynogels/dynogels-tests.ts +++ b/types/dynogels/dynogels-tests.ts @@ -8,7 +8,6 @@ dynogels.AWS.config.loadFromPath('credentials.json'); dynogels.AWS.config.update({ region: "REGION" }); //Define a Model - var Account = dynogels.define('Account', { hashKey: 'email', @@ -805,26 +804,26 @@ var Account = dynogels.define('Account', { }); // INFO level on account table var Account = dynogels.define('Account', { - hashKey : 'email', + hashKey: 'email', - // add the timestamp attributes (updatedAt, createdAt) - timestamps : true, + // add the timestamp attributes (updatedAt, createdAt) + timestamps: true, - schema : { - email : Joi.string().email(), - name : Joi.string().required(), - age : Joi.number(), - } + schema: { + email: Joi.string().email(), + name: Joi.string().required(), + age: Joi.number(), + } }); -Account.create({email: 'test@example.com', name : 'Test Account'}, function (err, acc) { - console.log('created account at', acc.get('created')); // prints created Date +Account.create({ email: 'test@example.com', name: 'Test Account' }, function (err, acc) { + console.log('created account at', acc.get('created')); // prints created Date - acc.set({age: 22}); + acc.set({ age: 22 }); - acc.update(function (err) { - console.log('updated account age'); - }); + acc.update(function (err) { + console.log('updated account age'); + }); }); diff --git a/types/dynogels/index.d.ts b/types/dynogels/index.d.ts index 9772fe33b2..b62098ec2c 100644 --- a/types/dynogels/index.d.ts +++ b/types/dynogels/index.d.ts @@ -7,36 +7,9 @@ export import AWS = require("aws-sdk"); import * as joi from "joi"; import stream = require("stream"); +// Dynogels Data Members export let log: Log; - -interface Log { - info(...args: any[]): void; - warn(...args: any[]): void; -} - -export let models: { [key: string]: any }; -export function dynamoDriver(dynamoDB: AWS.DynamoDB): AWS.DynamoDB; -export function reset(): void; -export function define(modelName: string, config: ModelConfiguration): Model; -export function createTables(callback: (err: string) => void): void; -export function createTables(options: { [key: string]: CreateTablesOptions } | DynogelsGlobalOptions, callback: (err: string) => void): void; -export function Set(...args: any[]): any; - -type DynogelsGlobalOptions = { - $dynogels: { - pollingInterval: number; - } -}; - -interface CreateTablesOptions { - readCapacity?: number; - writeCapacity?: number; - streamSpecification?: { - streamEnabled: boolean; - streamViewType: string; - }; -} - +export let models: { [key: string]: Model }; export let types: { stringSet(): joi.AnySchema; numberSet(): joi.AnySchema; @@ -45,8 +18,35 @@ export let types: { timeUUID(): joi.AnySchema; }; -type DynogelsItemCallback = (err: Error, data: Item) => void; +export interface Log { + info(...args: any[]): void; + warn(...args: any[]): void; +} +//Dynogels global functions +export function dynamoDriver(dynamoDB: AWS.DynamoDB): AWS.DynamoDB; +export function reset(): void; +export function define(modelName: string, config: ModelConfiguration): Model; +export function createTables(callback: (err: string) => void): void; +export function createTables(options: { [key: string]: CreateTablesOptions } | DynogelsGlobalOptions, callback: (err: string) => void): void; +export function Set(...args: any[]): any; + +export interface DynogelsGlobalOptions { + $dynogels: { + pollingInterval: number; + } +} + +export interface CreateTablesOptions { + readCapacity?: number; + writeCapacity?: number; + streamSpecification?: { + streamEnabled: boolean; + streamViewType: string; + }; +} + +//Dynogels Model export interface Model { new(attrs: { [key: string]: any }): Item; @@ -58,30 +58,40 @@ export interface Model { create(item: any, callback: DynogelsItemCallback): void; update(item: any, options: UpdateItemOptions, callback: DynogelsItemCallback): void; update(item: any, callback: DynogelsItemCallback): void; - destroy(hashKey: any, rangeKey: any, options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; - destroy(haskKey: any, options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; + destroy(hashKey: any, rangeKey: any, options: DestroyItemOptions, callback: DynogelsItemCallback): void; + destroy(haskKey: any, options: DestroyItemOptions, callback: DynogelsItemCallback): void; destroy(hashKey: any, callback: DynogelsItemCallback): void; destroy(hashKey: any, rangeKey: any, callback: DynogelsItemCallback): void; - destroy(item: any, options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; + destroy(item: any, options: DestroyItemOptions, callback: DynogelsItemCallback): void; destroy(item: any, callback: DynogelsItemCallback): void; query(hashKey: any): Query; scan(): Scan; parallelScan(totalSegments: number): Scan; getItems(items: string[] | { [key: string]: string }[], callback: (err: Error, items: any[]) => void): void; getItems(items: string[] | { [key: string]: string }[], options: GetItemOptions, callback: (err: Error, items: any[]) => void): void; - batchGetItems(): void; - createTable(): void; - updateTable(): void; - describeTable(): void; + batchGetItems(items: string[] | { [key: string]: string }[], callback: (err: Error, items: any[]) => void): void; + batchGetItems(items: string[] | { [key: string]: string }[], options: GetItemOptions, callback: (err: Error, items: any[]) => void): void; + createTable(options: { [key: string]: CreateTablesOptions } | DynogelsGlobalOptions, callback: (err: Error, data: AWS.DynamoDB.CreateTableOutput) => void): void; + createTable(callback: (err: Error, data: AWS.DynamoDB.CreateTableOutput) => void): void; + updateTable(throughput: Throughput, callback: (err: Error, data: AWS.DynamoDB.UpdateTableOutput) => void): void; + updateTable(callback: (err: Error, data: AWS.DynamoDB.UpdateTableOutput) => void): void; + describeTable(callback: (err: Error, data: AWS.DynamoDB.DescribeTableOutput) => void): void; deleteTable(callback: (err: Error) => void): void; - tableName(): void; + tableName(): string; after(): void; before(): void; - config(config: ModelConfig): void; + config(config: ModelConfig): { name: string }; } -interface CreateItemOptions { +type DynogelsItemCallback = (err: Error, data: Item) => void; + +export interface Throughput { + readCapacity: number; + writeCapacity: number; +} + +export interface CreateItemOptions { expected?: { [key: string]: any }; overwrite?: boolean; @@ -95,7 +105,7 @@ interface CreateItemOptions { ExpressionAttributeValues?: { [key: string]: any }; } -interface UpdateItemOptions { +export interface UpdateItemOptions { expected?: { [key: string]: any }; AttributeUpdates?: AWS.DynamoDB.AttributeUpdates; @@ -110,7 +120,7 @@ interface UpdateItemOptions { ExpressionAttributeValues?: { [key: string]: any }; } -interface DestroyItemOptions { +export interface DestroyItemOptions { Expected?: AWS.DynamoDB.ExpectedAttributeMap; ConditionalOperator?: AWS.DynamoDB.ConditionalOperator; ReturnValues?: AWS.DynamoDB.ReturnValue; @@ -121,7 +131,7 @@ interface DestroyItemOptions { ExpressionAttributeValues?: { [key: string]: any }; } -interface GetItemOptions { +export interface GetItemOptions { AttributesToGet?: AWS.DynamoDB.AttributeNameList; ConsistentRead?: AWS.DynamoDB.ConsistentRead; ReturnConsumedCapacity?: AWS.DynamoDB.ReturnConsumedCapacity; @@ -129,24 +139,26 @@ interface GetItemOptions { ExpressionAttributeNames?: AWS.DynamoDB.ExpressionAttributeNameMap; } -interface ModelConfig { +export interface ModelConfig { tableName?: string; docClient?: any; dynamodb?: AWS.DynamoDB; } +//Dynogels Item export interface Item { get(key: string): { [key: string]: any }; - set(params: {}): void; + set(params: {}): Item; save(callback: DynogelsItemCallback): void; - update(options: AWS.DynamoDB.UpdateItemInput, callback: DynogelsItemCallback): void; + update(options: UpdateItemOptions, callback: DynogelsItemCallback): void; update(callback: DynogelsItemCallback): void; - destroy(options: AWS.DynamoDB.DeleteItemInput, callback: DynogelsItemCallback): void; + destroy(options: DestroyItemOptions, callback: DynogelsItemCallback): void; destroy(callback: DynogelsItemCallback): void; toJSON(): any; toPlainObject(): any; } +//Dynogels Query export interface Query { limit(number: number): Query; filterExpression(expression: any): Query; @@ -196,6 +208,7 @@ export interface Query { exec(callback: (err: Error, data: any) => void): void; } +//Dynogels Scan export interface Scan { limit(number: number): Scan; addFilterCondition(condition: any): Scan; @@ -246,7 +259,8 @@ export interface ModelConfiguration { indexes?: any[]; log?: Log; } -interface Document { + +export interface Document { [key: string]: any; } From 3e738ec4706b98d944f4a1020a2f138425b53ff7 Mon Sep 17 00:00:00 2001 From: Evan Moran Date: Sun, 12 Nov 2017 10:06:19 -0500 Subject: [PATCH 143/495] Updated github name --- types/dynogels/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/dynogels/index.d.ts b/types/dynogels/index.d.ts index b62098ec2c..80ad3d26e4 100644 --- a/types/dynogels/index.d.ts +++ b/types/dynogels/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for dynogels 8.0 // Project: https://github.com/clarkie/dynogels#readme -// Definitions by: My Self +// Definitions by: Spartan Labs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export import AWS = require("aws-sdk"); From 1bca60eeaea49328fd63449ef8dffbd580b99752 Mon Sep 17 00:00:00 2001 From: Ryan Naddy Date: Sun, 12 Nov 2017 10:56:58 -0600 Subject: [PATCH 144/495] deepmerge does not exist on window > [ts] Property 'deepmerge' does not exist on type 'Window'. `deepmerge` is not found if it is being used within the browser --- types/deepmerge/index.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/types/deepmerge/index.d.ts b/types/deepmerge/index.d.ts index 797e52c8a5..05f5c96d2e 100644 --- a/types/deepmerge/index.d.ts +++ b/types/deepmerge/index.d.ts @@ -18,3 +18,10 @@ declare namespace deepmerge { function all(objects: Array>, options?: Options): T; } + +declare global { + interface Window { + deepmerge(x: Partial, y: Partial, options?: deepmerge.Options): T; + deepmerge(x: T1, y: T2, options?: deepmerge.Options): T1 & T2; + } +} From 2e6ef3f6a4bb7523834a7b49bfb3e72097920a00 Mon Sep 17 00:00:00 2001 From: Kepler Sticka-Jones Date: Sun, 12 Nov 2017 12:15:37 -0700 Subject: [PATCH 145/495] Add withRouter HOC to next.js typedef --- types/next/router.d.ts | 2 ++ types/next/test/next-router-tests.tsx | 2 ++ 2 files changed, 4 insertions(+) diff --git a/types/next/router.d.ts b/types/next/router.d.ts index 021b0dd3dc..0c831d8600 100644 --- a/types/next/router.d.ts +++ b/types/next/router.d.ts @@ -32,5 +32,7 @@ export interface SingletonRouter { onRouteChangeError?(error: any, url: string): void; } +export function withRouter(Component: React.ComponentType): React.ComponentType; + export const Singleton: SingletonRouter; export default Singleton; diff --git a/types/next/test/next-router-tests.tsx b/types/next/test/next-router-tests.tsx index 37e739d98a..e713f127b7 100644 --- a/types/next/test/next-router-tests.tsx +++ b/types/next/test/next-router-tests.tsx @@ -51,3 +51,5 @@ Router.replace('/route', '/asRoute', {shallow: false}).then((success: boolean) = Router.prefetch('/route').then(Component => { const element = (); }); + +r.withRouter(props =>
); From e4aa2472528bca570efbd1858f9919ae508560f6 Mon Sep 17 00:00:00 2001 From: Knuppe Date: Sun, 12 Nov 2017 21:43:47 -0200 Subject: [PATCH 146/495] puppeteer: Upgrade typings for version 0.13 --- types/puppeteer/index.d.ts | 713 ++++++++++++++++++++++++++++- types/puppeteer/puppeteer-tests.ts | 26 +- 2 files changed, 705 insertions(+), 34 deletions(-) diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index 8479c100a1..098ba9616a 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 { + /** + * Returns a ElementHandle + */ asElement(): ElementHandle; + /** + * 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 `