diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 0380b02e1e..8c7f823a07 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -4293,6 +4293,7 @@ /types/timer-machine/ @dolanmiu /types/timezone-js/ @bonnici /types/tinajs__tina/ @Jimexist +/types/tinajs__tina-redux/ @Jimexist /types/tinder/ @pingec /types/tiny-slider-react/ @screendriver /types/tinycolor2/ @M-Zuber @geertjansen @nvh diff --git a/types/agenda/agenda-tests.ts b/types/agenda/agenda-tests.ts index e4de026c0e..2c011efaf7 100644 --- a/types/agenda/agenda-tests.ts +++ b/types/agenda/agenda-tests.ts @@ -67,6 +67,9 @@ var mongoConnectionString = "mongodb://127.0.0.1/agenda"; await job.save(); const jobs = await agenda.jobs({ name: 'printAnalyticsReport' }); + jobs.forEach((job) => { + job.save(); + }); let numRemoved = await agenda.cancel({ name: 'printAnalyticsReport' }); diff --git a/types/agenda/index.d.ts b/types/agenda/index.d.ts index d728a76032..be07b84aaf 100644 --- a/types/agenda/index.d.ts +++ b/types/agenda/index.d.ts @@ -96,7 +96,7 @@ declare class Agenda extends EventEmitter { * Find all Jobs matching `query` and pass same back in cb(). * @param query */ - jobs(query: any): Promise; + jobs(query: any): Promise[]>; /** * Removes all jobs in the database without defined behaviors. Useful if you change a definition name and want diff --git a/types/babel__core/index.d.ts b/types/babel__core/index.d.ts index 84f49c20fc..277228341b 100644 --- a/types/babel__core/index.d.ts +++ b/types/babel__core/index.d.ts @@ -10,10 +10,10 @@ import { GeneratorOptions } from "@babel/generator"; import traverse, { Visitor, NodePath } from "@babel/traverse"; import template from "@babel/template"; import * as t from "@babel/types"; -import { BabylonOptions } from "babylon"; +import { ParseOptions } from "@babel/parser"; export { - BabylonOptions, + ParseOptions, GeneratorOptions, t as types, template, @@ -217,7 +217,7 @@ export interface TransformOptions { * * Default: `{}` */ - parserOpts?: BabylonOptions | null; + parserOpts?: ParseOptions | null; /** * List of plugins to load and use diff --git a/types/babel__core/tsconfig.json b/types/babel__core/tsconfig.json index 22eb208383..2f96e019cb 100644 --- a/types/babel__core/tsconfig.json +++ b/types/babel__core/tsconfig.json @@ -22,6 +22,9 @@ "@babel/generator": [ "babel__generator" ], + "@babel/parser": [ + "babel__parser" + ], "@babel/template": [ "babel__template" ], diff --git a/types/backbone.marionette/backbone.marionette-tests.ts b/types/backbone.marionette/backbone.marionette-tests.ts index c6400b2672..2b86849622 100644 --- a/types/backbone.marionette/backbone.marionette-tests.ts +++ b/types/backbone.marionette/backbone.marionette-tests.ts @@ -135,6 +135,15 @@ class MyView extends Marionette.View { } } +class MyOtherView extends MyView { + private readonly foo: string; + + constructor(model: MyModel) { + super(model); + this.foo = 'bar'; + } +} + class MainRegion extends Marionette.Region { constructor() { super(); @@ -185,10 +194,20 @@ class MyHtmlElRegion extends Marionette.Region { } } -class MyCollectionView extends Marionette.CollectionView { +class MyCollectionView extends Marionette.CollectionView { constructor() { super(); + + this.childView = (model: MyModel) => { + if (model.get('isFoo')) { + return MyView; + } + + return MyOtherView; + }; + this.childView = MyView; + this.childViewEvents = { render() { console.log('a childView has been rendered'); @@ -282,7 +301,7 @@ function CollectionViewTests() { cv.collection.add(new MyModel()); app.mainRegion.show(cv); cv.emptyView = MyView; - const view: Marionette.CollectionView = cv.destroy(); + const view: Marionette.CollectionView = cv.destroy(); } class MyController { diff --git a/types/backbone.marionette/index.d.ts b/types/backbone.marionette/index.d.ts index 0b717c9bb1..bacd045ba1 100644 --- a/types/backbone.marionette/index.d.ts +++ b/types/backbone.marionette/index.d.ts @@ -3,7 +3,8 @@ // Definitions by: Zeeshan Hamid , // Natan Vivo , // Sven Tschui , -// Volker Nauruhn +// Volker Nauruhn , +// Ard Timmerman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -1157,7 +1158,7 @@ export interface CollectionViewOptions< /** * Specify a child view to use. */ - childView?: (() => typeof Backbone.View) | typeof Backbone.View; + childView?: ((model: TModel) => typeof Backbone.View) | typeof Backbone.View; /** * Define options to pass to the childView constructor. @@ -1219,7 +1220,7 @@ export class CollectionView { new(...args: any[]): TView }) | { new(...args: any[]): TView }; + childView: ((model: TModel) => { new(...args: any[]): TView }) | { new(...args: any[]): TView }; /** * Define options to pass to the childView constructor. diff --git a/types/bull/bull-tests.tsx b/types/bull/bull-tests.tsx index c2e0d3161f..a8c7f403a7 100644 --- a/types/bull/bull-tests.tsx +++ b/types/bull/bull-tests.tsx @@ -6,7 +6,10 @@ import Redis = require("ioredis"); import Queue = require("bull"); const videoQueue = new Queue('video transcoding', 'redis://127.0.0.1:6379'); -const audioQueue = new Queue('audio transcoding', {redis: {port: 6379, host: '127.0.0.1'}}); // Specify Redis connection using object +const audioQueue = new Queue('audio transcoding', { + redis: {port: 6379, host: '127.0.0.1'}, // Specify Redis connection using object + settings: {}, +}); const imageQueue: Queue.Queue<{ image: string }> = new Queue('image transcoding'); videoQueue.process((job, done) => { diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index 6ed6fa88e7..a11ae0257a 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -88,7 +88,7 @@ declare namespace Bull { /** * Define a custom backoff strategy */ - backoffStrategies: { + backoffStrategies?: { [key: string]: (attemptsMade: number, err: typeof Error) => number; }; } diff --git a/types/bull/tsconfig.json b/types/bull/tsconfig.json index 3ce6f08792..7dbd4e7b61 100644 --- a/types/bull/tsconfig.json +++ b/types/bull/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/cesium/index.d.ts b/types/cesium/index.d.ts index f2bb11479c..6c34023eae 100644 --- a/types/cesium/index.d.ts +++ b/types/cesium/index.d.ts @@ -3593,7 +3593,7 @@ declare namespace Cesium { cull?: boolean; asynchronous?: boolean; debugShowBoundingVolume?: boolean; - shadows: ShadowMode + shadows?: ShadowMode }); destroy(): void; getGeometryInstanceAttributes(id: any): any; diff --git a/types/clipboard/clipboard-tests.ts b/types/clipboard/clipboard-tests.ts index a2ae8f9354..1a9a170087 100644 --- a/types/clipboard/clipboard-tests.ts +++ b/types/clipboard/clipboard-tests.ts @@ -14,6 +14,12 @@ const cb5 = new ClipboardJS(".btn", { action: elem => "copy", target: elem => null }); +const cb6 = new ClipboardJS(".btn", { + action: elem => "copy", + text: trigger => trigger.getAttribute('aria-label'), + target: trigger => trigger.nextElementSibling, + container: document.getElementById('modal') +}); cb1.destroy(); ClipboardJS.isSupported(); diff --git a/types/clipboard/index.d.ts b/types/clipboard/index.d.ts index 2405c0c6f0..ceb15b885b 100644 --- a/types/clipboard/index.d.ts +++ b/types/clipboard/index.d.ts @@ -49,6 +49,14 @@ declare namespace ClipboardJS { * @returns Text to be copied. */ text?(elem: Element): string; + + /** + * For use in Bootstrap Modals or with any + * other library that changes the focus + * you'll want to set the focused element + * as the container value. + */ + container?: Element; } interface Event { diff --git a/types/d3-hierarchy/d3-hierarchy-tests.ts b/types/d3-hierarchy/d3-hierarchy-tests.ts index 65b1f5c392..b75b9fbbd0 100644 --- a/types/d3-hierarchy/d3-hierarchy-tests.ts +++ b/types/d3-hierarchy/d3-hierarchy-tests.ts @@ -189,6 +189,10 @@ stratificatorizer = d3Hierarchy.stratify(); // id(...) +stratificatorizer = stratificatorizer.id((d) => { + return d.name; // d is of type TabularHierarchyDatum +}); + stratificatorizer = stratificatorizer.id((d, i, data) => { console.log('Length of tabular array: ', data.length); console.log('Name of first entry in tabular array: ', data[0].name); // data of type Array @@ -199,6 +203,10 @@ idStringAccessor = stratificatorizer.id(); // parentId(...) +stratificatorizer = stratificatorizer.parentId((d) => { + return d.parentId; // d is of type TabularHierarchyDatum +}); + stratificatorizer = stratificatorizer.parentId((d, i, data) => { console.log('Length of tabular array: ', data.length); console.log('Name of first entry in tabular array: ', data[0].name); // data of type Array @@ -225,14 +233,12 @@ clusterLayout = d3Hierarchy.cluster(); // size() ---------------------------------------------------------------- -clusterLayout = clusterLayout.size(null); clusterLayout = clusterLayout.size([200, 200]); size = clusterLayout.size(); // nodeSize() ------------------------------------------------------------ -clusterLayout = clusterLayout.nodeSize(null); clusterLayout = clusterLayout.nodeSize([10, 10]); size = clusterLayout.nodeSize(); @@ -358,14 +364,12 @@ treeLayout = d3Hierarchy.tree(); // size() ---------------------------------------------------------------- -treeLayout = treeLayout.size(null); treeLayout = treeLayout.size([200, 200]); size = treeLayout.size(); // nodeSize() ------------------------------------------------------------ -treeLayout = treeLayout.nodeSize(null); treeLayout = treeLayout.nodeSize([10, 10]); size = treeLayout.nodeSize(); @@ -416,7 +420,6 @@ tilingFn = treemapLayout.tile(); // size() ---------------------------------------------------------------- -treemapLayout = treemapLayout.size(null); treemapLayout = treemapLayout.size([400, 200]); size = treemapLayout.size(); @@ -635,7 +638,6 @@ partitionLayout = d3Hierarchy.partition(); // size() ---------------------------------------------------------------- -partitionLayout = partitionLayout.size(null); partitionLayout = partitionLayout.size([400, 200]); size = partitionLayout.size(); @@ -674,7 +676,6 @@ packLayout = d3Hierarchy.pack(); // size() ---------------------------------------------------------------- -packLayout = packLayout.size(null); packLayout = packLayout.size([400, 400]); size = packLayout.size(); diff --git a/types/d3-hierarchy/index.d.ts b/types/d3-hierarchy/index.d.ts index 440a779217..bdb7b652d5 100644 --- a/types/d3-hierarchy/index.d.ts +++ b/types/d3-hierarchy/index.d.ts @@ -1,65 +1,208 @@ // Type definitions for D3JS d3-hierarchy module 1.1 // Project: https://github.com/d3/d3-hierarchy/ -// Definitions by: Tom Wanzek , Alex Ford , Boris Yankov +// Definitions by: Tom Wanzek +// Alex Ford +// Boris Yankov +// denisname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.1.1 +// Last module patch version validated against: 1.1.6 // ----------------------------------------------------------------------- // Hierarchy // ----------------------------------------------------------------------- export interface HierarchyLink { + /** + * The source of the link. + */ source: HierarchyNode; + + /** + * The target of the link. + */ target: HierarchyNode; } export interface HierarchyNode { - data: Datum; - readonly depth: number; - readonly height: number; - parent: HierarchyNode | null; - children?: Array>; /** - * Aggregated numeric value as calculated by sum(value) or count(), - * if previously invoked. + * The associated data, as specified to the constructor. + */ + data: Datum; + + /** + * Zero for the root node, and increasing by one for each descendant generation. + */ + readonly depth: number; + + /** + * Zero for leaf nodes, and the greatest distance from any descendant leaf for internal nodes. + */ + readonly height: number; + + /** + * The parent node, or null for the root node. + */ + parent: this | null; + + /** + * An array of child nodes, if any; undefined for leaf nodes. + */ + children?: this[]; + + /** + * Aggregated numeric value as calculated by `sum(value)` or `count()`, if previously invoked. */ readonly value?: number; + /** - * Optional Node Id string set by StratifyOperator, if - * hierarchical data was created from tabular data using stratify() + * Optional node id string set by `StratifyOperator`, if hierarchical data was created from tabular data using stratify(). */ readonly id?: string; - ancestors(): Array>; - descendants(): Array>; - leaves(): Array>; - path(target: HierarchyNode): Array>; + + /** + * Returns the array of ancestors nodes, starting with this node, then followed by each parent up to the root. + */ + ancestors(): this[]; + + /** + * Returns the array of descendant nodes, starting with this node, then followed by each child in topological order. + */ + descendants(): this[]; + + /** + * Returns the array of leaf nodes in traversal order; leaves are nodes with no children. + */ + leaves(): this[]; + + /** + * Returns the shortest path through the hierarchy from this node to the specified target node. + * The path starts at this node, ascends to the least common ancestor of this node and the target node, and then descends to the target node. + * + * @param target The target node. + */ + path(target: this): this[]; + + /** + * Returns an array of links for this node, where each link is an object that defines source and target properties. + * The source of each link is the parent node, and the target is a child node. + */ links(): Array>; + + /** + * Evaluates the specified value function for this node and each descendant in post-order traversal, and returns this node. + * The `node.value` property of each node is set to the numeric value returned by the specified function plus the combined value of all descendants. + * + * @param value The value function is passed the node’s data, and must return a non-negative number. + */ sum(value: (d: Datum) => number): this; + + /** + * Computes the number of leaves under this node and assigns it to `node.value`, and similarly for every descendant of node. + * If this node is a leaf, its count is one. Returns this node. + */ count(): this; - sort(compare: (a: HierarchyNode, b: HierarchyNode) => number): this; - each(func: (node: HierarchyNode) => void): this; - eachAfter(func: (node: HierarchyNode) => void): this; - eachBefore(func: (node: HierarchyNode) => void): this; - copy(): HierarchyNode; + + /** + * Sorts the children of this node, if any, and each of this node’s descendants’ children, + * in pre-order traversal using the specified compare function, and returns this node. + * + * @param compare The compare function is passed two nodes a and b to compare. + * If a should be before b, the function must return a value less than zero; + * if b should be before a, the function must return a value greater than zero; + * otherwise, the relative order of a and b are not specified. See `array.sort` for more. + */ + sort(compare: (a: this, b: this) => number): this; + + /** + * Invokes the specified function for node and each descendant in breadth-first order, + * such that a given node is only visited if all nodes of lesser depth have already been visited, + * as well as all preceding nodes of the same depth. + * + * @param func The specified function is passed the current node. + */ + each(func: (node: this) => void): this; + + /** + * Invokes the specified function for node and each descendant in post-order traversal, + * such that a given node is only visited after all of its descendants have already been visited. + * + * @param func The specified function is passed the current node. + */ + eachAfter(func: (node: this) => void): this; + + /** + * Invokes the specified function for node and each descendant in pre-order traversal, + * such that a given node is only visited after all of its ancestors have already been visited. + * + * @param func The specified function is passed the current node. + */ + eachBefore(func: (node: this) => void): this; + + /** + * Return a deep copy of the subtree starting at this node. The returned deep copy shares the same data, however. + * The returned node is the root of a new tree; the returned node’s parent is always null and its depth is always zero. + */ + copy(): this; } +/** + * Constructs a root node from the specified hierarchical data. + * + * @param data The root specified data. + * @param children The specified children accessor function invoked for each datum, starting with the root data. + * Must return an array of data representing the children, and return null or undefined if the current datum has no children. + * If children is not specified, it defaults to: `(d) => d.children`. + */ export function hierarchy(data: Datum, children?: (d: Datum) => (Datum[] | null)): HierarchyNode; // ----------------------------------------------------------------------- // Stratify // ----------------------------------------------------------------------- -// TODO: Review the comment in the API documentation related to 'reserved properties': id, parentId, children. If this is referring to the element on node, it should be 'parent'? - export interface StratifyOperator { + /** + * Generates a new hierarchy from the specified tabular data. Each node in the returned object has a shallow copy of the properties + * from the corresponding data object, excluding the following reserved properties: id, parentId, children. + * + * @param data The root specified data. + * @throws Error on missing id, ambiguous id, cycle, multiple roots or no root. + */ (data: Datum[]): HierarchyNode; + + /** + * Returns the current id accessor, which defaults to: `(d) => d.id`. + */ id(): (d: Datum, i: number, data: Datum[]) => (string | null | '' | undefined); + /** + * Sets the id accessor to the given function. + * The id accessor is invoked for each element in the input data passed to the stratify operator. + * The returned string is then used to identify the node's relationships in conjunction with the parent id. + * For leaf nodes, the id may be undefined, null or the empty string; otherwise, the id must be unique. + * + * @param id The id accessor. + */ id(id: (d: Datum, i?: number, data?: Datum[]) => (string | null | '' | undefined)): this; + + /** + * Returns the current parent id accessor, which defaults to: `(d) => d.parentId`. + */ parentId(): (d: Datum, i: number, data: Datum[]) => (string | null | '' | undefined); + /** + * Sets the parent id accessor to the given function. + * The parent id accessor is invoked for each element in the input data passed to the stratify operator. + * The returned string is then used to identify the node's relationships in conjunction with the id. + * For the root node, the parent id should be undefined, null or the empty string. + * There must be exactly one root node in the input data, and no circular relationships. + * + * @param parentId The parent id accessor. + */ parentId(parentId: (d: Datum, i?: number, data?: Datum[]) => (string | null | '' | undefined)): this; } +/** + * Constructs a new stratify operator with the default settings. + */ export function stratify(): StratifyOperator; // ----------------------------------------------------------------------- @@ -67,52 +210,86 @@ export function stratify(): StratifyOperator; // ----------------------------------------------------------------------- export interface HierarchyPointLink { + /** + * The source of the link. + */ source: HierarchyPointNode; + + /** + * The target of the link. + */ target: HierarchyPointNode; } -export interface HierarchyPointNode { +export interface HierarchyPointNode extends HierarchyNode { + /** + * The x-coordinate of the node. + */ x: number; + + /** + * The y-coordinate of the node. + */ y: number; - data: Datum; - readonly depth: number; - readonly height: number; - parent: HierarchyPointNode | null; - children?: Array>; + /** - * Aggregated numeric value as calculated by sum(value) or count(), - * if previously invoked. + * Returns an array of links for this node, where each link is an object that defines source and target properties. + * The source of each link is the parent node, and the target is a child node. */ - readonly value?: number; - /** - * Optional Node Id string set by StratifyOperator, if - * hierarchical data was created from tabular data using stratify() - */ - readonly id?: string; - ancestors(): Array>; - descendants(): Array>; - leaves(): Array>; - path(target: HierarchyPointNode): Array>; links(): Array>; - sum(value: (d: Datum) => number): this; - count(): this; - sort(compare: (a: HierarchyPointNode, b: HierarchyPointNode) => number): this; - each(func: (node: HierarchyPointNode) => void): this; - eachAfter(func: (node: HierarchyPointNode) => void): this; - eachBefore(func: (node: HierarchyPointNode) => void): this; - copy(): HierarchyPointNode; } export interface ClusterLayout { + /** + * Lays out the specified root hierarchy. + * You may want to call `root.sort` before passing the hierarchy to the cluster layout. + * + * @param root The specified root hierarchy. + */ (root: HierarchyNode): HierarchyPointNode; + + /** + * Returns the current layout size, which defaults to [1, 1]. A layout size of null indicates that a node size will be used instead. + */ size(): [number, number] | null; + /** + * Sets this cluster layout’s size to the specified [width, height] array and returns the cluster layout. + * The size represent an arbitrary coordinate system; for example, to produce a radial layout, + * a size of [360, radius] corresponds to a breadth of 360° and a depth of radius. + * + * @param size The specified two-element size array. + */ size(size: [number, number]): this; + + /** + * Returns the current node size, which defaults to null. A node size of null indicates that a layout size will be used instead. + */ nodeSize(): [number, number] | null; + /** + * Sets this cluster layout’s node size to the specified [width, height] array and returns this cluster layout. + * When a node size is specified, the root node is always positioned at <0, 0>. + * + * @param size The specified two-element size array. + */ nodeSize(size: [number, number]): this; + + /** + * Returns the current separation accessor, which defaults to: `(a, b) => a.parent == b.parent ? 1 : 2`. + */ separation(): (a: HierarchyPointNode, b: HierarchyPointNode) => number; + /** + * Sets the separation accessor to the specified function and returns this cluster layout. + * The separation accessor is used to separate neighboring leaves. + * + * @param separation The separation function is passed two leaves a and b, and must return the desired separation. + * The nodes are typically siblings, though the nodes may be more distantly related if the layout decides to place such nodes adjacent. + */ separation(separation: (a: HierarchyPointNode, b: HierarchyPointNode) => number): this; } +/** + * Creates a new cluster layout with default settings. + */ export function cluster(): ClusterLayout; // ----------------------------------------------------------------------- @@ -120,15 +297,56 @@ export function cluster(): ClusterLayout; // ----------------------------------------------------------------------- export interface TreeLayout { + /** + * Lays out the specified root hierarchy. + * You may want to call `root.sort` before passing the hierarchy to the tree layout. + * + * @param root The specified root hierarchy. + */ (root: HierarchyNode): HierarchyPointNode; + + /** + * Returns the current layout size, which defaults to [1, 1]. A layout size of null indicates that a node size will be used instead. + */ size(): [number, number] | null; + /** + * Sets this tree layout’s size to the specified [width, height] array and returns the tree layout. + * The size represent an arbitrary coordinate system; for example, to produce a radial layout, + * a size of [360, radius] corresponds to a breadth of 360° and a depth of radius. + * + * @param size The specified two-element size array. + */ size(size: [number, number]): this; + + /** + * Returns the current node size, which defaults to null. A node size of null indicates that a layout size will be used instead. + */ nodeSize(): [number, number] | null; + /** + * Sets this tree layout’s node size to the specified [width, height] array and returns this tree layout. + * When a node size is specified, the root node is always positioned at <0, 0>. + * + * @param size The specified two-element size array. + */ nodeSize(size: [number, number]): this; + + /** + * Returns the current separation accessor, which defaults to: `(a, b) => a.parent == b.parent ? 1 : 2`. + */ separation(): (a: HierarchyPointNode, b: HierarchyPointNode) => number; + /** + * Sets the separation accessor to the specified function and returns this tree layout. + * The separation accessor is used to separate neighboring nodes. + * + * @param separation The separation function is passed two nodes a and b, and must return the desired separation. + * The nodes are typically siblings, though the nodes may be more distantly related if the layout decides to place such nodes adjacent. + */ separation(separation: (a: HierarchyPointNode, b: HierarchyPointNode) => number): this; } +/** + * Creates a new tree layout with default settings. + */ export function tree(): TreeLayout; // ----------------------------------------------------------------------- @@ -136,91 +354,283 @@ export function tree(): TreeLayout; // ----------------------------------------------------------------------- export interface HierarchyRectangularLink { + /** + * The source of the link. + */ source: HierarchyRectangularNode; + + /** + * The target of the link. + */ target: HierarchyRectangularNode; } -export interface HierarchyRectangularNode { +export interface HierarchyRectangularNode extends HierarchyNode { + /** + * The left edge of the rectangle. + */ x0: number; + + /** + * The top edge of the rectangle + */ y0: number; + + /** + * The right edge of the rectangle. + */ x1: number; + + /** + * The bottom edge of the rectangle. + */ y1: number; - data: Datum; - readonly depth: number; - readonly height: number; - parent: HierarchyRectangularNode | null; - children?: Array>; + /** - * Aggregated numeric value as calculated by sum(value) or count(), - * if previously invoked. + * Returns an array of links for this node, where each link is an object that defines source and target properties. + * The source of each link is the parent node, and the target is a child node. */ - readonly value?: number; - /** - * Optional Node Id string set by StratifyOperator, if - * hierarchical data was created from tabular data using stratify() - */ - readonly id?: string; - ancestors(): Array>; - descendants(): Array>; - leaves(): Array>; - path(target: HierarchyRectangularNode): Array>; links(): Array>; - sum(value: (d: Datum) => number): this; - count(): this; - sort(compare: (a: HierarchyRectangularNode, b: HierarchyRectangularNode) => number): this; - each(func: (node: HierarchyRectangularNode) => void): this; - eachAfter(func: (node: HierarchyRectangularNode) => void): this; - eachBefore(func: (node: HierarchyRectangularNode) => void): this; - copy(): HierarchyRectangularNode; } export interface TreemapLayout { + /** + * Lays out the specified root hierarchy. + * You must call `root.sum` before passing the hierarchy to the treemap layout. + * You probably also want to call `root.sort` to order the hierarchy before computing the layout. + * + * @param root The specified root hierarchy. + */ (root: HierarchyNode): HierarchyRectangularNode; + + /** + * Returns the current tiling method, which defaults to `d3.treemapSquarify` with the golden ratio. + */ tile(): (node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number) => void; + /** + * Sets the tiling method to the specified function and returns this treemap layout. + * + * @param tile The specified tiling function. + */ tile(tile: (node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number) => void): this; + + /** + * Returns the current size, which defaults to [1, 1]. + */ size(): [number, number]; + /** + * Sets this treemap layout’s size to the specified [width, height] array and returns this treemap layout. + * + * @param size The specified two-element size array. + */ size(size: [number, number]): this; + + /** + * Returns the current rounding state, which defaults to false. + */ round(): boolean; + /** + * Enables or disables rounding according to the given boolean and returns this treemap layout. + * + * @param round The specified boolean flag. + */ round(round: boolean): this; + + /** + * Returns the current inner padding function. + */ padding(): (node: HierarchyRectangularNode) => number; + /** + * Sets the inner and outer padding to the specified number and returns this treemap layout. + * + * @param padding The specified padding value. + */ padding(padding: number): this; + /** + * Sets the inner and outer padding to the specified function and returns this treemap layout. + * + * @param padding The specified padding function. + */ padding(padding: (node: HierarchyRectangularNode) => number): this; + + /** + * Returns the current inner padding function, which defaults to the constant zero. + */ paddingInner(): (node: HierarchyRectangularNode) => number; + /** + * Sets the inner padding to the specified number and returns this treemap layout. + * The inner padding is used to separate a node’s adjacent children. + * + * @param padding The specified inner padding value. + */ paddingInner(padding: number): this; + /** + * Sets the inner padding to the specified function and returns this treemap layout. + * The function is invoked for each node with children, being passed the current node. + * The inner padding is used to separate a node’s adjacent children. + * + * @param padding The specified inner padding function. + */ paddingInner(padding: (node: HierarchyRectangularNode) => number): this; + + /** + * Returns the current top padding function. + */ paddingOuter(): (node: HierarchyRectangularNode) => number; + /** + * Sets the top, right, bottom and left padding to the specified function and returns this treemap layout. + * + * @param padding The specified padding outer value. + */ paddingOuter(padding: number): this; + /** + * Sets the top, right, bottom and left padding to the specified function and returns this treemap layout. + * + * @param padding The specified padding outer function. + */ paddingOuter(padding: (node: HierarchyRectangularNode) => number): this; + + /** + * Returns the current top padding function, which defaults to the constant zero. + */ paddingTop(): (node: HierarchyRectangularNode) => number; + /** + * Sets the top padding to the specified number and returns this treemap layout. + * The top padding is used to separate the top edge of a node from its children. + * + * @param padding The specified top padding value. + */ paddingTop(padding: number): this; + /** + * Sets the top padding to the specified function and returns this treemap layout. + * The function is invoked for each node with children, being passed the current node. + * The top padding is used to separate the top edge of a node from its children. + * + * @param padding The specified top padding function. + */ paddingTop(padding: (node: HierarchyRectangularNode) => number): this; + + /** + * Returns the current right padding function, which defaults to the constant zero. + */ paddingRight(): (node: HierarchyRectangularNode) => number; + /** + * Sets the right padding to the specified number and returns this treemap layout. + * The right padding is used to separate the right edge of a node from its children. + * + * @param padding The specified right padding value. + */ paddingRight(padding: number): this; + /** + * Sets the right padding to the specified function and returns this treemap layout. + * The function is invoked for each node with children, being passed the current node. + * The right padding is used to separate the right edge of a node from its children. + * + * @param padding The specified right padding function. + */ paddingRight(padding: (node: HierarchyRectangularNode) => number): this; + + /** + * Returns the current bottom padding function, which defaults to the constant zero. + */ paddingBottom(): (node: HierarchyRectangularNode) => number; + /** + * Sets the bottom padding to the specified number and returns this treemap layout. + * The bottom padding is used to separate the bottom edge of a node from its children. + * + * @param padding The specified bottom padding value. + */ paddingBottom(padding: number): this; + /** + * Sets the bottom padding to the specified function and returns this treemap layout. + * The function is invoked for each node with children, being passed the current node. + * The bottom padding is used to separate the bottom edge of a node from its children. + * + * @param padding The specified bottom padding function. + */ paddingBottom(padding: (node: HierarchyRectangularNode) => number): this; + + /** + * Returns the current left padding function, which defaults to the constant zero. + */ paddingLeft(): (node: HierarchyRectangularNode) => number; + /** + * Sets the left padding to the specified number and returns this treemap layout. + * The left padding is used to separate the left edge of a node from its children. + * + * @param padding The specified left padding value. + */ paddingLeft(padding: number): this; + /** + * Sets the left padding to the specified function and returns this treemap layout. + * The function is invoked for each node with children, being passed the current node. + * The left padding is used to separate the left edge of a node from its children. + * + * @param padding The specified left padding function. + */ paddingLeft(padding: (node: HierarchyRectangularNode) => number): this; } +/** + * Creates a new treemap layout with default settings. + */ export function treemap(): TreemapLayout; -// Tiling functions --------------------------------------------------------------------------------- +// Tiling functions ----------------------------------------------------------------------- +/** + * Recursively partitions the specified nodes into an approximately-balanced binary tree, + * choosing horizontal partitioning for wide rectangles and vertical partitioning for tall rectangles. + */ export function treemapBinary(node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number): void; + +/** + * Divides the rectangular area specified by x0, y0, x1, y1 horizontally according the value of each of the specified node’s children. + * The children are positioned in order, starting with the left edge (x0) of the given rectangle. + * If the sum of the children’s values is less than the specified node’s value (i.e., if the specified node has a non-zero internal value), + * the remaining empty space will be positioned on the right edge (x1) of the given rectangle. + */ export function treemapDice(node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number): void; + +/** + * Divides the rectangular area specified by x0, y0, x1, y1 vertically according the value of each of the specified node’s children. + * The children are positioned in order, starting with the top edge (y0) of the given rectangle. + * If the sum of the children’s values is less than the specified node’s value (i.e., if the specified node has a non-zero internal value), + * the remaining empty space will be positioned on the bottom edge (y1) of the given rectangle. + */ export function treemapSlice(node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number): void; + +/** + * If the specified node has odd depth, delegates to treemapSlice; otherwise delegates to treemapDice. + */ export function treemapSliceDice(node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number): void; // TODO: Test Factory code export interface RatioSquarifyTilingFactory { (node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number): void; + + /** + * Specifies the desired aspect ratio of the generated rectangles. + * Note that the orientation of the generated rectangles (tall or wide) is not implied by the ratio. + * Furthermore, the rectangles ratio are not guaranteed to have the exact specified aspect ratio. + * If not specified, the aspect ratio defaults to the golden ratio, φ = (1 + sqrt(5)) / 2, per Kong et al. + * + * @param ratio The specified ratio value greater than or equal to one. + */ ratio(ratio: number): RatioSquarifyTilingFactory; } +/** + * Implements the squarified treemap algorithm by Bruls et al., which seeks to produce rectangles of a given aspect ratio. + */ export const treemapSquarify: RatioSquarifyTilingFactory; + +/** + * Like `d3.treemapSquarify`, except preserves the topology (node adjacencies) of the previous layout computed by `d3.treemapResquarify`, + * if there is one and it used the same target aspect ratio. This tiling method is good for animating changes to treemaps because + * it only changes node sizes and not their relative positions, thus avoiding distracting shuffling and occlusion. + * The downside of a stable update, however, is a suboptimal layout for subsequent updates: only the first layout uses the Bruls et al. squarified algorithm. + */ export const treemapResquarify: RatioSquarifyTilingFactory; // ----------------------------------------------------------------------- @@ -228,15 +638,53 @@ export const treemapResquarify: RatioSquarifyTilingFactory; // ----------------------------------------------------------------------- export interface PartitionLayout { + /** + * Lays out the specified root hierarchy. + * You must call `root.sum` before passing the hierarchy to the partition layout. + * You probably also want to call `root.sort` to order the hierarchy before computing the layout. + * + * @param root The specified root hierarchy. + */ (root: HierarchyNode): HierarchyRectangularNode; + + /** + * Returns the current size, which defaults to [1, 1]. + */ size(): [number, number]; + /** + * Sets this partition layout’s size to the specified [width, height] array and returns this partition layout. + * + * @param size The specified two-element size array. + */ size(size: [number, number]): this; + + /** + * Returns the current rounding state, which defaults to false. + */ round(): boolean; + /** + * Enables or disables rounding according to the given boolean and returns this partition layout. + * + * @param round The specified boolean flag. + */ round(round: boolean): this; + + /** + * Returns the current padding, which defaults to zero. + */ padding(): number; + /** + * Sets the padding to the specified number and returns this partition layout. + * The padding is used to separate a node’s adjacent children. + * + * @param padding The specified padding value. + */ padding(padding: number): this; } +/** + * Creates a new partition layout with the default settings. + */ export function partition(): PartitionLayout; // ----------------------------------------------------------------------- @@ -244,54 +692,110 @@ export function partition(): PartitionLayout; // ----------------------------------------------------------------------- export interface HierarchyCircularLink { + /** + * The source of the link. + */ source: HierarchyCircularNode; + + /** + * The target of the link. + */ target: HierarchyCircularNode; } -export interface HierarchyCircularNode { +export interface HierarchyCircularNode extends HierarchyNode { + /** + * The x-coordinate of the circle’s center. + */ x: number; + + /** + * The y-coordinate of the circle’s center. + */ y: number; + + /** + * The radius of the circle. + */ r: number; - data: Datum; - readonly depth: number; - readonly height: number; - parent: HierarchyCircularNode | null; - children?: Array>; + /** - * Aggregated numeric value as calculated by sum(value) or count(), - * if previously invoked. + * Returns an array of links for this node, where each link is an object that defines source and target properties. + * The source of each link is the parent node, and the target is a child node. */ - readonly value?: number; - /** - * Optional Node Id string set by StratifyOperator, if - * hierarchical data was created from tabular data using stratify() - */ - readonly id?: string; - ancestors(): Array>; - descendants(): Array>; - leaves(): Array>; - path(target: HierarchyCircularNode): Array>; links(): Array>; - sum(value: (d: Datum) => number): this; - count(): this; - sort(compare: (a: HierarchyCircularNode, b: HierarchyCircularNode) => number): this; - each(func: (node: HierarchyCircularNode) => void): this; - eachAfter(func: (node: HierarchyCircularNode) => void): this; - eachBefore(func: (node: HierarchyCircularNode) => void): this; - copy(): HierarchyCircularNode; } export interface PackLayout { + /** + * Lays out the specified root hierarchy. + * You must call `root.sum` before passing the hierarchy to the pack layout. + * You probably also want to call `root.sort` to order the hierarchy before computing the layout. + * + * @param root The specified root hierarchy. + */ (root: HierarchyNode): HierarchyCircularNode; + + /** + * Returns the current radius accessor, which defaults to null. + */ radius(): null | ((node: HierarchyCircularNode) => number); + /** + * Sets the pack layout’s radius accessor to the specified function and returns this pack layout. + * If the radius accessor is null, the radius of each leaf circle is derived from the leaf `node.value` (computed by `node.sum`); + * the radii are then scaled proportionally to fit the layout size. + * If the radius accessor is not null, the radius of each leaf circle is specified exactly by the function. + * + * @param radius The specified radius accessor. + */ radius(radius: (node: HierarchyCircularNode) => number): this; + + /** + * Returns the current size, which defaults to [1, 1]. + */ size(): [number, number]; + /** + * Sets this pack layout’s size to the specified [width, height] array and returns this pack layout. + * + * @param size The specified two-element size array. + */ size(size: [number, number]): this; + + /** + * Returns the current padding accessor, which defaults to the constant zero. + */ padding(): (node: HierarchyCircularNode) => number; + /** + * Sets this pack layout’s padding accessor to the specified number and returns this pack layout. + * Returns the current padding accessor, which defaults to the constant zero. + * + * When siblings are packed, tangent siblings will be separated by approximately the specified padding; + * the enclosing parent circle will also be separated from its children by approximately the specified padding. + * If an explicit radius is not specified, the padding is approximate because a two-pass algorithm + * is needed to fit within the layout size: the circles are first packed without padding; + * a scaling factor is computed and applied to the specified padding; and lastly the circles are re-packed with padding. + * + * @param padding The specified padding value. + */ padding(padding: number): this; + /** + * Sets this pack layout’s padding accessor to the specified function and returns this pack layout. + * Returns the current padding accessor, which defaults to the constant zero. + * + * When siblings are packed, tangent siblings will be separated by approximately the specified padding; + * the enclosing parent circle will also be separated from its children by approximately the specified padding. + * If an explicit radius is not specified, the padding is approximate because a two-pass algorithm + * is needed to fit within the layout size: the circles are first packed without padding; + * a scaling factor is computed and applied to the specified padding; and lastly the circles are re-packed with padding. + * + * @param padding The specified padding function. + */ padding(padding: (node: HierarchyCircularNode) => number): this; } +/** + * Creates a new pack layout with the default settings. + */ export function pack(): PackLayout; // ----------------------------------------------------------------------- @@ -299,8 +803,19 @@ export function pack(): PackLayout; // ----------------------------------------------------------------------- export interface PackCircle { + /** + * The radius of the circle. + */ r: number; + + /** + * The x-coordinate of the circle’s center. + */ x?: number; + + /** + * The y-coordinate of the circle’s center. + */ y?: number; } @@ -309,6 +824,19 @@ export interface PackCircle { // For invocation of packEnclose the x and y coordinates are mandatory. It seems easier to just comment // on the mandatory nature, then to create separate interfaces and having to deal with recasting. +/** + * Packs the specified array of circles, each of which must have a `circle.r` property specifying the circle’s radius. + * The circles are positioned according to the front-chain packing algorithm by Wang et al. + * + * @param circles The specified array of circles to pack. + */ export function packSiblings(circles: Datum[]): Datum[]; +/** + * Computes the smallest circle that encloses the specified array of circles, each of which must have + * a `circle.r` property specifying the circle’s radius, and `circle.x` and `circle.y` properties specifying the circle’s center. + * The enclosing circle is computed using the Matoušek-Sharir-Welzl algorithm. (See also Apollonius’ Problem.) + * + * @param circles The specified array of circles to pack. + */ export function packEnclose(circles: Datum[]): { r: number, x: number, y: number }; diff --git a/types/detect-node/detect-node-tests.ts b/types/detect-node/detect-node-tests.ts new file mode 100644 index 0000000000..01a81a356b --- /dev/null +++ b/types/detect-node/detect-node-tests.ts @@ -0,0 +1,3 @@ +import isNode = require("detect-node"); + +isNode; diff --git a/types/detect-node/index.d.ts b/types/detect-node/index.d.ts new file mode 100644 index 0000000000..38fd280f1e --- /dev/null +++ b/types/detect-node/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for detect-node 2.0 +// Project: https://github.com/iliakan/detect-node +// Definitions by: Leonid Logvinov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +declare const isNode: boolean; +export = isNode; diff --git a/types/detect-node/tsconfig.json b/types/detect-node/tsconfig.json new file mode 100644 index 0000000000..e853bcf92c --- /dev/null +++ b/types/detect-node/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "detect-node-tests.ts"] +} diff --git a/types/detect-node/tslint.json b/types/detect-node/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/detect-node/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index 3583889a74..93babaa0a7 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -328,11 +328,11 @@ declare module 'ember' { */ resolveRegistration(fullName: string): Function; /** - * Registers a factory that can be used for dependency injection (with + * Registers a factory or value that can be used for dependency injection (with * `inject`) or for service lookup. Each factory is registered with * a full name including two parts: `type:name`. */ - register(fullName: string, factory: Function, options?: { singleton?: boolean, instantiate?: boolean }): any; + register(fullName: string, factory: any, options?: { singleton?: boolean, instantiate?: boolean }): any; /** * Unregister a factory. */ @@ -3372,7 +3372,48 @@ declare module 'ember' { /** * The Router service is the public API that provides component/view layer access to the router. */ - class RouterService extends Ember.Service { + export class RouterService extends Ember.Service { + // + /** + Name of the current route. + This property represent the logical name of the route, + which is comma separated. + For the following router: + ```app/router.js + Router.map(function() { + this.route('about'); + this.route('blog', function () { + this.route('post', { path: ':post_id' }); + }); + }); + ``` + It will return: + * `index` when you visit `/` + * `about` when you visit `/about` + * `blog.index` when you visit `/blog` + * `blog.post` when you visit `/blog/some-post-id` + */ + readonly currentRouteName: string; + // + /** + Current URL for the application. + This property represent the URL path for this route. + For the following router: + ```app/router.js + Router.map(function() { + this.route('about'); + this.route('blog', function () { + this.route('post', { path: ':post_id' }); + }); + }); + ``` + It will return: + * `/` when you visit `/` + * `/about` when you visit `/about` + * `/blog` when you visit `/blog` + * `/blog/some-post-id` when you visit `/blog/some-post-id` + */ + readonly currentURL: string; // /** * Determines whether a route is active. @@ -3776,6 +3817,11 @@ declare module '@ember/routing/router' { export default class EmberRouter extends Ember.Router { } } +declare module '@ember/routing/router-service' { + import { RouterService } from 'ember'; + export default class extends RouterService { } +} + declare module '@ember/runloop' { import Ember from 'ember'; export const begin: typeof Ember.run.begin; diff --git a/types/ember/test/application-instance.ts b/types/ember/test/application-instance.ts index 9881e4815a..9ae22e5f26 100644 --- a/types/ember/test/application-instance.ts +++ b/types/ember/test/application-instance.ts @@ -1,4 +1,5 @@ import ApplicationInstance from '@ember/application/instance'; +import hbs from 'htmlbars-inline-precompile'; const appInstance = ApplicationInstance.create(); appInstance.register('some:injection', class Foo {}); @@ -11,6 +12,8 @@ appInstance.register('some:injection', class Foo {}, { instantiate: false, }); +appInstance.register('templates:foo/bar', hbs`

Hello World

`); + appInstance.register('some:injection', class Foo {}, { singleton: false, instantiate: true, diff --git a/types/ember/test/router.ts b/types/ember/test/router.ts index ff5f4c554f..760e9ed5bc 100755 --- a/types/ember/test/router.ts +++ b/types/ember/test/router.ts @@ -1,4 +1,5 @@ import Ember from 'ember'; +import { assertType } from './lib/assert'; const AppRouter = Ember.Router.extend({ }); @@ -25,6 +26,12 @@ AppRouter.map(function() { const RouterServiceConsumer = Ember.Service.extend({ router: Ember.inject.service('router'), + currentRouteName() { + const x: string = Ember.get(this, 'router').currentRouteName; + }, + currentURL() { + const x: string = Ember.get(this, 'router').currentURL; + }, transitionWithoutModel() { Ember.get(this, 'router') .transitionTo('some-route'); diff --git a/types/espruino/espruino-tests.ts b/types/espruino/espruino-tests.ts index 32f044796d..c1bafc9048 100644 --- a/types/espruino/espruino-tests.ts +++ b/types/espruino/espruino-tests.ts @@ -10,5 +10,8 @@ wifi.startAP('ssid', { password: 'pass', authMode: 'wpa_wpa2' }, err => { console.log("created"); }); +digitalWrite(D2, false); +digitalWrite(D2, true); + I2C1.setup({ scl: D4, sda: D0 }); Serial2.setup(9600, { rx: D16, tx: D17 }); diff --git a/types/espruino/index.d.ts b/types/espruino/index.d.ts index 61cf72f173..cb6151e85a 100644 --- a/types/espruino/index.d.ts +++ b/types/espruino/index.d.ts @@ -3600,7 +3600,7 @@ declare function digitalPulse(pin: Pin, value: boolean, time: any): void; * @param value * @url http://www.espruino.com/Reference#l__global_digitalWrite */ -declare function digitalWrite(pin: Pin, value: number): void; +declare function digitalWrite(pin: Pin, value: number | boolean): void; /** *

Get the digital value of the given pin.

diff --git a/types/eth-lightwallet/eth-lightwallet-tests.ts b/types/eth-lightwallet/eth-lightwallet-tests.ts new file mode 100644 index 0000000000..4907c73cbf --- /dev/null +++ b/types/eth-lightwallet/eth-lightwallet-tests.ts @@ -0,0 +1,3 @@ +import * as lw from "eth-lightwallet"; + +lw.keystore.createVault({}); diff --git a/types/eth-lightwallet/index.d.ts b/types/eth-lightwallet/index.d.ts new file mode 100644 index 0000000000..f55e71884e --- /dev/null +++ b/types/eth-lightwallet/index.d.ts @@ -0,0 +1,64 @@ +// Type definitions for eth-lightwallet 3.0 +// Project: https://github.com/ConsenSys/eth-lightwallet#readme +// Definitions by: Leonid Logvinov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// + +export interface ECSignatureBuffer { + v: number; + r: Buffer; + s: Buffer; +} +export namespace signing { + function signTx( + keystore: keystore, + pwDerivedKey: Uint8Array, + rawTx: string, + signingAddress: string + ): string; + function signMsg( + keystore: keystore, + pwDerivedKey: Uint8Array, + rawMsg: string, + signingAddress: string + ): ECSignatureBuffer; + function signMsgHash( + keystore: keystore, + pwDerivedKey: Uint8Array, + msgHash: string, + signingAddress: string + ): ECSignatureBuffer; + function concatSig(signature: any): string; +} + +export class keystore { + static createVault( + options: any, + callback?: (error: Error, keystore: keystore) => void + ): keystore; + static generateRandomSeed(): string; + static isSeedValid(seed: string): boolean; + static deserialize(keystore: string): keystore; + serialize(): string; + keyFromPassword( + password: string, + callback?: (error: Error, pwDerivedKey: Uint8Array) => void + ): Uint8Array; + isDerivedKeyCorrect(pwDerivedKey: Uint8Array): boolean; + generateNewAddress( + pwDerivedKey: Uint8Array, + numberOfAddresses: number + ): void; + getSeed(pwDerivedKey: Uint8Array): string; + exportPrivateKey(address: string, pwDerivedKey: Uint8Array): string; + getAddresses(): string[]; +} + +export interface VaultOptions { + password: string; + seedPhrase: string; + salt?: string; + hdPathString: string; +} diff --git a/types/eth-lightwallet/tsconfig.json b/types/eth-lightwallet/tsconfig.json new file mode 100644 index 0000000000..80eab8563a --- /dev/null +++ b/types/eth-lightwallet/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", + "eth-lightwallet-tests.ts" + ] +} diff --git a/types/eth-lightwallet/tslint.json b/types/eth-lightwallet/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/eth-lightwallet/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/figlet/figlet-tests.ts b/types/figlet/figlet-tests.ts new file mode 100644 index 0000000000..676fb9003f --- /dev/null +++ b/types/figlet/figlet-tests.ts @@ -0,0 +1,95 @@ +import figlet = require('figlet'); + +figlet('abc', (err, str) => { + // $ExpectType Error | null + err; + // $ExpectType string | undefined + str; +}); +figlet('My World', '1Row', (err, str) => { + // $ExpectType Error | null + err; + // $ExpectType string | undefined + str; +}); +// $ExpectError +figlet('fweGWEPewfe', 'What is the font? I cannot get it'); +// $ExpectError +figlet('qweoqw'); +// $ExpectError +figlet('qweoqw', '1Row'); +// $ExpectError +figlet('qweoqw', '1Row', undefined as any, undefined as any); + +figlet.text('tokiyo tomare', (err, str) => { + // $ExpectType Error | null + err; + // $ExpectType string | undefined + str; +}); +figlet.text('Hi', 'Flower Power', (err, str) => { + // $ExpectType Error | null + err; + // $ExpectType string | undefined + str; +}); +figlet.text('Annyeong', { + font: 'Fun Face', + horizontalLayout: 'full', + verticalLayout: 'fitted', +}, (err, str) => { + // $ExpectType Error | null + err; + // $ExpectType string | undefined + str; +}); +figlet.text('Oreehe', { + font: 'Fun Face', + // $ExpectError + value: 'abc', +}, undefined as any); +// $ExpectError +figlet.text('It cannot make sense'); + +// $ExpectType string +figlet.textSync('test text'); +// $ExpectType string +figlet.textSync('text desu', 'Fuzzy'); +// $ExpectType string +figlet.textSync('oho', { + font: 'Invita', +}); +// $ExpectError +figlet.textSync(); + +figlet.metadata('JS Block Letters', (err, fontOptions, headerComment) => { + // $ExpectType Error | null + err; + // $ExpectType FontOptions | undefined + fontOptions; + // $ExpectType string | undefined + headerComment; +}); +// $ExpectError +figlet.metadata('This is random font name which cannot make sense', undefined as any); +// $ExpectError +figlet.metadata('Alligator', undefined as any, undefined as any); + +// $ExpectType Defaults +figlet.defaults(); +// $ExpectType Defaults +figlet.defaults({}); +// $ExpectType Defaults +figlet.defaults({ + font: 'Patorjk\'s Cheese' +}); + +figlet.fonts((err, fonts) => { + // $ExpectType Error | null + err; + // $ExpectType Fonts[] | undefined + fonts; +}); + +// $ExpectType Fonts[] +figlet.fontsSync(); diff --git a/types/figlet/index.d.ts b/types/figlet/index.d.ts new file mode 100644 index 0000000000..07bb706066 --- /dev/null +++ b/types/figlet/index.d.ts @@ -0,0 +1,406 @@ +// Type definitions for figlet 1.2 +// Project: https://github.com/patorjk/figlet.js +// Definitions by: Junyoung Clare Jang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.1 + +declare namespace figlet { + type Fonts = + | '1Row' + | '3-D' + | '3D Diagonal' + | '3D-ASCII' + | '3x5' + | '4Max' + | '5 Line Oblique' + | 'AMC 3 Line' + | 'AMC 3 Liv1' + | 'AMC AAA01' + | 'AMC Neko' + | 'AMC Razor' + | 'AMC Razor2' + | 'AMC Slash' + | 'AMC Slider' + | 'AMC Thin' + | 'AMC Tubes' + | 'AMC Untitled' + | 'ANSI Shadow' + | 'ASCII New Roman' + | 'Acrobatic' + | 'Alligator' + | 'Alligator2' + | 'Alpha' + | 'Alphabet' + | 'Arrows' + | 'Avatar' + | 'B1FF' + | 'B1FF' + | 'Banner' + | 'Banner3-D' + | 'Banner3' + | 'Banner4' + | 'Barbwire' + | 'Basic' + | 'Bear' + | 'Bell' + | 'Benjamin' + | 'Big Chief' + | 'Big Money-ne' + | 'Big Money-nw' + | 'Big Money-se' + | 'Big Money-sw' + | 'Big' + | 'Bigfig' + | 'Binary' + | 'Block' + | 'Blocks' + | 'Bloody' + | 'Bolger' + | 'Braced' + | 'Bright' + | 'Broadway KB' + | 'Broadway' + | 'Bubble' + | 'Bulbhead' + | 'Caligraphy' + | 'Caligraphy2' + | 'Calvin S' + | 'Cards' + | 'Catwalk' + | 'Chiseled' + | 'Chunky' + | 'Coinstak' + | 'Cola' + | 'Colossal' + | 'Computer' + | 'Contessa' + | 'Contrast' + | 'Cosmike' + | 'Crawford' + | 'Crawford2' + | 'Crazy' + | 'Cricket' + | 'Cursive' + | 'Cyberlarge' + | 'Cybermedium' + | 'Cybersmall' + | 'Cygnet' + | 'DANC4' + | 'DOS Rebel' + | 'DWhistled' + | 'Dancing Font' + | 'Decimal' + | 'Def Leppard' + | 'Delta Corps Priest 1' + | 'Diamond' + | 'Diet Cola' + | 'Digital' + | 'Doh' + | 'Doom' + | 'Dot Matrix' + | 'Double Shorts' + | 'Double' + | 'Dr Pepper' + | 'Efti Chess' + | 'Efti Font' + | 'Efti Italic' + | 'Efti Piti' + | 'Efti Robot' + | 'Efti Wall' + | 'Efti Water' + | 'Electronic' + | 'Elite' + | 'Epic' + | 'Fender' + | 'Filter' + | 'Fire Font-k' + | 'Fire Font-s' + | 'Flipped' + | 'Flower Power' + | 'Four Tops' + | 'Fraktur' + | 'Fun Face' + | 'Fun Faces' + | 'Fuzzy' + | 'Georgi16' + | 'Georgia11' + | 'Ghost' + | 'Ghoulish' + | 'Glenyn' + | 'Goofy' + | 'Gothic' + | 'Graceful' + | 'Gradient' + | 'Graffiti' + | 'Greek' + | 'Heart Left' + | 'Heart Right' + | 'Henry 3D' + | 'Hex' + | 'Hieroglyphs' + | 'Hollywood' + | 'Horizontal Left' + | 'Horizontal Right' + | 'ICL-1900' + | 'Impossible' + | 'Invita' + | 'Isometric1' + | 'Isometric2' + | 'Isometric3' + | 'Isometric4' + | 'Italic' + | 'Ivrit' + | 'JS Block Letters' + | 'JS Bracket Letters' + | 'JS Capital Curves' + | 'JS Cursive' + | 'JS Stick Letters' + | 'Jacky' + | 'Jazmine' + | 'Jerusalem' + | 'Katakana' + | 'Kban' + | 'Keyboard' + | 'Knob' + | 'Konto Slant' + | 'Konto' + | 'LCD' + | 'Larry 3D 2' + | 'Larry 3D' + | 'Lean' + | 'Letters' + | 'Lil Devil' + | 'Line Blocks' + | 'Linux' + | 'Lockergnome' + | 'Madrid' + | 'Marquee' + | 'Maxfour' + | 'Merlin1' + | 'Merlin2' + | 'Mike' + | 'Mini' + | 'Mirror' + | 'Mnemonic' + | 'Modular' + | 'Morse' + | 'Morse2' + | 'Moscow' + | 'Mshebrew210' + | 'Muzzle' + | 'NScript' + | 'NT Greek' + | 'NV Script' + | 'Nancyj-Fancy' + | 'Nancyj-Improved' + | 'Nancyj-Underlined' + | 'Nancyj' + | 'Nipples' + | 'O8' + | 'OS2' + | 'Octal' + | 'Ogre' + | 'Old Banner' + | 'Patorjk\'s Cheese' + | 'Patorjk-HeX' + | 'Pawp' + | 'Peaks Slant' + | 'Peaks' + | 'Pebbles' + | 'Pepper' + | 'Poison' + | 'Puffy' + | 'Puzzle' + | 'Pyramid' + | 'Rammstein' + | 'Rectangles' + | 'Red Phoenix' + | 'Relief' + | 'Relief2' + | 'Reverse' + | 'Roman' + | 'Rot13' + | 'Rot13' + | 'Rotated' + | 'Rounded' + | 'Rowan Cap' + | 'Rozzo' + | 'Runic' + | 'Runyc' + | 'S Blood' + | 'SL Script' + | 'Santa Clara' + | 'Script' + | 'Serifcap' + | 'Shadow' + | 'Shimrod' + | 'Short' + | 'Slant Relief' + | 'Slant' + | 'Slide' + | 'Small Caps' + | 'Small Isometric1' + | 'Small Keyboard' + | 'Small Poison' + | 'Small Script' + | 'Small Shadow' + | 'Small Slant' + | 'Small Tengwar' + | 'Small' + | 'Soft' + | 'Speed' + | 'Spliff' + | 'Stacey' + | 'Stampate' + | 'Stampatello' + | 'Standard' + | 'Star Strips' + | 'Star Wars' + | 'Stellar' + | 'Stforek' + | 'Stick Letters' + | 'Stop' + | 'Straight' + | 'Stronger Than All' + | 'Sub-Zero' + | 'Swamp Land' + | 'Swan' + | 'Sweet' + | 'THIS' + | 'Tanja' + | 'Tengwar' + | 'Term' + | 'Test1' + | 'The Edge' + | 'Thick' + | 'Thin' + | 'Thorned' + | 'Three Point' + | 'Ticks Slant' + | 'Ticks' + | 'Tiles' + | 'Tinker-Toy' + | 'Tombstone' + | 'Train' + | 'Trek' + | 'Tsalagi' + | 'Tubular' + | 'Twisted' + | 'Two Point' + | 'USA Flag' + | 'Univers' + | 'Varsity' + | 'Wavy' + | 'Weird' + | 'Wet Letter' + | 'Whimsy' + | 'Wow' + ; + + type KerningMethods = + | 'default' + | 'full' + | 'fitted' + | 'controlled smushing' + | 'universal smushing' + ; + type PrintDirection = number; + + interface FittingRules { + vLayout: number; + vRule5: boolean; + vRule4: boolean; + vRule3: boolean; + vRule2: boolean; + vRule1: boolean; + hLayout: number; + hRule6: boolean; + hRule5: boolean; + hRule4: boolean; + hRule3: boolean; + hRule2: boolean; + hRule1: boolean; + } + + interface Options { + font?: Fonts; + horizontalLayout?: KerningMethods; + verticalLayout?: KerningMethods; + printDirection?: PrintDirection; + showHardBlanks?: boolean; + } + interface FontOptions { + hardBlank: string; + height: number; + baseline: number; + maxLength: number; + oldLayout: number; + numCommentLines: number; + printDirection: PrintDirection; + fullLayout: number | null; + codeTagCount: number | null; + fittingRules: FittingRules; + } + interface Defaults { + font: Fonts; + fontPath: string; + } + + function text(txt: string, cb: (error: Error | null, result?: string) => void): void; + function text(txt: string, font: Fonts, cb: (error: Error | null, result?: string) => void): void; + /** + * @desc + * This `unified-signatures` is disabled because `Fonts` type is too long + */ + // tslint:disable-next-line: unified-signatures + function text(txt: string, options: Options | undefined, cb: (error: Error | null, result?: string) => void): void; + + function textSync(txt: string, font?: Fonts): string; + /** + * @desc + * This `unified-signatures` is disabled because `Fonts` type is too long + */ + // tslint:disable-next-line: unified-signatures + function textSync(txt: string, options: Options): string; + + function metadata(font: Fonts, cb: (error: Error | null, fontOptions?: FontOptions, headerComment?: string) => void): void; + + function defaults(opt?: Partial): Defaults; + + function loadFont(font: Fonts, cb: (error: Error | null, fontOptions?: FontOptions) => void): void; + /** + * @todo + * Use 'node' namespace to add following methods only in node environment. + */ + /** + * @warn + * This method works in node environment only. + * In browser environment, this method does not work. + */ + function loadFontSync(font: Fonts): FontOptions; + /** + * @warn + * This method exists in node environment only. + * In browser environment, this method does not exist. + */ + function fonts(cb: (error: Error | null, fontList?: Fonts[]) => void): void; + /** + * @warn + * This method exists in node environment only. + * In browser environment, this method does not exist. + */ + function fontsSync(): Fonts[]; +} + +declare function figlet(txt: string, cb: (error: Error | null, result?: string) => void): void; +declare function figlet(txt: string, font: figlet.Fonts, cb: (error: Error | null, result?: string) => void): void; +/** + * @desc + * This `unified-signatures` is disabled because `Fonts` type is too long + */ +// tslint:disable-next-line: unified-signatures +declare function figlet(txt: string, options: figlet.Options | undefined, cb: (error: Error | null, result?: string) => void): void; + +export as namespace figlet; +export = figlet; diff --git a/types/figlet/tsconfig.json b/types/figlet/tsconfig.json new file mode 100644 index 0000000000..946bec6c7d --- /dev/null +++ b/types/figlet/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "figlet-tests.ts" + ] +} diff --git a/types/figlet/tslint.json b/types/figlet/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/figlet/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/google-cloud__pubsub/index.d.ts b/types/google-cloud__pubsub/index.d.ts index 130e62a5e4..9375b55860 100644 --- a/types/google-cloud__pubsub/index.d.ts +++ b/types/google-cloud__pubsub/index.d.ts @@ -1,7 +1,8 @@ // Type definitions for @google-cloud/pubsub 0.18 -// Project: https://github.com/GoogleCloudPlatform/google-cloud-node/tree/master/packages/pubsub +// Project: https://github.com/googleapis/nodejs-pubsub // Definitions by: Paul Huynh // LunaPg +// Marco Siviero // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -115,11 +116,15 @@ declare namespace PubSub { interface Publisher { publish(data: Buffer, callback: Publisher.PublishCallback): void; - publish(data: Buffer, attributes: object, callback: Publisher.PublishCallback): void; - publish(data: Buffer, attributes?: object): Promise; + publish(data: Buffer, attributes: Publisher.Attributes, callback: Publisher.PublishCallback): void; + publish(data: Buffer, attributes?: Publisher.Attributes): Promise; } namespace Publisher { type PublishCallback = (error: Error | null, messageId: string) => void; + + interface Attributes { + [key: string]: string | Buffer | ArrayBuffer; + } } interface Snapshot { diff --git a/types/gulp-imagemin/gulp-imagemin-tests.ts b/types/gulp-imagemin/gulp-imagemin-tests.ts new file mode 100644 index 0000000000..7fc1d86311 --- /dev/null +++ b/types/gulp-imagemin/gulp-imagemin-tests.ts @@ -0,0 +1,20 @@ +import * as GulpImagemin from 'gulp-imagemin'; + +GulpImagemin(); + +GulpImagemin([ + GulpImagemin.gifsicle({ interlaced: true }), + GulpImagemin.jpegtran({ progressive: true }), + GulpImagemin.optipng({ optimizationLevel: 5 }), + GulpImagemin.svgo({ + plugins: [{ removeViewBox: true }, { cleanupIDs: false }] + }) +]); + +GulpImagemin({ verbose: true }); + +GulpImagemin([ + GulpImagemin.svgo({ + plugins: [{ removeViewBox: true }] + }) +], { verbose: true }); diff --git a/types/gulp-imagemin/index.d.ts b/types/gulp-imagemin/index.d.ts new file mode 100644 index 0000000000..42c1ef8d5c --- /dev/null +++ b/types/gulp-imagemin/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for gulp-imagemin 4.1 +// Project: https://github.com/sindresorhus/gulp-imagemin#readme +// Definitions by: Romain Faust +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Transform } from 'stream'; + +declare function imagemin(pluginsOrOptions?: imagemin.Plugin[] | imagemin.Options): Transform; +declare function imagemin(plugins?: imagemin.Plugin[], options?: imagemin.Options): Transform; + +declare namespace imagemin { + interface Options { + verbose?: boolean; + } + + type Plugin = (input: any) => Promise; + type PluginFactory = (options?: any) => Plugin; + + const gifsicle: PluginFactory; + const jpegtran: PluginFactory; + const optipng: PluginFactory; + const svgo: PluginFactory; +} + +export = imagemin; diff --git a/types/gulp-imagemin/tsconfig.json b/types/gulp-imagemin/tsconfig.json new file mode 100644 index 0000000000..1b35a74382 --- /dev/null +++ b/types/gulp-imagemin/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", + "gulp-imagemin-tests.ts" + ] +} diff --git a/types/gulp-imagemin/tslint.json b/types/gulp-imagemin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gulp-imagemin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/history/index.d.ts b/types/history/index.d.ts index eb15aaa0fc..1c7b35b8f2 100644 --- a/types/history/index.d.ts +++ b/types/history/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for history 4.6.2 +// Type definitions for history 4.7.2 // Project: https://github.com/mjackson/history // Definitions by: Sergey Buturlakin , Nathan Brown , Young Rok Kim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 export as namespace History; export type Action = 'PUSH' | 'POP' | 'REPLACE'; @@ -23,24 +24,24 @@ export interface History { createHref(location: LocationDescriptorObject): Href; } -export interface Location { +export interface Location { pathname: Pathname; search: Search; - state: LocationState; + state: S; hash: Hash; key?: LocationKey; } -export interface LocationDescriptorObject { +export interface LocationDescriptorObject { pathname?: Pathname; search?: Search; - state?: LocationState; + state?: S; hash?: Hash; key?: LocationKey; } export namespace History { - export type LocationDescriptor = Path | LocationDescriptorObject; + export type LocationDescriptor = Path | LocationDescriptorObject; export type LocationKey = string; export type LocationListener = (location: Location, action: Action) => void; export type LocationState = any; @@ -53,7 +54,7 @@ export namespace History { export type Href = string; } -export type LocationDescriptor = History.LocationDescriptor; +export type LocationDescriptor = History.LocationDescriptor; export type LocationKey = History.LocationKey; export type LocationListener = History.LocationListener; export type LocationState = History.LocationState; diff --git a/types/hoist-non-react-statics/hoist-non-react-statics-tests.ts b/types/hoist-non-react-statics/hoist-non-react-statics-tests.ts new file mode 100644 index 0000000000..7065c47410 --- /dev/null +++ b/types/hoist-non-react-statics/hoist-non-react-statics-tests.ts @@ -0,0 +1,31 @@ +import * as React from 'react'; + +import hoistNonReactStatics = require('hoist-non-react-statics'); + +class A extends React.Component { + static a = 'a'; + + getA() { + return A.a; + } +} + +class B extends React.Component { + static b = 'b'; + + getB() { + return B.b; + } +} + +const C = hoistNonReactStatics(A, B); + +C.a !== C.b; + +C.prototype.getA(); // should work +// C.prototype.getB(); // should emit an error + +const D = hoistNonReactStatics(A, B, { b: true }); + +D.a; +// D.b; // should emit an error diff --git a/types/hoist-non-react-statics/index.d.ts b/types/hoist-non-react-statics/index.d.ts new file mode 100644 index 0000000000..f55fb92b6d --- /dev/null +++ b/types/hoist-non-react-statics/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for hoist-non-react-statics 3.0 +// Project: https://github.com/mridgway/hoist-non-react-statics#readme +// Definitions by: JounQin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +declare function hoistNonReactStatics< + T extends React.ComponentType, + S extends React.ComponentType, + C extends { + [key: string]: true + } = {} +>( + TargetComponent: T, + SourceComponent: S, + customStatic?: C, +): T & + { + [key in Exclude< + keyof S, + // only extends static properties, exclude instance properties + 'prototype' | keyof C + >]: S[key] + }; + +export = hoistNonReactStatics; diff --git a/types/hoist-non-react-statics/tsconfig.json b/types/hoist-non-react-statics/tsconfig.json new file mode 100644 index 0000000000..61c70382e5 --- /dev/null +++ b/types/hoist-non-react-statics/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", + "hoist-non-react-statics-tests.ts" + ] +} diff --git a/types/hoist-non-react-statics/tslint.json b/types/hoist-non-react-statics/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hoist-non-react-statics/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jquery.fileupload/index.d.ts b/types/jquery.fileupload/index.d.ts index 6ca998d41a..28bbf3c969 100644 --- a/types/jquery.fileupload/index.d.ts +++ b/types/jquery.fileupload/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for jQuery File Upload Plugin 5.40.1 +// Type definitions for jQuery File Upload Plugin 9.22.0 // Project: https://github.com/blueimp/jQuery-File-Upload // Definitions by: Rob Alarcon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,7 +6,7 @@ /// -// Interface options for the plugin +// Interface options for the plugin interface JQueryFileInputOptions { /** @@ -106,8 +106,8 @@ interface JQueryFileInputOptions { */ redirectParamName?: string; - // The HTTP request method must be "POST" or "PUT" - type?: string, + // The HTTP request method must be "POST" or "PUT" + type?: string, /** * Set the following option to the location of a postMessage window, @@ -199,7 +199,7 @@ interface JQueryFileInputOptions { * handlers using jQuery's Deferred callbacks: * data.submit().done(func).fail(func).always(func); */ - add?: (e: JQueryEventObject, data: JQueryFileInputOptions) => void; + add?: (e: JQueryEventObject, data: JqueryFileUploadAddObject) => void; // The plugin options are used as settings object for the ajax calls. // The following are jQuery ajax settings required for the file uploads: @@ -209,7 +209,7 @@ interface JQueryFileInputOptions { cache?: boolean; timeout?: number; - + active?: Function; progress?: (e: JQueryEventObject, data: JQueryFileUploadProgressObject) => void; send?: (e: JQueryEventObject, data: JQueryFileUploadProgressObject) => void; @@ -217,13 +217,13 @@ interface JQueryFileInputOptions { // Validation /** - * The maximum allowed file size in bytes. - * Type: integer - * Default: undefined - * Example: 10000000 // 10 MB - * Note: This option has only an effect for browsers supporting the File API. - * @see https://github.com/blueimp/jQuery-File-Upload/wiki/Options#maxfilesize - */ + * The maximum allowed file size in bytes. + * Type: integer + * Default: undefined + * Example: 10000000 // 10 MB + * Note: This option has only an effect for browsers supporting the File API. + * @see https://github.com/blueimp/jQuery-File-Upload/wiki/Options#maxfilesize + */ maxFileSize?: number; // Other callbacks: @@ -243,7 +243,7 @@ interface JQueryFileInputOptions { chunkfail?: (e: JQueryEventObject, data: JQueryFileUploadChunkObject) => void; chunkalways?: (e: JQueryEventObject, data: JQueryFileUploadChunkObject) => void; - // Others + // Others url?: string; files?: any; @@ -263,6 +263,12 @@ interface JQuery { fileupload(action: string, message:string, settings: JQueryFileInputOptions | string): JQueryFileUpload; } +interface JqueryFileUploadEnhancedPromise extends JQueryPromise{ + success: JQueryPromise['done'], + error: JQueryPromise['fail'], + complete: JQueryPromise['always'], +} + interface JQuerySupport { fileInput?: boolean; } @@ -275,6 +281,20 @@ interface JQueryFileUploadChangeObject { originalFiles: File[]; } +interface JqueryFileUploadConvenienceObject { + abort: () => JqueryFileUploadEnhancedPromise; + process: (resolveFunc?: Function, rejectFunc?: Function) => JqueryFileUploadEnhancedPromise; + processing: () => JqueryFileUploadEnhancedPromise; + progress: () => JqueryFileUploadEnhancedPromise; + response: () => JqueryFileUploadEnhancedPromise; + submit(): JqueryFileUploadEnhancedPromise; + state: () => JqueryFileUploadEnhancedPromise; +} + +interface JqueryFileUploadAddObject extends JQueryFileUploadChangeObject, JqueryFileUploadConvenienceObject { + paramName?: string | string[]; +} + interface JQueryFileUploadProgressAllObject { loaded?: number; total?: number; @@ -304,4 +324,4 @@ interface JQueryFileUploadProgressObject extends JQueryFileInputOptions, JQueryF } interface JQueryFileUploadDone extends JQueryFileInputOptions, JQueryFileUploadXhr { -} +} \ No newline at end of file diff --git a/types/jquery.gridster/index.d.ts b/types/jquery.gridster/index.d.ts index c91fd6f9e4..0106b448c6 100644 --- a/types/jquery.gridster/index.d.ts +++ b/types/jquery.gridster/index.d.ts @@ -10,23 +10,23 @@ gridster-0.1.0.d.ts may be freely distributed under the MIT license. Copyright (c) 2013 Josh Baldwin https://github.com/jbaldwin/gridster.d.ts Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ @@ -104,7 +104,7 @@ interface GridsterOptions { * Base widget dimensions in pixels. The first index for the width and the second for the height. * Default = [400, 225] **/ - widget_base_dimensions?: number[]; + widget_base_dimensions?: ('auto'|number)[]; /** * Add more columns in addition to those that have been calculated. @@ -292,7 +292,7 @@ interface Gridster { * @return Returns the instance of the Gridster class. **/ enable(): Gridster; - + /** * Disables dragging. * @return Returns the instance of the Gridster class. diff --git a/types/jquery.gridster/jquery.gridster-tests.ts b/types/jquery.gridster/jquery.gridster-tests.ts index 4dc3e3f27e..6703dea785 100644 --- a/types/jquery.gridster/jquery.gridster-tests.ts +++ b/types/jquery.gridster/jquery.gridster-tests.ts @@ -28,6 +28,9 @@ var position = coords.col + coords.row; options.widget_base_dimensions = [100, 200]; gridster.resize_widget_dimensions(options); +options.widget_base_dimensions = ['auto', 200]; +gridster.resize_widget_dimensions(options); + gridster.set_widget_min_size(0, [1, 2]); function noOptions() { @@ -48,13 +51,13 @@ function widgetSelectorString() { }; var grid: Gridster = $('.gridster ul').gridster(opts).data('gridster') -} +} function withNamespace() { var grid: Gridster = $('.gridster ul').gridster({ namespace: 'custom-gridster' }).data('gridster') -} +} function withStylesheet() { var grid: Gridster = $('.gridster ul').gridster({ diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index f6be274a30..fe8d46658a 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -286,12 +286,6 @@ declare namespace Knex { (columnName: string): QueryBuilder; } - interface WhereIn { - (columnName: string, values: Value[]): QueryBuilder; - (columnName: string, callback: QueryCallback): QueryBuilder; - (columnName: string, query: QueryBuilder): QueryBuilder; - } - interface WhereBetween { (columnName: string, range: [Value, Value]): QueryBuilder; } @@ -306,7 +300,8 @@ declare namespace Knex { } interface WhereIn { - (columnName: string, values: Value[]): QueryBuilder; + (columnName: string, values: Value[] | QueryBuilder | QueryCallback): QueryBuilder; + (columnNames: string[], values: Value[][] | QueryBuilder | QueryCallback): QueryBuilder; } interface GroupBy extends RawQueryBuilder, ColumnNameQueryBuilder { diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index 0c04dfc918..329ed9d414 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -1123,3 +1123,25 @@ knex({ table1Id: 'table1.id', table2Id: 'table2.id' }); + +knex('characters') + .select() + .whereIn(['name', 'class'], [['Bar', 'Fighter'], ['Foo', 'Druid']]); + +knex('characters') + .select() + .whereIn('name', knex('characters').select('name')); +knex('characters') + .select() + .whereIn(['name', 'class'], knex('characters').select('name', 'class')); + +knex('characters') + .select() + .whereIn('name', function() { + this.select('name').from('characters'); + }); +knex('characters') + .select() + .whereIn(['name', 'class'], function() { + this.select('name', 'class').from('characters'); + }); diff --git a/types/koa-html-minifier/index.d.ts b/types/koa-html-minifier/index.d.ts new file mode 100644 index 0000000000..5343257116 --- /dev/null +++ b/types/koa-html-minifier/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for koa-html-minifier 1.0 +// Project: https://github.com/koajs/html-minifier +// Definitions by: Romain Faust +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Middleware } from 'koa'; +import { Options } from 'html-minifier'; + +declare function minifier(options?: Options): Middleware; + +declare namespace minifier {} + +export = minifier; diff --git a/types/koa-html-minifier/koa-html-minifier-tests.ts b/types/koa-html-minifier/koa-html-minifier-tests.ts new file mode 100644 index 0000000000..c068d303af --- /dev/null +++ b/types/koa-html-minifier/koa-html-minifier-tests.ts @@ -0,0 +1,8 @@ +import * as Koa from 'koa'; +import * as KoaHtmlMinifier from 'koa-html-minifier'; + +const app = new Koa() + .use(KoaHtmlMinifier()) + .use(KoaHtmlMinifier({ + collapseWhitespace: true + })); diff --git a/types/koa-html-minifier/tsconfig.json b/types/koa-html-minifier/tsconfig.json new file mode 100644 index 0000000000..9a46770f6f --- /dev/null +++ b/types/koa-html-minifier/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", + "koa-html-minifier-tests.ts" + ] +} diff --git a/types/koa-html-minifier/tslint.json b/types/koa-html-minifier/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-html-minifier/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/koa-joi-router/index.d.ts b/types/koa-joi-router/index.d.ts index bf3f387d31..e9e8670726 100644 --- a/types/koa-joi-router/index.d.ts +++ b/types/koa-joi-router/index.d.ts @@ -1,30 +1,36 @@ // Type definitions for koa-joi-router 5.0 // Project: https://github.com/koajs/joi-router // Definitions by: Matthew Bull +// Dave Welsh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 import * as Koa from 'koa'; import * as Joi from 'joi'; -interface Spec { - method: string; - path: string|RegExp; - handler: (ctx: createRouter.Context) => void; - validate?: { - type: string; - body?: Joi.AnySchema; - params?: Joi.AnySchema; - output?: {[status: number]: Joi.AnySchema}; - }; -} - interface createRouter { (): createRouter.Router; Joi: typeof Joi; } declare namespace createRouter { + interface Spec { + method: string; + path: string|RegExp; + handler: (ctx: Context) => void; + validate?: { + header?: Joi.AnySchema|{[key: string]: Joi.AnySchema}; + query?: Joi.AnySchema|{[key: string]: Joi.AnySchema}; + params?: Joi.AnySchema|{[key: string]: Joi.AnySchema}; + body?: Joi.AnySchema|{[key: string]: Joi.AnySchema}; + maxBody?: number; + failure?: number; + type?: 'form'|'json'|'multipart'; + output?: {[status: number]: Joi.AnySchema}; + continueOnError?: boolean; + }; + } + interface Request extends Koa.Request { body: any; params: {[key: string]: string}; diff --git a/types/koa-joi-router/koa-joi-router-tests.ts b/types/koa-joi-router/koa-joi-router-tests.ts index 76a392bdec..90dac8d752 100644 --- a/types/koa-joi-router/koa-joi-router-tests.ts +++ b/types/koa-joi-router/koa-joi-router-tests.ts @@ -2,7 +2,7 @@ import router = require('koa-joi-router'); const { Joi } = router; -const spec1 = { +const spec1: router.Spec = { path: '/user', method: 'POST', handler: (ctx: router.Context) => ctx.body = '', @@ -10,7 +10,7 @@ const spec1 = { router().route(spec1); -const spec2 = { +const spec2: router.Spec = { method: 'PATCH', path: '/user', validate: { @@ -21,7 +21,7 @@ const spec2 = { router().route(spec2); -const spec3 = { +const spec3: router.Spec = { method: 'PATCH', path: '/user', validate: { @@ -33,7 +33,7 @@ const spec3 = { router().route(spec3); -const spec4 = { +const spec4: router.Spec = { method: 'PATCH', path: '/user', validate: { @@ -50,7 +50,7 @@ const spec4 = { router().route(spec4); -const spec5 = { +const spec5: router.Spec = { method: 'PUT', path: '/user', handler: (ctx: router.Context) => { @@ -61,7 +61,7 @@ const spec5 = { router().route(spec5); -const spec6 = { +const spec6: router.Spec = { method: 'GET', path: '/user', handler: (ctx: router.Context) => { @@ -72,6 +72,39 @@ const spec6 = { router().route(spec6); +const spec7: router.Spec = { + method: 'GET', + path: '/user', + validate: { + query: { + id: Joi.number(), + name: Joi.string(), + } + }, + handler: (ctx: router.Context) => { + ctx.status = 201; + ctx.body = ctx.request.params; + }, +}; + +router().route(spec7); + +const spec8: router.Spec = { + method: 'POST', + path: '/user', + validate: { + header: { + authentication: Joi.string(), + } + }, + handler: (ctx: router.Context) => { + ctx.status = 201; + ctx.body = ctx.request.params; + }, +}; + +router().route(spec8); + router().route([spec1, spec2, spec3]); router().routes.map(({ path }) => path); diff --git a/types/koa__cors/index.d.ts b/types/koa__cors/index.d.ts index 25d337716e..da58136652 100644 --- a/types/koa__cors/index.d.ts +++ b/types/koa__cors/index.d.ts @@ -1,10 +1,13 @@ // Type definitions for @koa/cors 2.2 // Project: https://github.com/koajs/cors -// Definitions by: Xavier Stouder , Izayoi Ko , Steve Hipwell +// Definitions by: Xavier Stouder +// Izayoi Ko +// Steve Hipwell +// Steven McDowall // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import * as Koa from "koa"; +import * as Koa from 'koa'; export = cors; @@ -12,7 +15,7 @@ declare function cors(options?: cors.Options): Koa.Middleware; declare namespace cors { interface Options { - origin?: ((req: Koa.Request) => string) | string; + origin?: ((ctx: Koa.Context) => string) | string; allowMethods?: string[] | string; exposeHeaders?: string[] | string; allowHeaders?: string[] | string; diff --git a/types/koa__cors/koa__cors-tests.ts b/types/koa__cors/koa__cors-tests.ts index 135845f205..25f068eb13 100644 --- a/types/koa__cors/koa__cors-tests.ts +++ b/types/koa__cors/koa__cors-tests.ts @@ -3,3 +3,11 @@ import cors = require('@koa/cors'); const app = new Koa(); app.use(cors()); + +// Trying using cors() passing in a function .. +function testCorsFunction(ctx: Koa.Context) { + const requestOrigin = ctx.request.origin; + return requestOrigin; +} + +app.use(cors({ origin: testCorsFunction })); diff --git a/types/lazy.js/index.d.ts b/types/lazy.js/index.d.ts index 3a44d2ce40..cea9ef0dea 100644 --- a/types/lazy.js/index.d.ts +++ b/types/lazy.js/index.d.ts @@ -4,259 +4,283 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace LazyJS { - interface LazyStatic { - - (value: string): StringLikeSequence; - (value: T[]): ArrayLikeSequence; - (value: any[]): ArrayLikeSequence; - (value: Object): ObjectLikeSequence; - (value: Object): ObjectLikeSequence; - - strict(): LazyStatic; - - generate(generatorFn: GeneratorCallback, length?: number): GeneratedSequence; - - range(to: number): GeneratedSequence; - range(from: number, to: number, step?: number): GeneratedSequence; - - repeat(value: T, count?: number): GeneratedSequence; - - on(eventType: string): Sequence; - - readFile(path: string): StringLikeSequence; - makeHttpRequest(path: string): StringLikeSequence; + (value: string): StringLikeSequence; + (value: T[]): ArrayLikeSequence; + (value: any[]): ArrayLikeSequence; + (value: Object): ObjectLikeSequence; + (value: Object): ObjectLikeSequence; + + strict(): LazyStatic; + + generate( + generatorFn: GeneratorCallback, + length?: number + ): GeneratedSequence; + + range(to: number): GeneratedSequence; + range(from: number, to: number, step?: number): GeneratedSequence; + + repeat(value: T, count?: number): GeneratedSequence; + + on(eventType: string): Sequence; + + readFile(path: string): StringLikeSequence; + makeHttpRequest(path: string): StringLikeSequence; } - + interface ArrayLike { - length: number; - [index: number]: T; + length: number; + [index: number]: T; } - + interface Callback { - (): void; + (): void; } - + interface ErrorCallback { - (error: any): void; + (error: any): void; } - + interface ValueCallback { - (value: T): void; + (value: T): void; } - + interface GetKeyCallback { - (value: T): string; + (value: T): string; } - - interface TestCallback { - (value: T): boolean; + + interface TestCallback { + (value: T, index: U): boolean; } - + interface MapCallback { - (value: T): U; + (value: T): U; } - + interface MapStringCallback { - (value: string): string; + (value: string): string; } - + interface NumberCallback { - (value: T): number; + (value: T): number; } - + interface MemoCallback { - (memo: U, value: T): U; + (memo: U, value: T): U; } - + interface GeneratorCallback { - (index: number): T; + (index: number): T; } - + interface CompareCallback { - (x: any, y: any): number; + (x: any, y: any): number; } - + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + interface Iterator { - new (sequence: Sequence): Iterator; - current(): T; - moveNext(): boolean; + new (sequence: Sequence): Iterator; + current(): T; + moveNext(): boolean; } - + interface GeneratedSequence extends Sequence { - new(generatorFn: GeneratorCallback, length: number): GeneratedSequence; - length(): number; + new (generatorFn: GeneratorCallback, length: number): GeneratedSequence< + T + >; + length(): number; } - + interface AsyncSequence extends SequenceBase { - each(callback: ValueCallback): AsyncHandle; + each(callback: ValueCallback): AsyncHandle; } - + interface AsyncHandle { - cancel(): void; - onComplete(callback: Callback): void; - onError(callback: ErrorCallback): void; + cancel(): void; + onComplete(callback: Callback): void; + onError(callback: ErrorCallback): void; } - + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + namespace Sequence { - function define(methodName: string[], overrides: Object): Function; + function define(methodName: string[], overrides: Object): Function; } - + interface Sequence extends SequenceBase { - each(eachFn: ValueCallback): Sequence; + each(eachFn: ValueCallback): Sequence; } - + interface SequenceBase extends SequenceBaser { - first(): any; - first(count: number): Sequence; - indexOf(value: any, startIndex?: number): Sequence; - - last(): any; - last(count: number): Sequence; - lastIndexOf(value: any): Sequence; - - reverse(): Sequence; + first(): any; + first(count: number): Sequence; + indexOf(value: any, startIndex?: number): Sequence; + + last(): any; + last(count: number): Sequence; + lastIndexOf(value: any): Sequence; + + reverse(): Sequence; } - + interface SequenceBaser { - // TODO improve define() (needs ugly overload) - async(interval: number): AsyncSequence; - chunk(size: number): Sequence; - compact(): Sequence; - concat(var_args: T[]): Sequence; - consecutive(length: number): Sequence; - contains(value: T): boolean; - countBy(keyFn: GetKeyCallback): ObjectLikeSequence; - countBy(propertyName: string): ObjectLikeSequence; - dropWhile(predicateFn: TestCallback): Sequence; - every(predicateFn: TestCallback): boolean; - filter(predicateFn: TestCallback): Sequence; - find(predicateFn: TestCallback): T; - findWhere(properties: Object): T; - - flatten(): Sequence; - groupBy(keyFn: GetKeyCallback): ObjectLikeSequence; - initial(count?: number): Sequence; - intersection(var_args: T[]): Sequence; - invoke(methodName: string): Sequence; - isEmpty(): boolean; - join(delimiter?: string): string; - map(mapFn: MapCallback): Sequence; - - max(valueFn?: NumberCallback): T; - min(valueFn?: NumberCallback): T; - none(valueFn?: TestCallback): boolean; - pluck(propertyName: string): Sequence; - reduce(aggregatorFn: MemoCallback, memo?: U): U; - reduceRight(aggregatorFn: MemoCallback, memo: U): U; - reject(predicateFn: TestCallback): Sequence; - rest(count?: number): Sequence; - shuffle(): Sequence; - some(predicateFn?: TestCallback): boolean; - sort(sortFn?: CompareCallback, descending?: boolean): Sequence; - sortBy(sortFn: string, descending?: boolean): Sequence; - sortBy(sortFn: NumberCallback, descending?: boolean): Sequence; - sortedIndex(value: T): Sequence; - size(): number; - sum(valueFn?: NumberCallback): T; - takeWhile(predicateFn: TestCallback): Sequence; - union(var_args: T[]): Sequence; - uniq(): Sequence; - where(properties: Object): Sequence; - without(...var_args: T[]): Sequence; - without(var_args: T[]): Sequence; - zip(var_args: T[]): Sequence; - - toArray(): T[]; - toObject(): Object; + // TODO improve define() (needs ugly overload) + async(interval: number): AsyncSequence; + chunk(size: number): Sequence; + compact(): Sequence; + concat(var_args: T[]): Sequence; + consecutive(length: number): Sequence; + contains(value: T): boolean; + countBy(keyFn: GetKeyCallback): ObjectLikeSequence; + countBy(propertyName: string): ObjectLikeSequence; + dropWhile(predicateFn: TestCallback): Sequence; + every(predicateFn: TestCallback): boolean; + filter(predicateFn: TestCallback): Sequence; + find(predicateFn: TestCallback): T; + findWhere(properties: Object): T; + flatten(): Sequence; + groupBy(keyFn: GetKeyCallback): ObjectLikeSequence; + initial(count?: number): Sequence; + intersection(var_args: T[]): Sequence; + invoke(methodName: string): Sequence; + isEmpty(): boolean; + join(delimiter?: string): string; + map(mapFn: MapCallback): Sequence; + max(valueFn?: NumberCallback): T; + min(valueFn?: NumberCallback): T; + none(valueFn?: TestCallback): boolean; + pluck(propertyName: string): Sequence; + reduce(aggregatorFn: MemoCallback, memo?: U): U; + reduceRight(aggregatorFn: MemoCallback, memo: U): U; + reject(predicateFn: TestCallback): Sequence; + rest(count?: number): Sequence; + shuffle(): Sequence; + size(): number; + some(predicateFn?: TestCallback): boolean; + sort(sortFn?: CompareCallback, descending?: boolean): Sequence; + sortBy(sortFn: NumberCallback, descending?: boolean): Sequence; + sortBy(sortFn: string, descending?: boolean): Sequence; + sortedIndex(value: T): Sequence; + sum(valueFn?: NumberCallback): T; + takeWhile(predicateFn: TestCallback): Sequence; + toArray(): T[]; + toObject(): Object; + union(var_args: T[]): Sequence; + uniq(): Sequence; + where(properties: Object): Sequence; + without(...var_args: T[]): Sequence; + without(var_args: T[]): Sequence; + zip(var_args: T[]): Sequence; } - + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + namespace ArrayLikeSequence { - function define(methodName: string[], overrides: Object): Function; + function define(methodName: string[], overrides: Object): Function; } - + interface ArrayLikeSequence extends Sequence { - // define()X; - concat(var_args: T[]): ArrayLikeSequence; - first(count?: number): ArrayLikeSequence; - get(index: number): T; - length(): number; - map(mapFn: MapCallback): ArrayLikeSequence; - pop(): ArrayLikeSequence; - rest(count?: number): ArrayLikeSequence; - reverse(): ArrayLikeSequence; - shift(): ArrayLikeSequence; - slice(begin: number, end?: number): ArrayLikeSequence; + // define()X; + concat(var_args: T[]): ArrayLikeSequence; + first(count?: number): ArrayLikeSequence; + get(index: number): T; + length(): number; + map(mapFn: MapCallback): ArrayLikeSequence; + pop(): ArrayLikeSequence; + push(value: T): ArrayLikeSequence; + rest(count?: number): ArrayLikeSequence; + reverse(): ArrayLikeSequence; + shift(): ArrayLikeSequence; + slice(begin: number, end?: number): ArrayLikeSequence; + unshift(value: T): ArrayLikeSequence; + + dropWhile(predicateFn: TestCallback): Sequence; + every(predicateFn: TestCallback): boolean; + filter(predicateFn: TestCallback): Sequence; + find(predicateFn: TestCallback): T; + none(valueFn?: TestCallback): boolean; + reject(predicateFn: TestCallback): Sequence; + some(predicateFn?: TestCallback): boolean; + takeWhile(predicateFn: TestCallback): Sequence; } - + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + namespace ObjectLikeSequence { - function define(methodName: string[], overrides: Object): Function; + function define(methodName: string[], overrides: Object): Function; } - + interface ObjectLikeSequence extends Sequence { - assign(other: Object): ObjectLikeSequence; - // throws error - //async(): X; - defaults(defaults: Object): ObjectLikeSequence; - functions(): Sequence; - get(property: string): ObjectLikeSequence; - invert(): ObjectLikeSequence; - keys(): Sequence; - merge(others: Object | ObjectLikeSequence, mergeFn?: Function): ObjectLikeSequence; - omit(properties: string[]): ObjectLikeSequence; - pairs(): Sequence; - pick(properties: string[]): ObjectLikeSequence; - toArray(): T[]; - toObject(): Object; - values(): Sequence; + assign(other: Object): ObjectLikeSequence; + // throws error + //async(): X; + defaults(defaults: Object): ObjectLikeSequence; + functions(): Sequence; + get(property: string): ObjectLikeSequence; + invert(): ObjectLikeSequence; + keys(): Sequence; + merge(others: Object | ObjectLikeSequence, mergeFn?: Function): ObjectLikeSequence; + omit(properties: string[]): ObjectLikeSequence; + pairs(): Sequence; + pick(properties: string[]): ObjectLikeSequence; + toArray(): T[]; + toObject(): Object; + values(): Sequence; + watch(propertyNames: string | string[]): Sequence<{property: string; value: any;}>; + + dropWhile(predicateFn: TestCallback): Sequence; + every(predicateFn: TestCallback): boolean; + filter(predicateFn: TestCallback): Sequence; + find(predicateFn: TestCallback): T; + none(valueFn?: TestCallback): boolean; + reject(predicateFn: TestCallback): Sequence; + some(predicateFn?: TestCallback): boolean; + takeWhile(predicateFn: TestCallback): Sequence; } - + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + namespace StringLikeSequence { - function define(methodName: string[], overrides: Object): Function; + function define(methodName: string[], overrides: Object): Function; } - + interface StringLikeSequence extends SequenceBaser { - charAt(index: number): string; - charCodeAt(index: number): number; - contains(value: string): boolean; - endsWith(suffix: string): boolean; + charAt(index: number): string; + charCodeAt(index: number): number; + contains(value: string): boolean; + endsWith(suffix: string): boolean; + first(): string; + indexOf(substring: string, startIndex?: number): number; + last(): string; + last(count: number): StringLikeSequence; + lastIndexOf(substring: string, startIndex?: number): number; + mapString(mapFn: MapStringCallback): StringLikeSequence; + match(pattern: RegExp): StringLikeSequence; + reverse(): StringLikeSequence; + split(delimiter: RegExp): StringLikeSequence; + split(delimiter: string): StringLikeSequence; + startsWith(prefix: string): boolean; + substring(start: number, stop?: number): StringLikeSequence; + toLowerCase(): StringLikeSequence; + toUpperCase(): StringLikeSequence; - first(): string; - first(count: number): StringLikeSequence; - - indexOf(substring: string, startIndex?: number): number; - - last(): string; - last(count: number): StringLikeSequence; - - lastIndexOf(substring: string, startIndex?: number): number; - mapString(mapFn: MapStringCallback): StringLikeSequence; - match(pattern: RegExp): StringLikeSequence; - reverse(): StringLikeSequence; - - split(delimiter: string): StringLikeSequence; - split(delimiter: RegExp): StringLikeSequence; - - startsWith(prefix: string): boolean; - substring(start: number, stop?: number): StringLikeSequence; - toLowerCase(): StringLikeSequence; - toUpperCase(): StringLikeSequence; + dropWhile(predicateFn: TestCallback): Sequence; + every(predicateFn: TestCallback): boolean; + filter(predicateFn: TestCallback): Sequence; + find(predicateFn: TestCallback): string; + first(count: number): StringLikeSequence; + none(valueFn?: TestCallback): boolean; + reject(predicateFn: TestCallback): Sequence; + some(predicateFn?: TestCallback): boolean; + takeWhile(predicateFn: TestCallback): Sequence; } -} - -declare var Lazy: LazyJS.LazyStatic; - -declare module 'lazy.js' { -export = Lazy; -} - + } + + declare var Lazy: LazyJS.LazyStatic; + + declare module 'lazy.js' { + export = Lazy; + } + \ No newline at end of file diff --git a/types/less/index.d.ts b/types/less/index.d.ts index bca5c21c33..7d69273a52 100644 --- a/types/less/index.d.ts +++ b/types/less/index.d.ts @@ -52,6 +52,11 @@ declare namespace Less { interface StaticOptions { async: boolean; fileAsync: boolean; + modifyVars: { [variable: string]: string }; + } + + interface ImportManager { + contents: { [fileName: string]: string }; } interface Options { @@ -76,21 +81,33 @@ declare namespace Less { map: string; imports: string[]; } + + interface RefreshOutput { + endTime: Date; + startTime: Date; + sheets: number; + totalMilliseconds: number; + } } interface LessStatic { options: Less.StaticOptions; - - modifyVars(vars: { [name: string]: string }): void; - + + importManager?: Less.ImportManager; + sheets: HTMLLinkElement[]; + + modifyVars(vars: { [name: string]: string }): Promise; + refreshStyles(): void; - + render(input: string, callback: (error: Less.RenderError, output: Less.RenderOutput) => void): void; render(input: string, options: Less.Options, callback: (error: Less.RenderError, output: Less.RenderOutput) => void): void; render(input: string): Promise; render(input: string, options: Less.Options): Promise; + refresh(reload?: boolean, modifyVars?: { [variable: string]: string }, clearFileCache?: boolean): Promise; + version: number[]; watch(): void; diff --git a/types/less/less-tests.ts b/types/less/less-tests.ts index 5d0029475a..20a1f587a9 100644 --- a/types/less/less-tests.ts +++ b/types/less/less-tests.ts @@ -39,8 +39,22 @@ less.render("h1 { background: red; }", options); less.modifyVars({ '@buttonFace': '#5B83AD', '@buttonText': '#D9EEF2' +}).then((output) => { + console.log('Successfully modified vars.'); }); less.refreshStyles(); less.watch(); + +less.refresh(true, { + '@buttonFace': '#5B83AD' +}, true).then((output) => { + console.log('successfully refreshed less files'); +}); + +if (less.importManager) { + for (let fileName in less.importManager.contents) { + let fileContents = less.importManager.contents[fileName]; + } +} \ No newline at end of file diff --git a/types/mongodb/v2/index.d.ts b/types/mongodb/v2/index.d.ts index 4c26149d81..a7d45ac2d0 100644 --- a/types/mongodb/v2/index.d.ts +++ b/types/mongodb/v2/index.d.ts @@ -22,7 +22,7 @@ export function connect(uri: string, options?: MongoClientOptions): Promise; export function connect(uri: string, callback: MongoCallback): void; export function connect(uri: string, options: MongoClientOptions, callback: MongoCallback): void; -export { Binary, Double, Long, Decimal128, MaxKey, MinKey, ObjectID, ObjectId, Timestamp, DBRef } from 'bson'; +export { Binary, Double, Long, Decimal128, MaxKey, MinKey, ObjectID, ObjectId, Timestamp, DBRef, Int32 } from 'bson'; // Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html export class MongoClient { diff --git a/types/moonjs/index.d.ts b/types/moonjs/index.d.ts index 13dcbbe04e..c003f7ad58 100644 --- a/types/moonjs/index.d.ts +++ b/types/moonjs/index.d.ts @@ -22,11 +22,11 @@ declare namespace Moon { } interface MoonConstructor { - new (options?: ConstructorOptions): Instance>; + new (options?: ConstructorOptions): Instance>; } interface MoonStatic extends MoonConstructor { - component(name: string, options: ComponentOptions): MoonConstructor; + component(name: string, options: ComponentOptions): MoonConstructor; config: MoonConfig; use(plugin: object): void; compile(template: string): void; diff --git a/types/moonjs/moonjs-tests.ts b/types/moonjs/moonjs-tests.ts index aa6527ea82..34d1d8d359 100644 --- a/types/moonjs/moonjs-tests.ts +++ b/types/moonjs/moonjs-tests.ts @@ -17,6 +17,7 @@ const count = app.get("count"); count; // $ExpectType number app.get("increment")(); // $ExpectType void app.callMethod("increment"); // $ExpectType any +app.get("blahblahblah"); // $ExpectError app.destroy(); diff --git a/types/mssql/index.d.ts b/types/mssql/index.d.ts index 109a515515..db1256e2a3 100644 --- a/types/mssql/index.d.ts +++ b/types/mssql/index.d.ts @@ -201,6 +201,7 @@ export declare class ConnectionPool extends events.EventEmitter { public close(): Promise; public close(callback: (err: any) => void): void; public request(): Request; + public transaction(): Transaction; } export declare class ConnectionError implements Error { @@ -297,6 +298,7 @@ export declare class Transaction extends events.EventEmitter { public commit(callback: (err?: any) => void): void; public rollback(): Promise; public rollback(callback: (err?: any) => void): void; + public request(): Request; } export declare class TransactionError implements Error { diff --git a/types/next/router.d.ts b/types/next/router.d.ts index 74aafd4a33..fe3563d473 100644 --- a/types/next/router.d.ts +++ b/types/next/router.d.ts @@ -62,7 +62,16 @@ export interface RouterProps { options?: EventChangeOptions, ): Promise; - // events + // events (deprecated soonish) + onAppUpdated?(nextRoute: string): void; + onBeforeHistoryChange?(as: string): void; + onHashChangeStart?(url: string): void; + onHashChangeComplete?(url: string): void; + onRouteChangeComplete?(url: string): void; + onRouteChangeError?(error: RouteChangeError, url: string): void; + onRouteChangeStart?(url: string): void; + + // events API (6.1.1+) readonly events: { on: (eventName: EventName, handler: EventHandler | ErrorEventHandler) => void; off: (eventName: EventName, handler: (url: string) => any) => void; diff --git a/types/node-zopfli-es/index.d.ts b/types/node-zopfli-es/index.d.ts new file mode 100644 index 0000000000..e015655d8b --- /dev/null +++ b/types/node-zopfli-es/index.d.ts @@ -0,0 +1,69 @@ +// Type definitions for node-zopfli-es 0.0 +// Project: https://github.com/jaeh/node-zopfli-es +// Definitions by: Alorel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { Transform } from 'stream'; + +declare class Zopfli extends Transform { + constructor(format?: Zopfli.Format, options?: Zopfli.Options); + + static createGzip(options?: Zopfli.Options): Zopfli; + static createDeflate(options?: Zopfli.Options): Zopfli; + static createZlib(options?: Zopfli.Options): Zopfli; + + static gzipSync(options?: Zopfli.Options): Buffer; + static deflateSync(options?: Zopfli.Options): Buffer; + static zlibSync(options?: Zopfli.Options): Buffer; + + static deflate(input: Buffer, options: Zopfli.Options, cb: (err: Error, out: Buffer) => void): void; + static deflate(input: Buffer, cb: (err: Error, out: Buffer) => void): void; + static deflate(input: Buffer, options?: Zopfli.Options): Promise; + + static gzip(input: Buffer, options: Zopfli.Options, cb: (err: Error, out: Buffer) => void): void; + static gzip(input: Buffer, cb: (err: Error, out: Buffer) => void): void; + static gzip(input: Buffer, options?: Zopfli.Options): Promise; + + static zlib(input: Buffer, options: Zopfli.Options, cb: (err: Error, out: Buffer) => void): void; + static zlib(input: Buffer, cb: (err: Error, out: Buffer) => void): void; + static zlib(input: Buffer, options?: Zopfli.Options): Promise; + + static compress(input: Buffer, format: Zopfli.Format, options: Zopfli.Options, cb: (err: Error, out: Buffer) => void): void; + static compress(input: Buffer, format: Zopfli.Format, cb: (err: Error, out: Buffer) => void): void; + static compress(input: Buffer, format: Zopfli.Format, options?: Zopfli.Options): Promise; +} + +declare namespace Zopfli { + type Format = 'deflate' | 'gzip' | 'zlib'; + + interface Options { + verbose?: boolean; + verbose_more?: boolean; + /** + * Maximum amount of times to rerun forward and backward pass to optimize LZ77 compression cost. + * Good values: 10, 15 for small files, 5 for files over several MB in size or it will be too slow. + */ + numiterations?: number; + /** + * If true, splits the data in multiple deflate blocks with optimal choice for the block boundaries. + * Block splitting gives better compression. + */ + blocksplitting?: boolean; + /** + * If true, chooses the optimal block split points only after doing the iterative LZ77 compression. + * If false, chooses the block split points first, then does iterative LZ77 on each individual block. + * Depending on the file, either first or last gives the best compression. + */ + blocksplittinglast?: boolean; + /** + * Maximum amount of blocks to split into (0 for unlimited, + * but this can give extreme results that hurt compression on some files). + */ + blocksplittingmax?: number; + } +} + +export = Zopfli; diff --git a/types/node-zopfli-es/node-zopfli-es-tests.ts b/types/node-zopfli-es/node-zopfli-es-tests.ts new file mode 100644 index 0000000000..3f3294cf3f --- /dev/null +++ b/types/node-zopfli-es/node-zopfli-es-tests.ts @@ -0,0 +1,51 @@ +import * as Zopfli from 'node-zopfli-es'; +import * as fs from 'fs'; + +const opts: Zopfli.Options = { + verbose: true, + numiterations: 1 +}; +let input: Buffer = Buffer.from('foo'); +const read = fs.createReadStream('foo'); +const write = fs.createWriteStream('foo'); + +function cb(e: Error, b: Buffer): void {} +function then(b: Buffer): void {} + +Zopfli.zlib(input, cb); +Zopfli.zlib(input, opts, cb); +Zopfli.zlib(input, opts).then(then); +Zopfli.zlib(input).then(then); + +Zopfli.gzip(input, cb); +Zopfli.gzip(input, opts, cb); +Zopfli.gzip(input, opts).then(then); +Zopfli.gzip(input).then(then); + +Zopfli.deflate(input, cb); +Zopfli.deflate(input, opts, cb); +Zopfli.deflate(input, opts).then(then); +Zopfli.deflate(input).then(then); + +Zopfli.compress(input, 'zlib', cb); +Zopfli.compress(input, 'zlib', opts, cb); +Zopfli.compress(input, 'zlib', opts).then(then); +Zopfli.compress(input, 'zlib').then(then); + +input = Zopfli.gzipSync(); +input = Zopfli.gzipSync(opts); + +input = Zopfli.deflateSync(); +input = Zopfli.deflateSync(opts); + +input = Zopfli.zlibSync(); +input = Zopfli.zlibSync(opts); + +read.pipe(Zopfli.createGzip()).pipe(write); +read.pipe(Zopfli.createGzip(opts)).pipe(write); + +read.pipe(Zopfli.createDeflate()).pipe(write); +read.pipe(Zopfli.createDeflate(opts)).pipe(write); + +read.pipe(Zopfli.createZlib()).pipe(write); +read.pipe(Zopfli.createZlib(opts)).pipe(write); diff --git a/types/node-zopfli-es/tsconfig.json b/types/node-zopfli-es/tsconfig.json new file mode 100644 index 0000000000..bbd6de30e8 --- /dev/null +++ b/types/node-zopfli-es/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", + "node-zopfli-es-tests.ts" + ] +} diff --git a/types/node-zopfli-es/tslint.json b/types/node-zopfli-es/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/node-zopfli-es/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 43d4f25cc9..bb4b54efa7 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -2225,24 +2225,31 @@ declare module "child_process" { encoding: string | null; // specify `null`. } + export interface ExecException extends Error { + cmd?: string; + killed?: boolean; + code?: number; + signal?: string; + } + // no `options` definitely means stdout/stderr are `string`. - export function exec(command: string, callback?: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + export function exec(command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. - export function exec(command: string, options: { encoding: "buffer" | null } & ExecOptions, callback?: (error: Error | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function exec(command: string, options: { encoding: "buffer" | null } & ExecOptions, callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; // `options` with well known `encoding` means stdout/stderr are definitely `string`. - export function exec(command: string, options: { encoding: BufferEncoding } & ExecOptions, callback?: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + export function exec(command: string, options: { encoding: BufferEncoding } & ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. - export function exec(command: string, options: { encoding: string } & ExecOptions, callback?: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + export function exec(command: string, options: { encoding: string } & ExecOptions, callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; // `options` without an `encoding` means stdout/stderr are definitely `string`. - export function exec(command: string, options: ExecOptions, callback?: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + export function exec(command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; // fallback if nothing else matches. Worst case is always `string | Buffer`. - export function exec(command: string, options: ({ encoding?: string | null } & ExecOptions) | undefined | null, callback?: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + export function exec(command: string, options: ({ encoding?: string | null } & ExecOptions) | undefined | null, callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace exec { @@ -2503,7 +2510,7 @@ declare module "url" { append(name: string, value: string): void; delete(name: string): void; entries(): IterableIterator<[string, string]>; - forEach(callback: (value: string, name: string) => void): void; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; get(name: string): string | null; getAll(name: string): string[]; has(name: string): boolean; diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index c3a23dc094..aae5512702 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -690,9 +690,10 @@ namespace url_tests { const searchParams = new url.URLSearchParams('abc=123'); assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string): void => { + searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { assert.equal(name, 'abc'); assert.equal(value, '123'); + assert.equal(me, searchParams); }); assert.equal(searchParams.get('abc'), '123'); diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 9cceb11e71..de1b280260 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -2002,7 +2002,7 @@ declare module "url" { append(name: string, value: string): void; delete(name: string): void; entries(): Iterator; - forEach(callback: (value: string, name: string) => void): void; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; get(name: string): string | null; getAll(name: string): string[]; has(name: string): boolean; diff --git a/types/node/v6/node-tests.ts b/types/node/v6/node-tests.ts index 6ab45137c4..43441e9840 100644 --- a/types/node/v6/node-tests.ts +++ b/types/node/v6/node-tests.ts @@ -538,9 +538,10 @@ namespace url_tests { const searchParams = new url.URLSearchParams('abc=123'); assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string): void => { + searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { assert.equal(name, 'abc'); assert.equal(value, '123'); + assert.equal(me, searchParams); }); assert.equal(searchParams.get('abc'), '123'); diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index b93c70017b..a40d713dcf 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -2045,7 +2045,7 @@ declare module "url" { append(name: string, value: string): void; delete(name: string): void; entries(): Iterator; - forEach(callback: (value: string, name: string) => void): void; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; get(name: string): string | null; getAll(name: string): string[]; has(name: string): boolean; diff --git a/types/node/v7/node-tests.ts b/types/node/v7/node-tests.ts index a74a438665..4549ab7062 100644 --- a/types/node/v7/node-tests.ts +++ b/types/node/v7/node-tests.ts @@ -520,9 +520,10 @@ namespace url_tests { const searchParams = new url.URLSearchParams('abc=123'); assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string): void => { + searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { assert.equal(name, 'abc'); assert.equal(value, '123'); + assert.equal(me, searchParams); }); assert.equal(searchParams.get('abc'), '123'); diff --git a/types/node/v8/index.d.ts b/types/node/v8/index.d.ts index 6acb0c62a7..8e6c649d00 100644 --- a/types/node/v8/index.d.ts +++ b/types/node/v8/index.d.ts @@ -2378,7 +2378,7 @@ declare module "url" { append(name: string, value: string): void; delete(name: string): void; entries(): IterableIterator<[string, string]>; - forEach(callback: (value: string, name: string) => void): void; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; get(name: string): string | null; getAll(name: string): string[]; has(name: string): boolean; diff --git a/types/node/v8/node-tests.ts b/types/node/v8/node-tests.ts index 318062648a..9cec14a88e 100644 --- a/types/node/v8/node-tests.ts +++ b/types/node/v8/node-tests.ts @@ -654,9 +654,10 @@ namespace url_tests { const searchParams = new url.URLSearchParams('abc=123'); assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string): void => { + searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { assert.equal(name, 'abc'); assert.equal(value, '123'); + assert.equal(me, searchParams); }); assert.equal(searchParams.get('abc'), '123'); diff --git a/types/node/v9/index.d.ts b/types/node/v9/index.d.ts index 7d9b0dbb29..19259316b8 100644 --- a/types/node/v9/index.d.ts +++ b/types/node/v9/index.d.ts @@ -2459,7 +2459,7 @@ declare module "url" { append(name: string, value: string): void; delete(name: string): void; entries(): IterableIterator<[string, string]>; - forEach(callback: (value: string, name: string) => void): void; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; get(name: string): string | null; getAll(name: string): string[]; has(name: string): boolean; diff --git a/types/node/v9/node-tests.ts b/types/node/v9/node-tests.ts index 30b0666773..3d7861f532 100644 --- a/types/node/v9/node-tests.ts +++ b/types/node/v9/node-tests.ts @@ -680,9 +680,10 @@ namespace url_tests { const searchParams = new url.URLSearchParams('abc=123'); assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string): void => { + searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { assert.equal(name, 'abc'); assert.equal(value, '123'); + assert.equal(me, searchParams); }); assert.equal(searchParams.get('abc'), '123'); diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 36c659a7b2..d883822f37 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -8708,7 +8708,7 @@ declare namespace Office { */ getInitializationContextAsync(callback?: (result: AsyncResult) => void): void; /** - * Gets the entities found in the selected item. + * Gets the entities found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -8722,7 +8722,7 @@ declare namespace Office { */ getEntities(): Entities; /** - * Gets an array of all the entities of the specified entity type found in the selected item. + * Gets an array of all the entities of the specified entity type found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -8731,7 +8731,7 @@ declare namespace Office { * @param entityType One of the EntityType enumeration values. * * @returns - * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present on the item, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. + * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present in the item's body, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. * * @remarks * @@ -9989,7 +9989,7 @@ declare namespace Office { */ getInitializationContextAsync(callback?: (result: AsyncResult) => void): void; /** - * Gets the entities found in the selected item. + * Gets the entities found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -10003,7 +10003,7 @@ declare namespace Office { */ getEntities(): Entities; /** - * Gets an array of all the entities of the specified entity type found in the selected item. + * Gets an array of all the entities of the specified entity type found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -10012,7 +10012,7 @@ declare namespace Office { * @param entityType One of the EntityType enumeration values. * * @returns - * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present on the item, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. + * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present in the item's body, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. * * @remarks *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}Restricted
@@ -11523,7 +11523,7 @@ declare namespace Office { */ getInitializationContextAsync(callback?: (result: AsyncResult) => void): void; /** - * Gets the entities found in the selected item. + * Gets the entities found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -11537,7 +11537,7 @@ declare namespace Office { */ getEntities(): Entities; /** - * Gets an array of all the entities of the specified entity type found in the selected item. + * Gets an array of all the entities of the specified entity type found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -11546,7 +11546,7 @@ declare namespace Office { * @param entityType One of the EntityType enumeration values. * * @returns - * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present on the item, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. + * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present in the item's body, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. * * @remarks * @@ -18430,7 +18430,7 @@ declare namespace Excel { * @param sourceData The Range object corresponding to the source data. * @param seriesBy Optional. Specifies the way columns or rows are used as data series on the chart. See Excel.ChartSeriesBy for details. */ - add(type: Excel.ChartType, sourceData: Range | string, seriesBy?: Excel.ChartSeriesBy): Excel.Chart; + add(type: Excel.ChartType, sourceData: Range, seriesBy?: Excel.ChartSeriesBy): Excel.Chart; /** * * Creates a new chart. @@ -18441,7 +18441,7 @@ declare namespace Excel { * @param sourceData The Range object corresponding to the source data. * @param seriesBy Optional. Specifies the way columns or rows are used as data series on the chart. See Excel.ChartSeriesBy for details. */ - add(type: "Invalid" | "ColumnClustered" | "ColumnStacked" | "ColumnStacked100" | "3DColumnClustered" | "3DColumnStacked" | "3DColumnStacked100" | "BarClustered" | "BarStacked" | "BarStacked100" | "3DBarClustered" | "3DBarStacked" | "3DBarStacked100" | "LineStacked" | "LineStacked100" | "LineMarkers" | "LineMarkersStacked" | "LineMarkersStacked100" | "PieOfPie" | "PieExploded" | "3DPieExploded" | "BarOfPie" | "XYScatterSmooth" | "XYScatterSmoothNoMarkers" | "XYScatterLines" | "XYScatterLinesNoMarkers" | "AreaStacked" | "AreaStacked100" | "3DAreaStacked" | "3DAreaStacked100" | "DoughnutExploded" | "RadarMarkers" | "RadarFilled" | "Surface" | "SurfaceWireframe" | "SurfaceTopView" | "SurfaceTopViewWireframe" | "Bubble" | "Bubble3DEffect" | "StockHLC" | "StockOHLC" | "StockVHLC" | "StockVOHLC" | "CylinderColClustered" | "CylinderColStacked" | "CylinderColStacked100" | "CylinderBarClustered" | "CylinderBarStacked" | "CylinderBarStacked100" | "CylinderCol" | "ConeColClustered" | "ConeColStacked" | "ConeColStacked100" | "ConeBarClustered" | "ConeBarStacked" | "ConeBarStacked100" | "ConeCol" | "PyramidColClustered" | "PyramidColStacked" | "PyramidColStacked100" | "PyramidBarClustered" | "PyramidBarStacked" | "PyramidBarStacked100" | "PyramidCol" | "3DColumn" | "Line" | "3DLine" | "3DPie" | "Pie" | "XYScatter" | "3DArea" | "Area" | "Doughnut" | "Radar" | "Histogram" | "Pareto" | "RegionMap", sourceData: Range | string, seriesBy?: "Auto" | "Columns" | "Rows"): Excel.Chart; + add(type: "Invalid" | "ColumnClustered" | "ColumnStacked" | "ColumnStacked100" | "3DColumnClustered" | "3DColumnStacked" | "3DColumnStacked100" | "BarClustered" | "BarStacked" | "BarStacked100" | "3DBarClustered" | "3DBarStacked" | "3DBarStacked100" | "LineStacked" | "LineStacked100" | "LineMarkers" | "LineMarkersStacked" | "LineMarkersStacked100" | "PieOfPie" | "PieExploded" | "3DPieExploded" | "BarOfPie" | "XYScatterSmooth" | "XYScatterSmoothNoMarkers" | "XYScatterLines" | "XYScatterLinesNoMarkers" | "AreaStacked" | "AreaStacked100" | "3DAreaStacked" | "3DAreaStacked100" | "DoughnutExploded" | "RadarMarkers" | "RadarFilled" | "Surface" | "SurfaceWireframe" | "SurfaceTopView" | "SurfaceTopViewWireframe" | "Bubble" | "Bubble3DEffect" | "StockHLC" | "StockOHLC" | "StockVHLC" | "StockVOHLC" | "CylinderColClustered" | "CylinderColStacked" | "CylinderColStacked100" | "CylinderBarClustered" | "CylinderBarStacked" | "CylinderBarStacked100" | "CylinderCol" | "ConeColClustered" | "ConeColStacked" | "ConeColStacked100" | "ConeBarClustered" | "ConeBarStacked" | "ConeBarStacked100" | "ConeCol" | "PyramidColClustered" | "PyramidColStacked" | "PyramidColStacked100" | "PyramidBarClustered" | "PyramidBarStacked" | "PyramidBarStacked100" | "PyramidCol" | "3DColumn" | "Line" | "3DLine" | "3DPie" | "Pie" | "XYScatter" | "3DArea" | "Area" | "Doughnut" | "Radar" | "Histogram" | "Pareto" | "RegionMap", sourceData: Range, seriesBy?: "Auto" | "Columns" | "Rows"): Excel.Chart; /** * * Returns the number of charts in the worksheet. @@ -18663,7 +18663,7 @@ declare namespace Excel { * @param sourceData The range corresponding to the source data. * @param seriesBy Specifies the way columns or rows are used as data series on the chart. Can be one of the following: Auto (default), Rows, and Columns. See Excel.ChartSeriesBy for details. */ - setData(sourceData: Range | string, seriesBy?: Excel.ChartSeriesBy): void; + setData(sourceData: Range, seriesBy?: Excel.ChartSeriesBy): void; /** * * Resets the source data for the chart. @@ -18673,7 +18673,7 @@ declare namespace Excel { * @param sourceData The range corresponding to the source data. * @param seriesBy Specifies the way columns or rows are used as data series on the chart. Can be one of the following: Auto (default), Rows, and Columns. See Excel.ChartSeriesBy for details. */ - setData(sourceData: Range | string, seriesBy?: "Auto" | "Columns" | "Rows"): void; + setData(sourceData: Range, seriesBy?: "Auto" | "Columns" | "Rows"): void; /** * * Positions the chart relative to cells on the worksheet. diff --git a/types/pino/index.d.ts b/types/pino/index.d.ts index 0f98e0a622..27d0f51fc6 100644 --- a/types/pino/index.d.ts +++ b/types/pino/index.d.ts @@ -19,7 +19,7 @@ export = P; * relative protocol is enabled. Default: process.stdout * @returns a new logger instance. */ -declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream.Duplex | stream.Transform): P.Logger; +declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream): P.Logger; /** * @param [options]: an options object @@ -27,7 +27,7 @@ declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream. * relative protocol is enabled. Default: process.stdout * @returns a new logger instance. */ -declare function P(options: P.LoggerOptions, stream: stream.Writable | stream.Duplex | stream.Transform): P.Logger; +declare function P(options: P.LoggerOptions, stream: stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream): P.Logger; declare namespace P { /** diff --git a/types/pino/pino-tests.ts b/types/pino/pino-tests.ts index 6d226a1d92..6959a6cd97 100644 --- a/types/pino/pino-tests.ts +++ b/types/pino/pino-tests.ts @@ -93,3 +93,6 @@ log.level = 'info'; pino.levels.values.error === 50; pino.levels.labels[50] === 'error'; + +const logstderr: pino.Logger = pino(process.stderr); +logstderr.error('on stderr instead of stdout'); diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index 4859b86fc1..a5e85f802e 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for puppeteer 1.5 +// Type definitions for puppeteer 1.6 // Project: https://github.com/GoogleChrome/puppeteer#readme // Definitions by: Marvin Hagemeister // Christopher Deutsch @@ -727,6 +727,10 @@ export interface ElementHandle extends JSHandle, Ev * If the element is detached from DOM, the method throws an error. */ hover(): Promise; + /** + * Resolves to true if the element is visible in the current viewport. + */ + isIntersectingViewport(): 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. @@ -860,6 +864,8 @@ export type ErrorCode = | "aborted" | "accessdenied" | "addressunreachable" + | "blockedbyclient" + | "blockedbyresponse" | "connectionaborted" | "connectionclosed" | "connectionfailed" @@ -1107,16 +1113,6 @@ export interface FrameBase extends Evalable { ...args: any[] ): Promise; - waitForRequest( - urlOrPredicate: string | ((req: Request) => boolean), - options?: { timeout?: number } - ): Promise; - - waitForResponse( - urlOrPredicate: string | ((res: Response) => boolean), - options?: { timeout?: number } - ): Promise; - waitForSelector( selector: string, options?: { visible?: boolean; hidden?: boolean; timeout?: number } @@ -1447,6 +1443,16 @@ export interface Page extends EventEmitter, FrameBase { */ waitForNavigation(options?: NavigationOptions): Promise; + waitForRequest( + urlOrPredicate: string | ((req: Request) => boolean), + options?: { timeout?: number } + ): Promise; + + waitForResponse( + urlOrPredicate: string | ((res: Response) => boolean), + options?: { timeout?: number } + ): Promise; + /** This method returns all of the dedicated WebWorkers associated with the page. */ workers(): Worker[]; } @@ -1705,6 +1711,8 @@ export interface Coverage { export interface StartCoverageOptions { /** Whether to reset coverage on every navigation. Defaults to `true`. */ resetOnNavigation?: boolean; + /** Whether anonymous scripts generated by the page should be reported. Defaults to `false`. */ + reportAnonymousScripts?: boolean; } export interface CoverageEntry { diff --git a/types/qhistory/index.d.ts b/types/qhistory/index.d.ts index 301f6b4391..84bd4e6d83 100644 --- a/types/qhistory/index.d.ts +++ b/types/qhistory/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/pshrmn/qhistory#readme // Definitions by: Diogo Franco // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 export as namespace qhistory; diff --git a/types/qunit/index.d.ts b/types/qunit/index.d.ts index 2b7eb586ff..c5e677d187 100644 --- a/types/qunit/index.d.ts +++ b/types/qunit/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for QUnit v2.5.0 // Project: http://qunitjs.com/ // Definitions by: James Bracy +// Mike North // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Assert { @@ -234,6 +235,32 @@ interface Assert { */ throws(block: () => void, expected?: any, message?: any): void; raises(block: () => void, expected?: any, message?: any): void; + + /** + * A marker for progress in a given test. + * + * The `step()` assertion registers a passing assertion with a provided message. This makes + * it easy to check that specific portions of code are being executed, especially in + * asynchronous test cases and when used with `verifySteps()`. + * + * Together with the `verifySteps()` method, `step()` assertions give you an easy way + * to verify both the count and order of code execution. + * + * @param message Message to display for the step + */ + step(message: string): void; + + /** + * A helper assertion to verify the order and number of steps in a test. + * + * The assert.verifySteps() assertion compares a given array of string values (representing steps) + * with the order and values of previous step() calls. This assertion is helpful for verifying + * the order and count of portions of code paths, especially asynchronous ones. + * + * @param steps Array of strings representing steps to verify + * @param message A short description of the assertion + */ + verifySteps(steps: string[], message?: string): void; } @@ -313,6 +340,38 @@ interface NestedHooks { } +declare namespace QUnit { + interface BeginDetails { totalTests: number } + interface DoneDetails { failed: number, passed: number, total: number, runtime: number } + interface LogDetails { + result: boolean, + actual: any; + expected: any; + message: string; + source: string; + module: string; + name: string; + runtime: number; + } + interface ModuleDoneDetails { + name: string; + failed: number; + passed: number; + total: number; + runtime: number; + } + interface ModuleStartDetails { name: string } + interface TestDoneDetails { + name: string; + module: string; + failed: number; + passed: number; + total: number; + runtime: number; + } + interface TestStartDetails { name: string; module: string; } +} + interface QUnit { /** @@ -333,7 +392,7 @@ interface QUnit { * * @callback callback Callback to execute. */ - begin(callback: (details: { totalTests: number }) => void): void; + begin(callback: (details: QUnit.BeginDetails) => void): void; /** * Configuration for QUnit @@ -348,7 +407,7 @@ interface QUnit { * * @param callback Callback to execute */ - done(callback: (details: { failed: number, passed: number, total: number, runtime: number }) => void): void; + done(callback: (details: QUnit.DoneDetails) => void): void; /** * Advanced and extensible data dumping for JavaScript. @@ -392,16 +451,7 @@ interface QUnit { * * @param callback Callback to execute */ - log(callback: (details: { - result: boolean, - actual: any; - expected: any; - message: string; - source: string; - module: string; - name: string; - runtime: number; - }) => void): void; + log(callback: (details: QUnit.LogDetails) => void): void; /** * Group related tests under a single label. @@ -449,20 +499,14 @@ interface QUnit { * * @param callback Callback to execute */ - moduleDone(callback: (details: { - name: string; - failed: number; - passed: number; - total: number; - runtime: number; - }) => void): void; + moduleDone(callback: (details: QUnit.ModuleDoneDetails) => void): void; /** * Register a callback to fire whenever a module begins. * * @param callback Callback to execute */ - moduleStart(callback: (details: { name: string }) => void): void; + moduleStart(callback: (details: QUnit.ModuleStartDetails) => void): void; /** * Adds a test to exclusively run, preventing all other tests from running. @@ -578,7 +622,7 @@ interface QUnit { * * @param callback Callback to execute */ - testStart(callback: (details: { name: string; module: string;}) => void): void; + testStart(callback: (details: QUnit.TestStartDetails) => void): void; /** * Adds a test which expects at least one failing assertion during its run. diff --git a/types/qunit/qunit-tests.ts b/types/qunit/qunit-tests.ts index e726113604..ae519cd0bc 100644 --- a/types/qunit/qunit-tests.ts +++ b/types/qunit/qunit-tests.ts @@ -214,13 +214,33 @@ QUnit.log(function( details ) { console.log( output ); }); -QUnit.moduleDone(function( details ) { - console.log( "Finished running: ", details.name, "Failed/total: ", details.failed, details.total ); +QUnit.log(function( details: QUnit.LogDetails ) { + let x: { actual: number; expected: number; message: string; module: string; name: string; result: boolean; runtime: number; source: string } = details; + x = details; }); -QUnit.moduleStart(function( details ) { +QUnit.begin(function( details: QUnit.BeginDetails ) { + console.log( "Total tests running: ", details.totalTests); +}); + +QUnit.done(function( details: QUnit.DoneDetails ) { + console.log( "Finished. Failed/total: ", details.failed, details.total, details.passed, details.runtime ); +}); + +QUnit.moduleDone(function( details: QUnit.ModuleDoneDetails ) { + console.log( "Finished running: ", details.name, "Failed/total: ", details.failed, details.total, details.passed, details.runtime ); +}); + +QUnit.moduleStart(function( details: QUnit.ModuleStartDetails ) { console.log( "Now running: ", details.name ); }); +QUnit.testDone(function( details: QUnit.TestDoneDetails ) { + console.log( "Finished running: ", details.name, "Failed/total: ", details.failed, details.total, details.passed, details.runtime); +}); + +QUnit.testStart(function( details: QUnit.TestStartDetails ) { + console.log( "Now running: ", details.name, ' from module ', details.module ); +}); let Robot: any = () => {}; @@ -562,3 +582,11 @@ equivResult = QUnit.equiv({}, {}); equivResult = QUnit.equiv(1, 2); equivResult = QUnit.equiv('foo', 'bar'); equivResult = QUnit.equiv(['foo'], ['bar']); + + +QUnit.test('steps', assert => { + assert.step('one'); + assert.step('two'); + assert.step('three'); + assert.verifySteps(['one', 'two', 'three'], 'Counting to three correctly'); +}); diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index ad57afda3f..66d3707d2b 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -9,7 +9,6 @@ // Vítor Castro // Jordan Quagliatini // Simon Højberg -// Charles-Philippe Clermont // Samson Keung // Angelo Ocana // Rayner Pupo diff --git a/types/react-adal/index.d.ts b/types/react-adal/index.d.ts new file mode 100644 index 0000000000..9f3cd9bef2 --- /dev/null +++ b/types/react-adal/index.d.ts @@ -0,0 +1,411 @@ +// Type definitions for react-adal 0.4 +// Project: https://github.com/salvoravida/react-adal#readme +// Definitions by: Dmitry Korolev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from 'react'; + +export type TokenCallback = ( + errorDesc: string | null, + token: string | null, + error: any +) => void; + +export type UserCallback = ( + errorDesc: string | null, + user: UserInfo | null +) => void; + +export interface AdalConfig { + /** + * Client ID assigned to your app by Azure Active Directory. + */ + clientId: string; + /** + * Endpoint at which you expect to receive tokens.Defaults to `window.location.href`. + */ + redirectUri?: string; + /** + * Azure Active Directory instance. Defaults to `https://login.microsoftonline.com/`. + */ + instance?: string; + /** + * Your target tenant. Defaults to `common`. + */ + tenant?: string; + /** + * Query parameters to add to the authentication request. + */ + extraQueryParameter?: string; + /** + * Unique identifier used to map the request with the response. Defaults to RFC4122 version 4 guid (128 bits). + */ + correlationId?: string; + /** + * User defined function of handling the navigation to Azure AD authorization endpoint in case of login. + */ + displayCall?: (url: string) => void; + /** + * Set this to true to enable login in a popup winodow instead of a full redirect. Defaults to `false`. + */ + popUp?: boolean; + /** + * Set this to the resource to request on login. Defaults to `clientId`. + */ + loginResource?: string; + /** + * Set this to redirect the user to a custom login page. + */ + localLoginUrl?: string; + /** + * Redirects to start page after login. Defaults to `true`. + */ + navigateToLoginRequestUrl?: boolean; + /** + * Set this to redirect the user to a custom logout page. + */ + logOutUri?: string; + /** + * Redirects the user to postLogoutRedirectUri after logout. Defaults to `redirectUri`. + */ + postLogoutRedirectUri?: string; + /** + * Sets browser storage to either 'localStorage' or sessionStorage'. Defaults to `sessionStorage`. + */ + cacheLocation?: "localStorage" | "sessionStorage"; + /** + * Array of keywords or URIs. Adal will attach a token to outgoing requests that have these keywords or URIs. + */ + endpoints?: { [resource: string]: string }; + /** + * Array of keywords or URIs. Adal will not attach a token to outgoing requests that have these keywords or URIs. + */ + anonymousEndpoints?: string[]; + /** + * If the cached token is about to be expired in the expireOffsetSeconds (in seconds), Adal will renew the token instead of using the cached token. Defaults to 300 seconds. + */ + expireOffsetSeconds?: number; + /** + * The number of milliseconds of inactivity before a token renewal response from AAD should be considered timed out. Defaults to 6 seconds. + */ + loadFrameTimeout?: number; + /** + * Callback to be invoked when a token is acquired. + */ + callback?: TokenCallback; +} + +export type LoggingLevel = 0 | 1 | 2 | 3; + +export interface RequestInfo { + /** + * Object comprising of fields such as id_token/error, session_state, state, e.t.c. + */ + parameters: any; + /** + * Request type. + */ + requestType: RequestType; + /** + * Whether state is valid. + */ + stateMatch: boolean; + /** + * Unique guid used to match the response with the request. + */ + stateResponse: string; + /** + * Whether `requestType` contains `id_token`, `access_token` or error. + */ + valid: boolean; +} + +export type RequestType = "LOGIN" | "RENEW_TOKEN" | "UNKNOWN"; + +export type ResponseType = "id_token token" | "token"; + +export interface UserInfo { + /** + * Username assigned from UPN or email. + */ + userName: string; + /** + * Properties parsed from `id_token`. + */ + profile: any; +} + +export interface Constants { + ACCESS_TOKEN: 'access_token'; + EXPIRES_IN: 'expires_in'; + ID_TOKEN: 'id_token'; + ERROR_DESCRIPTION: 'error_description'; + SESSION_STATE: 'session_state'; + STORAGE: { + TOKEN_KEYS: 'adal.token.keys'; + ACCESS_TOKEN_KEY: 'adal.access.token.key'; + EXPIRATION_KEY: 'adal.expiration.key'; + STATE_LOGIN: 'adal.state.login'; + STATE_RENEW: 'adal.state.renew'; + NONCE_IDTOKEN: 'adal.nonce.idtoken'; + SESSION_STATE: 'adal.session.state'; + USERNAME: 'adal.username'; + IDTOKEN: 'adal.idtoken'; + ERROR: 'adal.error'; + ERROR_DESCRIPTION: 'adal.error.description'; + LOGIN_REQUEST: 'adal.login.request'; + LOGIN_ERROR: 'adal.login.error'; + RENEW_STATUS: 'adal.token.renew.status'; + }; + RESOURCE_DELIMETER: '|'; + LOADFRAME_TIMEOUT: '6000'; + TOKEN_RENEW_STATUS_CANCELED: 'Canceled'; + TOKEN_RENEW_STATUS_COMPLETED: 'Completed'; + TOKEN_RENEW_STATUS_IN_PROGRESS: 'In Progress'; + LOGGING_LEVEL: { + ERROR: 0; + WARN: 1; + INFO: 2; + VERBOSE: 3; + }; + LEVEL_STRING_MAP: { + 0: 'ERROR:'; + 1: 'WARNING:'; + 2: 'INFO:'; + 3: 'VERBOSE:'; + }; + POPUP_WIDTH: 483; + POPUP_HEIGHT: 600; +} + +export class AuthenticationContext { + instance: string; + config: AdalConfig; + callback: TokenCallback; + popUp: boolean; + isAngular: boolean; + + /** + * Enum for request type + */ + REQUEST_TYPE: RequestType; + RESPONSE_TYPE: ResponseType; + CONSTANTS: Constants; + + constructor(options: AdalConfig); + /** + * Initiates the login process by redirecting the user to Azure AD authorization endpoint. + */ + login(): void; + /** + * Returns whether a login is in progress. + */ + loginInProgress(): boolean; + /** + * Gets token for the specified resource from the cache. + * @param resource A URI that identifies the resource for which the token is requested. + */ + getCachedToken(resource: string): string; + /** + * If user object exists, returns it. Else creates a new user object by decoding `id_token` from the cache. + */ + getCachedUser(): UserInfo; + /** + * Adds the passed callback to the array of callbacks for the specified resource. + * @param resource A URI that identifies the resource for which the token is requested. + * @param expectedState A unique identifier (guid). + * @param callback The callback provided by the caller. It will be called with token or error. + */ + registerCallback( + expectedState: string, + resource: string, + callback: TokenCallback + ): void; + /** + * Acquires token from the cache if it is not expired. Otherwise sends request to AAD to obtain a new token. + * @param resource Resource URI identifying the target resource. + * @param callback The callback provided by the caller. It will be called with token or error. + */ + acquireToken(resource: string, callback: TokenCallback): void; + /** + * Acquires token (interactive flow using a popup window) by sending request to AAD to obtain a new token. + * @param resource Resource URI identifying the target resource. + * @param extraQueryParameters Query parameters to add to the authentication request. + * @param claims Claims to add to the authentication request. + * @param callback The callback provided by the caller. It will be called with token or error. + */ + acquireTokenPopup( + resource: string, + extraQueryParameters: string | null | undefined, + claims: string | null | undefined, + callback: TokenCallback + ): void; + /** + * Acquires token (interactive flow using a redirect) by sending request to AAD to obtain a new token. In this case the callback passed in the authentication request constructor will be called. + * @param resource Resource URI identifying the target resource. + * @param extraQueryParameters Query parameters to add to the authentication request. + * @param claims Claims to add to the authentication request. + */ + acquireTokenRedirect( + resource: string, + extraQueryParameters?: string | null, + claims?: string | null + ): void; + /** + * Redirects the browser to Azure AD authorization endpoint. + * @param urlNavigate URL of the authorization endpoint. + */ + promptUser(urlNavigate: string): void; + /** + * Clears cache items. + */ + clearCache(): void; + /** + * Clears cache items for a given resource. + * @param resource Resource URI identifying the target resource. + */ + clearCacheForResource(resource: string): void; + /** + * Redirects user to logout endpoint. After logout, it will redirect to `postLogoutRedirectUri` if added as a property on the config object. + */ + logOut(): void; + /** + * Calls the passed in callback with the user object or error message related to the user. + * @param callback The callback provided by the caller. It will be called with user or error. + */ + getUser(callback: UserCallback): void; + /** + * Checks if the URL fragment contains access token, id token or error description. + * @param hash Hash passed from redirect page. + */ + isCallback(hash: string): boolean; + /** + * Gets login error. + */ + getLoginError(): string; + /** + * Creates a request info object from the URL fragment and returns it. + */ + getRequestInfo(hash: string): RequestInfo; + /** + * Saves token or error received in the response from AAD in the cache. In case of `id_token`, it also creates the user object. + */ + saveTokenFromHash(requestInfo: RequestInfo): void; + /** + * Gets resource for given endpoint if mapping is provided with config. + * @param endpoint Resource URI identifying the target resource. + */ + getResourceForEndpoint(resource: string): string; + /** + * This method must be called for processing the response received from AAD. It extracts the hash, processes the token or error, saves it in the cache and calls the callbacks with the result. + * @param hash Hash fragment of URL. Defaults to `window.location.hash`. + */ + handleWindowCallback(hash?: string): void; + + /** + * Checks the logging Level, constructs the log message and logs it. Users need to implement/override this method to turn on logging. + * @param level Level can be set 0, 1, 2 and 3 which turns on 'error', 'warning', 'info' or 'verbose' level logging respectively. + * @param message Message to log. + * @param error Error to log. + */ + log(level: LoggingLevel, message: string, error: any): void; + /** + * Logs messages when logging level is set to 0. + * @param message Message to log. + * @param error Error to log. + */ + error(message: string, error: any): void; + /** + * Logs messages when logging level is set to 1. + * @param message Message to log. + */ + warn(message: string): void; + /** + * Logs messages when logging level is set to 2. + * @param message Message to log. + */ + info(message: string): void; + /** + * Logs messages when logging level is set to 3. + * @param message Message to log. + */ + verbose(message: string): void; + + /** + * Logs Pii messages when Logging Level is set to 0 and window.piiLoggingEnabled is set to true. + * @param message Message to log. + * @param error Error to log. + */ + errorPii(message: string, error: any): void; + + /** + * Logs Pii messages when Logging Level is set to 1 and window.piiLoggingEnabled is set to true. + * @param message Message to log. + */ + warnPii(message: string): void; + + /** + * Logs messages when Logging Level is set to 2 and window.piiLoggingEnabled is set to true. + * @param message Message to log. + */ + infoPii(message: string): void; + + /** + * Logs messages when Logging Level is set to 3 and window.piiLoggingEnabled is set to true. + * @param message Message to log. + */ + verbosePii(message: string): void; +} + +/** + * Return user token + * @param authContext Authentication context + * @param resource Resource GUID ot URI identifying the target resource. + */ +export function adalGetToken( + authContext: AuthenticationContext, + resourceUrl: string +): Promise; + +/** + * Allows to make requests with adal token + * @param authContext Authentication context + * @param resource Resource GUID ot URI identifying the target resource. + * @param fetch Fetch client + * @param url Request url + * @param options Fetch options + */ +export function adalFetch( + authContext: AuthenticationContext, + resource: string, + fetch: (input: string, init: any) => Promise, + url: string, + options: any +): Promise; + +/** + * Wrap for the app + * @param authContext Authentication context + * @param app Render app callback + * @param doNotLogin Don`t need to login? + */ +export function runWithAdal( + authContext: AuthenticationContext, + app: () => void, + doNotLogin: boolean +): void; + +/** + * Creates a HOC that can be used to manage authentication for the certain components + * @param authContext Authentication context + * @param resource Resource GUID ot URI identifying the target resource. + */ +export function withAdalLogin( + authContext: AuthenticationContext, + resource: string +): ( + wrappedComponent: React.ComponentClass | React.StatelessComponent, + renderLoading: () => JSX.Element | null, + renderError: (error: any) => JSX.Element | null +) => React.ComponentClass; diff --git a/types/react-adal/react-adal-tests.tsx b/types/react-adal/react-adal-tests.tsx new file mode 100644 index 0000000000..961246560f --- /dev/null +++ b/types/react-adal/react-adal-tests.tsx @@ -0,0 +1,75 @@ +import * as React from 'react'; +import { AuthenticationContext, adalFetch, adalGetToken, runWithAdal, withAdalLogin, AdalConfig } from 'react-adal'; + +const resourceUrl = 'https://graph.microsoft.net'; + +const adalConfig: AdalConfig = { + cacheLocation: "localStorage", + clientId: '9ha8cqc6-4668-459a-9272-f48c80a053y5', + endpoints: { + api: resourceUrl + }, + postLogoutRedirectUri: 'https://localhost:3000', + tenant: 'tenantname.onmicrosoft.com' + }; + +const authContext = new AuthenticationContext(adalConfig); + +const adalApiFetch = (fetch: any, url: string, options: any) => { + return adalFetch(authContext, resourceUrl, fetch, url, options); +}; + +const getToken = () => adalGetToken(authContext, resourceUrl); + +class App extends React.Component { + render() { + return null; + } +} + +// user must login to use the app +runWithAdal(authContext, () => { + // ReactDOM.render(, document.getElementById('react-app') as HTMLElement); +}, false); + +const withAdalLoginApi = withAdalLogin(authContext, resourceUrl); + +const Loading: React.SFC = (props) => { + return null; +}; + +const ErrorPage: React.SFC = (props) => { + return null; +}; + +class SignInPage extends React.Component { + render() { + return null; + } +} + +class ProtectedPage1 extends React.Component { + render() { + return null; + } +} + +const ProtectedPage2: React.SFC = (props) => { + return null; +}; + +const AdalProtectedPage1 = withAdalLoginApi(ProtectedPage1, () => , () => ); +const AdalProtectedPage2 = withAdalLoginApi(ProtectedPage2, () =>

loading...

, () =>

It seems something went wrong...

); + +// user must login to use only specific pages +runWithAdal(authContext, () => { + const routes =
+ // $ExpectError + // $ExpectError + // $ExpectError +
; + // $ExpectError + const App = ; + // $ExpectError + ReactDOM.render(, document.getElementById('react-app') as HTMLElement); +}, true); diff --git a/types/react-adal/tsconfig.json b/types/react-adal/tsconfig.json new file mode 100644 index 0000000000..b77e4dffc1 --- /dev/null +++ b/types/react-adal/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-adal-tests.tsx" + ] +} diff --git a/types/react-adal/tslint.json b/types/react-adal/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-adal/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-big-calendar/index.d.ts b/types/react-big-calendar/index.d.ts index b73ffcc0d9..9275511fc9 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -86,11 +86,23 @@ export interface Format { eventTimeRangeEndFormat?: string; } +export interface HeaderProps { + culture: BigCalendarProps['culture']; + date: Date; + format: string; + label: string; + localizer: object; +} + export interface Components { event?: React.SFC | React.Component | React.ComponentClass | JSX.Element; eventWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; dayWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; dateCellWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; + /** + * component used as a header for each column in the TimeGridHeader + */ + header?: React.ComponentType; toolbar?: React.SFC | React.Component | React.ComponentClass | JSX.Element; agenda?: { date?: React.SFC | React.Component | React.ComponentClass | JSX.Element; diff --git a/types/react-measure/index.d.ts b/types/react-measure/index.d.ts index c61b22b187..241d482a53 100644 --- a/types/react-measure/index.d.ts +++ b/types/react-measure/index.d.ts @@ -46,7 +46,7 @@ export interface MeasuredComponentProps { type MeasuredComponent = React.ComponentType; -export interface MeasureProps { +export interface MeasureProps { client?: boolean; offset?: boolean; scroll?: boolean; @@ -60,5 +60,5 @@ export interface MeasureProps { export declare function withContentRect(types: ReadonlyArray | MeasurementType): (fn: MeasuredComponent) => React.ComponentType; -declare class Measure extends React.Component> {} +declare class Measure extends React.Component {} export default Measure; diff --git a/types/react-native-calendars/index.d.ts b/types/react-native-calendars/index.d.ts new file mode 100644 index 0000000000..6294af4682 --- /dev/null +++ b/types/react-native-calendars/index.d.ts @@ -0,0 +1,418 @@ +// Type definitions for react-native-calendars 1.20 +// Project: https://github.com/wix/react-native-calendars#readme +// Definitions by: Tyler Zhang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from 'react'; +import { ViewProps, StyleProp } from 'react-native'; + +export interface DateObject { + year: number; + month: number; + day: number; + timestamp: number; + dateString: string; +} + +export interface CalendarTheme { + backgroundColor?: string; + calendarBackground?: string; + textSectionTitleColor?: string; + selectedDayBackgroundColor?: string; + selectedDayTextColor?: string; + todayTextColor?: string; + dayTextColor?: string; + textDisabledColor?: string; + dotColor?: string; + selectedDotColor?: string; + arrowColor?: string; + monthTextColor?: string; + textDayFontFamily?: string; + textMonthFontFamily?: string; + textDayHeaderFontFamily?: string; + textMonthFontWeight?: string; + textDayFontSize?: number; + textMonthFontSize?: number; + textDayHeaderFontSize?: number; +} + +export interface DayComponentProps { + state: '' | 'selected' | 'disabled' | 'today'; + theme: CalendarTheme; + onPress: () => any; + onLongPress: () => any; + date: DateObject; + marking: false | Marking[]; +} + +export interface CalendarBaseProps { + /** + * Styles for the view + */ + style?: StyleProp; + + /** + * Specify theme properties to override specific styles for calendar parts. Default = {} + */ + theme?: CalendarTheme; + + /** + * Initially visible month. Default = Date() + */ + current?: Date | string; + + /** + * Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined + */ + minDate?: Date | string; + + /** + * Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined + */ + maxDate?: Date | string; + + /** + * Handler which gets executed on day press. Default = undefined + */ + onDayPress?: (day: number) => void; + + /** + * Handler which gets executed on day long press. Default = undefined + */ + onDayLongPress?: (day: number) => void; + + /** + * Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting + */ + monthFormat?: string; + + /** + * Handler which gets executed when visible month changes in calendar. Default = undefined + */ + onMonthChange?: (month: number) => void; + + /** + * Hide month navigation arrows. Default = false + */ + hideArrows?: boolean; + + /** + * Replace default arrows with custom ones (direction can be 'left' or 'right') + */ + renderArrow?: (direction: 'left' | 'right') => React.ReactNode; + + /** + * Do not show days of other months in month page. Default = false + */ + hideExtraDays?: boolean; + + /** + * If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out + * day from another month that is visible in calendar page. Default = false + */ + disableMonthChange?: boolean; + + /** + * If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday. + */ + firstDay?: number; + + /** + * Hide day names. Default = false + */ + hideDayNames?: boolean; + + /** + * Show week numbers to the left. Default = false + */ + showWeekNumbers?: boolean; + + /** + * Handler which gets executed when press arrow icon left. It receive a callback can go back month + */ + onPressArrowLeft?: (month: number) => void; + + /** + * Handler which gets executed when press arrow icon left. It receive a callback can go next month + */ + onPressArrowRight?: (month: number) => void; + + /** + * Custom day renderer + */ + dayComponent?: React.Component | React.SFC; +} + +export interface DotForMultiDot { + key: string; + color: string; + selectedDotColor?: string; +} + +export interface MultiDotMarking { + dots: DotForMultiDot[]; + selected?: boolean; + selectedColor?: string; + disabled?: boolean; +} + +export interface DotMarking { + selected?: boolean; + marked?: boolean; + selectedColor?: string; + dotColor?: string; + activeOpacity?: number; + disabled?: boolean; + disableTouchEvent?: boolean; +} + +export interface PeriodMarking { + textColor?: string; + startingDay?: boolean; + color?: string; + selected?: boolean; + endingDay?: boolean; + disabled?: boolean; +} + +export interface MultiPeriodMarking { + periods: Array<{ + startingDay?: boolean; + endingDay?: boolean; + color?: string; + }>; +} + +export interface CustomMarking { + customStyles: any; +} + +export type Marking = + MultiDotMarking | + DotMarking | + PeriodMarking | + MultiPeriodMarking | + CustomMarking; + +export interface MultiDotMarkingProps { + markingType: 'multi-dot'; + markedDates: { + [date: string]: MultiDotMarking; + }; +} + +export interface DotMarkingProps { + markingType?: 'simple'; + markedDates: { + [date: string]: DotMarking; + }; +} + +export interface PeriodMarkingProps { + markingType: 'period'; + markedDates: { + [date: string]: PeriodMarking; + }; +} + +export interface CustomMarkingProps { + markingType: 'custom'; + markedDates: { + [date: string]: CustomMarking; + }; +} + +/** + * This type of marking is only fully supported by as it will expand the height + * of the component + */ +export interface MultiPeriodMarkingProps { + markingType: 'multi-period'; + markedDates: { + [date: string]: MultiPeriodMarking + }; +} + +export type CalendarMarkingProps = + MultiDotMarkingProps | + DotMarkingProps | + PeriodMarkingProps | + MultiPeriodMarkingProps | + CustomMarkingProps | + {}; + +export class Calendar extends React.Component {} + +export interface CalendarListBaseProps extends CalendarBaseProps { + /** + * Callback which gets executed when visible months change in scroll view. Default = undefined + */ + onVisibleMonthsChange?: (months: number) => void; + + /** + * Max amount of months allowed to scroll to the past. Default = 50 + */ + pastScrollRange?: number; + + /** + * Max amount of months allowed to scroll to the future. Default = 50 + */ + futureScrollRange?: number; + + /** + * Enable or disable scrolling of calendar list + */ + scrollEnabled?: boolean; + + /** + * Enable or disable vertical scroll indicator. Default = false + */ + showScrollIndicator?: boolean; + + /** + * Enable horizontal scrolling, default = false + */ + horizontal?: boolean; + + /** + * Enable paging on horizontal, default = false + */ + pagingEnabled?: boolean; + + /** + * Set custom calendarWidth. + */ + calendarWidth?: boolean; +} + +export class CalendarList extends React.Component {} + +export interface AgendaProps { + /** + * the list of items that have to be displayed in agenda. If you want to render item as empty date + * the value of date key kas to be an empty array []. If there exists no value for date key it is + * considered that the date in question is not yet loaded + */ + items: { + [key: string]: T[]; + }; + + /** + * callback that gets called when items for a certain month should be loaded (month became visible) + */ + loadItemsForMonth?: (date: DateObject) => void; + + /** + * callback that fires when the calendar is opened or closed + */ + onCalendarToggled?: (calendarOpened: boolean) => void; + + /** + * callback that gets called on day press + */ + onDayPress?: (day: number) => void; + + /** + * callback that gets called when day changes while scrolling agenda list + */ + onDayChange?: (day: number) => void; + + /** + * initially selected day + */ + selected?: Date | string; + + /** + * Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined + */ + minDate?: Date | string; + + /** + * Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined + */ + maxDate?: Date | string; + + /** + * Max amount of months allowed to scroll to the past. Default = 50 + */ + pastScrollRange?: number; + + /** + * Max amount of months allowed to scroll to the future. Default = 50 + */ + futureScrollRange?: number; + + /** + * specify how each item should be rendered in agenda + */ + renderItem: (item: T, firstItemInDay?: T) => React.ReactNode; + + /** + * specify how each date should be rendered. day can be undefined if the item is not first in that day. + */ + renderDay?: (day: DateObject | undefined, item: T) => React.ReactNode; + + /** + * specify how empty date content with no items should be rendered + */ + renderEmptyDate?: () => React.ReactNode; + + /** + * specify how agenda knob should look like + */ + renderKnob?: () => React.ReactNode; + + /** + * specify what should be rendered instead of ActivityIndicator + */ + renderEmptyData?: () => React.ReactNode; + + /** + * specify your item comparison function for increased performance + */ + rowHasChanged?: (r1: any, r2: any) => boolean; + + /** + * Hide knob button. Default = false + */ + hideKnob?: boolean; + + /** + * A RefreshControl component, used to provide pull-to-refresh funtionality for the ScrollView + */ + refreshControl?: React.ReactNode; + + /** + * If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. + * Make sure to also set the refreshing prop correctly. + */ + onRefresh?: () => any; + + /** + * Set this true while waiting for new data from a refresh + */ + refreshing?: boolean; + + /** + * Display loading indicator. Default = false + */ + displayLoadingIndicator?: boolean; + + /** + * agenda theme + */ + theme?: { + agendaDayTextColor?: string; + agendaDayNumColor?: string; + agendaTodayColor?: string; + agendaKnobColor?: string; + } & CalendarTheme; + + /** + * agenda container style + */ + style?: StyleProp; +} + +export class Agenda extends React.Component & CalendarMarkingProps> {} diff --git a/types/react-native-calendars/react-native-calendars-tests.tsx b/types/react-native-calendars/react-native-calendars-tests.tsx new file mode 100644 index 0000000000..5b438937e1 --- /dev/null +++ b/types/react-native-calendars/react-native-calendars-tests.tsx @@ -0,0 +1,374 @@ +import * as React from "react"; +import { Text, View } from "react-native"; +import { Calendar, CalendarList, Agenda } from "react-native-calendars"; + + { + console.log("selected day", day); + }} + // Handler which gets executed on day long press. Default = undefined + onDayLongPress={day => { + console.log("selected day", day); + }} + // Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting + monthFormat={"yyyy MM"} + // Handler which gets executed when visible month changes in calendar. Default = undefined + onMonthChange={month => { + console.log("month changed", month); + }} + // Hide month navigation arrows. Default = false + hideArrows={true} + // Replace default arrows with custom ones (direction can be 'left' or 'right') + renderArrow={direction =>
} + // Do not show days of other months in month page. Default = false + hideExtraDays={true} + // If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out + // day from another month that is visible in calendar page. Default = false + disableMonthChange={true} + // If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday. + firstDay={1} + // Hide day names. Default = false + hideDayNames={true} + // Show week numbers to the left. Default = false + showWeekNumbers={true} + // Handler which gets executed when press arrow icon left. It receive a callback can go back month + onPressArrowLeft={substractMonth => console.log(substractMonth)} + // Handler which gets executed when press arrow icon left. It receive a callback can go next month + onPressArrowRight={addMonth => console.log(addMonth)} +/>; + + { + console.log("selected day", day); + }} + // Handler which gets executed on day long press. Default = undefined + onDayLongPress={day => { + console.log("selected day", day); + }} + // Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting + monthFormat={"yyyy MM"} + // Handler which gets executed when visible month changes in calendar. Default = undefined + onMonthChange={month => { + console.log("month changed", month); + }} + // Hide month navigation arrows. Default = false + hideArrows={true} + // Replace default arrows with custom ones (direction can be 'left' or 'right') + renderArrow={direction =>
} + // Do not show days of other months in month page. Default = false + hideExtraDays={true} + // If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out + // day from another month that is visible in calendar page. Default = false + disableMonthChange={true} + // If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday. + firstDay={1} + // Hide day names. Default = false + hideDayNames={true} + // Show week numbers to the left. Default = false + showWeekNumbers={true} + // Handler which gets executed when press arrow icon left. It receive a callback can go back month + onPressArrowLeft={substractMonth => console.log(substractMonth)} + // Handler which gets executed when press arrow icon left. It receive a callback can go next month + onPressArrowRight={addMonth => console.log(addMonth)} + markedDates={{ + "2012-05-16": { selected: true, marked: true, selectedColor: "blue" }, + "2012-05-17": { marked: true }, + "2012-05-18": { marked: true, dotColor: "red", activeOpacity: 0 }, + "2012-05-19": { disabled: true, disableTouchEvent: true } + }} +/>; + +const vacation = { key: "vacation", color: "red", selectedDotColor: "blue" }; +const massage = { key: "massage", color: "blue", selectedDotColor: "blue" }; +const workout = { key: "workout", color: "green" }; + +; + +; + +; + +; + +; + + { + return ( + + + {date.day} + + + ); + }} +/>; + + { + console.log("now these months are visible", months); + }} + // Max amount of months allowed to scroll to the past. Default = 50 + pastScrollRange={50} + // Horizontal + horizontal={true} + // Max amount of months allowed to scroll to the future. Default = 50 + futureScrollRange={50} + // Enable or disable scrolling of calendar list + scrollEnabled={true} + // Enable or disable vertical scroll indicator. Default = false + showScrollIndicator={true} + // Initially visible month. Default = Date() + current={"2012-03-01"} + // Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined + minDate={"2012-05-10"} + // Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined + maxDate={"2012-05-30"} + // Handler which gets executed on day press. Default = undefined + onDayPress={day => { + console.log("selected day", day); + }} + // Handler which gets executed on day long press. Default = undefined + onDayLongPress={day => { + console.log("selected day", day); + }} + // Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting + monthFormat={"yyyy MM"} + // Handler which gets executed when visible month changes in calendar. Default = undefined + onMonthChange={month => { + console.log("month changed", month); + }} + // Hide month navigation arrows. Default = false + hideArrows={true} + // Replace default arrows with custom ones (direction can be 'left' or 'right') + renderArrow={direction =>
} + // Do not show days of other months in month page. Default = false + hideExtraDays={true} + // If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out + // day from another month that is visible in calendar page. Default = false + disableMonthChange={true} + // If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday. + firstDay={1} + // Hide day names. Default = false + hideDayNames={true} + // Show week numbers to the left. Default = false + showWeekNumbers={true} + // Handler which gets executed when press arrow icon left. It receive a callback can go back month + onPressArrowLeft={substractMonth => console.log(substractMonth)} + // Handler which gets executed when press arrow icon left. It receive a callback can go next month + onPressArrowRight={addMonth => console.log(addMonth)} +/>; + + { + console.log("trigger items loading"); + }} + // callback that fires when the calendar is opened or closed + onCalendarToggled={calendarOpened => { + console.log(calendarOpened); + }} + // callback that gets called on day press + onDayPress={day => { + console.log("day pressed"); + }} + // callback that gets called when day changes while scrolling agenda list + onDayChange={day => { + console.log("day changed"); + }} + // initially selected day + selected={"2012-05-16"} + // Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined + minDate={"2012-05-10"} + // Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined + maxDate={"2012-05-30"} + // Max amount of months allowed to scroll to the past. Default = 50 + pastScrollRange={50} + // Max amount of months allowed to scroll to the future. Default = 50 + futureScrollRange={50} + // specify how each item should be rendered in agenda + renderItem={(item, firstItemInDay) => { + return ; + }} + // specify how each date should be rendered. day can be undefined if the item is not first in that day. + renderDay={(day, item) => { + return ; + }} + // specify how empty date content with no items should be rendered + renderEmptyDate={() => { + return ; + }} + // specify how agenda knob should look like + renderKnob={() => { + return ; + }} + // specify what should be rendered instead of ActivityIndicator + renderEmptyData={() => { + return ; + }} + // specify your item comparison function for increased performance + rowHasChanged={(r1, r2) => { + return r1.text !== r2.text; + }} + // Hide knob button. Default = false + hideKnob={true} + // By default, agenda dates are marked if they have at least one item, but you can override this if needed + markedDates={{ + "2012-05-16": { selected: true, marked: true }, + "2012-05-17": { marked: true }, + "2012-05-18": { disabled: true } + }} + // If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. Make sure to also set the refreshing prop correctly. + onRefresh={() => console.log("refreshing...")} + // Set this true while waiting for new data from a refresh + refreshing={false} + // Add a custom RefreshControl component, used to provide pull-to-refresh functionality for the ScrollView. + refreshControl={null} + // agenda theme + theme={{ + agendaDayTextColor: "yellow", + agendaDayNumColor: "green", + agendaTodayColor: "red", + agendaKnobColor: "blue" + }} + // agenda container style + style={{}} +/>; diff --git a/types/react-native-calendars/tsconfig.json b/types/react-native-calendars/tsconfig.json new file mode 100644 index 0000000000..e13f60597a --- /dev/null +++ b/types/react-native-calendars/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "react-native-calendars-tests.tsx" + ] +} diff --git a/types/react-native-calendars/tslint.json b/types/react-native-calendars/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-calendars/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-no-ssr/index.d.ts b/types/react-no-ssr/index.d.ts new file mode 100644 index 0000000000..77d52af1ff --- /dev/null +++ b/types/react-no-ssr/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for react-no-ssr 1.1 +// Project: https://github.com/kadirahq/react-no-ssr +// Definitions by: Rafał Filipek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from 'react'; + +export default class NoSSR extends React.Component<{ + onSSR?: React.ReactChild; +}> {} diff --git a/types/react-no-ssr/react-no-ssr-tests.tsx b/types/react-no-ssr/react-no-ssr-tests.tsx new file mode 100644 index 0000000000..62ad9b1989 --- /dev/null +++ b/types/react-no-ssr/react-no-ssr-tests.tsx @@ -0,0 +1,17 @@ +import * as React from 'react'; +import NoSSR from 'react-no-ssr'; + +export class NoSSRTest extends React.Component { + render() { + return ( +
+ +
+ + }> +
+ +
+ ); + } +} diff --git a/types/react-no-ssr/tsconfig.json b/types/react-no-ssr/tsconfig.json new file mode 100644 index 0000000000..23e59891d8 --- /dev/null +++ b/types/react-no-ssr/tsconfig.json @@ -0,0 +1,18 @@ +{ + "files": ["index.d.ts", "react-no-ssr-tests.tsx"], + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "experimentalDecorators": true, + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/types/react-no-ssr/tslint.json b/types/react-no-ssr/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-no-ssr/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-portal/index.d.ts b/types/react-portal/index.d.ts index 7595c5e8ad..2994290013 100644 --- a/types/react-portal/index.d.ts +++ b/types/react-portal/index.d.ts @@ -1,25 +1,35 @@ -// Type definitions for react-portal 3.0 +// Type definitions for react-portal 4.0 // Project: https://github.com/tajo/react-portal#readme // Definitions by: Shun Takahashi +// Horus Lugo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 import * as React from "react"; -interface CallBackProps extends React.Props { - closePortal(): void; +export interface PortalProps extends React.Props { + children: React.ReactNode; + node?: Element | null; } -interface ReactPortalProps { - isOpened?: boolean; - openByClickOn?: React.ReactElement; +export const Portal: React.ComponentClass; + +export interface PortalFunctionParams { + openPortal: (event?: any) => void; + closePortal: () => void; + portal: (children: React.ReactNode) => React.ReactElement>; + isOpen: boolean; +} + +export interface PortalWithStateProps extends React.Props { + children: (params: PortalFunctionParams) => React.ReactNode; + node?: Element | null; + defaultOpen?: boolean; + openByClickOn?: React.ReactElement; closeOnEsc?: boolean; closeOnOutsideClick?: boolean; - onOpen?(node: HTMLDivElement): void; - beforeClose?(node: HTMLDivElement, resetPortalState: () => void): void; + onOpen?(): void; onClose?(): void; - onUpdate?(): void; } -declare const ReactPortal: React.ComponentClass; -export = ReactPortal; +export const PortalWithState: React.ComponentClass; diff --git a/types/react-portal/react-portal-tests.tsx b/types/react-portal/react-portal-tests.tsx index 5313b101bd..7ee7183e45 100644 --- a/types/react-portal/react-portal-tests.tsx +++ b/types/react-portal/react-portal-tests.tsx @@ -1,44 +1,79 @@ // Example from https://github.com/tajo/react-portal -import * as React from "react"; -import * as ReactDOM from "react-dom"; -import Portal = require("react-portal"); +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import { Portal, PortalWithState } from 'react-portal'; -export default class App extends React.Component { - render() { - const button1 = ; - - return ( -
- {}} - beforeClose={(node: HTMLDivElement, resetPortalState) => resetPortalState()} - onClose={() => {}} - onUpdate={() => {}} - > - -

Pseudo Modal

-

This react component is appended to the document body.

-
-
- -
- ); - } +interface AppState { + isPortalOneActive: boolean; + isPortalTwoActive: boolean; } -export class PseudoModal extends React.Component<{ closePortal?(): void }> { - render() { - return ( -
- {this.props.children} -

-
- ); - } +export default class App extends React.Component<{}, AppState> { + constructor(props: any) { + super(props); + + this.state = { + isPortalOneActive: false, + isPortalTwoActive: false + }; + } + + render() { + return ( +
+

React Portal Examples

+

+ + https://github.com/tajo/react-portal + +

+ +

Portal (stateless)

+ + {this.state.isPortalOneActive && ( + +

This thing was portaled!

+
+ )} + +

Portal (stateless, custom node)

+ + {this.state.isPortalTwoActive && ( + +

This thing was portaled!

+
+ )} + +

PortalWithState

+ + {({ openPortal, closePortal, isOpen, portal }) => [ + , + portal( +

+ This is more advanced Portal. It handles its own state.{' '} + , hit ESC or + click outside of me. +

+ ) + ]} +
+
+ ); + } } -ReactDOM.render(, document.getElementById('react-body')); +ReactDOM.render(, document.getElementById('root')); diff --git a/types/react-portal/v3/index.d.ts b/types/react-portal/v3/index.d.ts new file mode 100644 index 0000000000..7595c5e8ad --- /dev/null +++ b/types/react-portal/v3/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for react-portal 3.0 +// Project: https://github.com/tajo/react-portal#readme +// Definitions by: Shun Takahashi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from "react"; + +interface CallBackProps extends React.Props { + closePortal(): void; +} + +interface ReactPortalProps { + isOpened?: boolean; + openByClickOn?: React.ReactElement; + closeOnEsc?: boolean; + closeOnOutsideClick?: boolean; + onOpen?(node: HTMLDivElement): void; + beforeClose?(node: HTMLDivElement, resetPortalState: () => void): void; + onClose?(): void; + onUpdate?(): void; +} + +declare const ReactPortal: React.ComponentClass; +export = ReactPortal; diff --git a/types/react-portal/v3/react-portal-tests.tsx b/types/react-portal/v3/react-portal-tests.tsx new file mode 100644 index 0000000000..ca6c0289de --- /dev/null +++ b/types/react-portal/v3/react-portal-tests.tsx @@ -0,0 +1,44 @@ +// Example from https://github.com/tajo/react-portal +import * as React from "react"; +import * as ReactDOM from "react-dom"; +import * as Portal from "react-portal"; + +export default class App extends React.Component { + render() { + const button1 = ; + + return ( +
+ {}} + beforeClose={(node: HTMLDivElement, resetPortalState) => resetPortalState()} + onClose={() => {}} + onUpdate={() => {}} + > + +

Pseudo Modal

+

This react component is appended to the document body.

+
+
+ +
+ ); + } +} + +export class PseudoModal extends React.Component<{ closePortal?(): void }> { + render() { + return ( +
+ {this.props.children} +

+
+ ); + } +} + +ReactDOM.render(, document.getElementById('react-body')); diff --git a/types/react-portal/v3/tsconfig.json b/types/react-portal/v3/tsconfig.json new file mode 100644 index 0000000000..3b6f5c966a --- /dev/null +++ b/types/react-portal/v3/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "lib": [ + "es6", + "dom" + ], + "jsx": "react", + "paths": { + "react-portal": [ "react-portal/v3" ] + } + }, + "files": [ + "index.d.ts", + "react-portal-tests.tsx" + ] +} diff --git a/types/react-portal/v3/tslint.json b/types/react-portal/v3/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-portal/v3/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-qr-reader/index.d.ts b/types/react-qr-reader/index.d.ts new file mode 100644 index 0000000000..d58da0e89f --- /dev/null +++ b/types/react-qr-reader/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for react-qr-reader 2.1 +// Project: https://github.com/JodusNodus/react-qr-reader +// Definitions by: David Kevork +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from "react"; + +export as namespace QrReader; + +export default QrReader; + +export namespace QrReader { + interface props { + onScan: (data: string | null) => void; + onError: (err: any) => void; + onLoad?: () => void; + onImageLoad?: (event: React.SyntheticEvent) => void; + delay?: number | false; + facingMode?: 'user' | 'environment'; + legacyMode?: boolean; + resolution?: number; + showViewFinder?: boolean; + style?: any; + className?: string; + } +} + +declare class QrReader extends React.Component { +} diff --git a/types/react-qr-reader/react-qr-reader-tests.tsx b/types/react-qr-reader/react-qr-reader-tests.tsx new file mode 100644 index 0000000000..20632f8029 --- /dev/null +++ b/types/react-qr-reader/react-qr-reader-tests.tsx @@ -0,0 +1,14 @@ +import * as React from "react"; +import QrReader from "react-qr-reader"; + +export class Test extends React.Component { + render() { + return ( + { console.log(err); }} + onScan={(data) => { console.log(data); }} + facingMode={'user'} + /> + ); + } +} diff --git a/types/react-qr-reader/tsconfig.json b/types/react-qr-reader/tsconfig.json new file mode 100644 index 0000000000..89aebb0de5 --- /dev/null +++ b/types/react-qr-reader/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-qr-reader-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/react-qr-reader/tslint.json b/types/react-qr-reader/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-qr-reader/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-router/index.d.ts b/types/react-router/index.d.ts index 05d5fe30bb..6814ecf19f 100644 --- a/types/react-router/index.d.ts +++ b/types/react-router/index.d.ts @@ -64,9 +64,9 @@ export interface StaticContext { statusCode?: number; } -export interface RouteComponentProps { +export interface RouteComponentProps { history: H.History; - location: H.Location; + location: H.Location; match: match

; staticContext?: C; } diff --git a/types/react-select/index.d.ts b/types/react-select/index.d.ts index bde3c3c6a0..b3d5490d9f 100644 --- a/types/react-select/index.d.ts +++ b/types/react-select/index.d.ts @@ -13,6 +13,7 @@ // David Schkalee // Arthur Udalov // Sebastian Silbermann +// Endurance Idehen // Guillaume Chartier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -241,7 +242,7 @@ export interface ReactSelectProps extends React.Props extends Partial { name: string; - label?: string; component?: ComponentType | "input" | "select" | "textarea"; format?: Formatter | null; normalize?: Normalizer; @@ -73,7 +72,6 @@ export class Field

extends Comp export interface WrappedFieldProps { input: WrappedFieldInputProps; meta: WrappedFieldMetaProps; - label?: string; } export interface WrappedFieldInputProps extends CommonFieldInputProps { diff --git a/types/redux-form/redux-form-tests.tsx b/types/redux-form/redux-form-tests.tsx index 06344b54c5..ea13a9618f 100644 --- a/types/redux-form/redux-form-tests.tsx +++ b/types/redux-form/redux-form-tests.tsx @@ -110,7 +110,6 @@ interface MyFieldCustomProps { type MyFieldProps = MyFieldCustomProps & WrappedFieldProps; const MyField: React.StatelessComponent = ({ children, - label, input, meta, foo diff --git a/types/req-cwd/index.d.ts b/types/req-cwd/index.d.ts new file mode 100644 index 0000000000..56ca4f0786 --- /dev/null +++ b/types/req-cwd/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for req-cwd 2.0 +// Project: https://github.com/sindresorhus/req-cwd +// Definitions by: Arturas Molcanovas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/** Like require(), throws when the module can't be found. */ +declare function reqCwd(moduleId: string): any; + +declare namespace reqCwd { + /** Returns null instead of throwing when the module can't be found. */ + function silent(moduleId: string): any; +} + +export = reqCwd; diff --git a/types/req-cwd/req-cwd-tests.ts b/types/req-cwd/req-cwd-tests.ts new file mode 100644 index 0000000000..df95f8161f --- /dev/null +++ b/types/req-cwd/req-cwd-tests.ts @@ -0,0 +1,9 @@ +import * as reqCwd from 'req-cwd'; + +const r1: string = reqCwd('./foo'); +const r2: number = reqCwd('./foo'); +const r3: {foo: string} = reqCwd('./foo'); + +const s1: string | null = reqCwd.silent('./foo'); +const s2: number | null = reqCwd.silent('./foo'); +const s3: {foo: string} | null = reqCwd.silent('./foo'); diff --git a/types/req-cwd/tsconfig.json b/types/req-cwd/tsconfig.json new file mode 100644 index 0000000000..648ca4cf75 --- /dev/null +++ b/types/req-cwd/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", + "req-cwd-tests.ts" + ] +} diff --git a/types/req-cwd/tslint.json b/types/req-cwd/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/req-cwd/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sane-email-validation/index.d.ts b/types/sane-email-validation/index.d.ts new file mode 100644 index 0000000000..92e285c1ca --- /dev/null +++ b/types/sane-email-validation/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for sane-email-validation 1.1 +// Project: https://github.com/scottgonzalez/sane-email-validation +// Definitions by: Forbes Lindesay +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function isEmail(email: string): boolean; + +declare namespace isEmail { + function isNotEmail(email: string): boolean; +} + +export = isEmail; diff --git a/types/sane-email-validation/sane-email-validation-tests.ts b/types/sane-email-validation/sane-email-validation-tests.ts new file mode 100644 index 0000000000..7b8ad88603 --- /dev/null +++ b/types/sane-email-validation/sane-email-validation-tests.ts @@ -0,0 +1,9 @@ +import isEmail = require('sane-email-validation'); + +const is: boolean = isEmail('foo@bar.com'); +const isNot: boolean = isEmail.isNotEmail('foo@bar.com'); + +// $ExpectError +isEmail(10); +// $ExpectError +isEmail.isNotEmail(10); diff --git a/types/sane-email-validation/tsconfig.json b/types/sane-email-validation/tsconfig.json new file mode 100644 index 0000000000..3b9b568d67 --- /dev/null +++ b/types/sane-email-validation/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "sane-email-validation-tests.ts" + ] +} diff --git a/types/sane-email-validation/tslint.json b/types/sane-email-validation/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sane-email-validation/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sanitize-html/index.d.ts b/types/sanitize-html/index.d.ts index bdd70f956a..2e7527e3fc 100644 --- a/types/sanitize-html/index.d.ts +++ b/types/sanitize-html/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for sanitize-html 1.14.1 +// Type definitions for sanitize-html 1.18.2 // Project: https://github.com/punkave/sanitize-html // Definitions by: Rogier Schouten // Afshin Darian // BehindTheMath +// Rinze de Laat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = sanitize; @@ -38,9 +39,12 @@ declare namespace sanitize { interface IOptions { allowedAttributes?: { [index: string]: string[] } | boolean; + allowedStyles?: { [index: string]: { [index: string]: RegExp[] } }; allowedClasses?: { [index: string]: string[] } | boolean; + allowedIframeHostnames?: string[]; allowedSchemes?: string[] | boolean; allowedSchemesByTag?: { [index: string]: string[] } | boolean; + allowedSchemesAppliedToAttributes?: string[]; allowProtocolRelative?: boolean; allowedTags?: string[] | boolean; exclusiveFilter?: (frame: IFrame) => boolean; diff --git a/types/sanitize-html/sanitize-html-tests.ts b/types/sanitize-html/sanitize-html-tests.ts index cc43d64fcb..b02a5a6653 100644 --- a/types/sanitize-html/sanitize-html-tests.ts +++ b/types/sanitize-html/sanitize-html-tests.ts @@ -4,8 +4,17 @@ let options: sanitize.IOptions = { allowedTags: sanitize.defaults.allowedTags.concat('h1', 'h2', 'img'), allowedAttributes: { 'a': sanitize.defaults.allowedAttributes['a'].concat('rel'), - 'img': ['src', 'height', 'width', 'alt'] + 'img': ['src', 'height', 'width', 'alt', 'style'] }, + allowedStyles: { + '*': { + color: [/^red$/], + background: [/^green$/], + 'background-color': [/^#0000FF$/] + } + }, + allowedIframeHostnames: ['www.youtube.com'], + allowedSchemesAppliedToAttributes: [ 'href', 'src', 'cite' ], transformTags: { 'a': sanitize.simpleTransform('a', { 'rel': 'nofollow' }), 'img': (tagName: string, attribs: sanitize.Attributes) => { diff --git a/types/sat/index.d.ts b/types/sat/index.d.ts index 538228049c..901c0814f2 100644 --- a/types/sat/index.d.ts +++ b/types/sat/index.d.ts @@ -59,10 +59,10 @@ declare namespace SAT { setPoints(points: Vector[]): Polygon; setAngle(angle: number): Polygon; setOffset(offset: Vector): Polygon; - recalc(): Polygon; rotate(angle: number): Polygon; translate(x: number, y: number): Polygon; getAABB(): Polygon; + getCentroid(): Vector; } export class Box { diff --git a/types/select2/v3/index.d.ts b/types/select2/v3/index.d.ts index 21bb2611c7..771d997384 100644 --- a/types/select2/v3/index.d.ts +++ b/types/select2/v3/index.d.ts @@ -75,6 +75,7 @@ interface Select2Options { dropdownCss?: any; dropdownCssClass?: any; escapeMarkup?: (markup: string) => string; + nextSearchTerm?: (selectedObject: object, currentSearchTerm: string) => string; } interface Select2JQueryEventObject extends JQueryEventObject { diff --git a/types/select2/v3/select2-tests.ts b/types/select2/v3/select2-tests.ts index 3b331cec3b..2d5a400352 100644 --- a/types/select2/v3/select2-tests.ts +++ b/types/select2/v3/select2-tests.ts @@ -210,6 +210,9 @@ $("#e17_2").select2({ }); $("#e18,#e18_2").select2(); alert("Selected value is: " + $("#e8").select2("val")); $("#e8").select2("val", { id: "CA", text: "Califoria" }); +$("#e19").select2({nextSearchTerm: function(selectedObject: object, currentSearchTerm: string) { + return currentSearchTerm; +}}); $("#e8").select2("val"); $("#e8").select2("val", "CA"); diff --git a/types/simple-oauth2/index.d.ts b/types/simple-oauth2/index.d.ts index 21718c0722..19a1ff2698 100644 --- a/types/simple-oauth2/index.d.ts +++ b/types/simple-oauth2/index.d.ts @@ -1,11 +1,10 @@ -// Type definitions for simple-oauth2 1.1 +// Type definitions for simple-oauth2 2.2 // Project: https://github.com/lelylan/simple-oauth2 // Definitions by: Michael Müller , // Troy Lamerton +// Martín Rodriguez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -import Bluebird = require("bluebird"); +// TypeScript Version: 2.9 /** Creates a new simple-oauth2 client with the passed configuration */ export function create(options: ModuleOptions): OAuthClient; @@ -33,13 +32,21 @@ export interface ModuleOptions { /** String path to request an authorization code. Default to /oauth/authorize. */ authorizePath?: string }; - /** optional object used to set global options to the internal http library (request-js). */ + /** + * Used to set global options to the internal http library (wreck). + * All options except baseUrl are allowed + * Defaults to header.Accept = "application/json" + */ http?: {}; options?: { - /** Whether or not the client.id/client.secret params are sent in the request body. Defaults to true. */ - useBodyAuth?: boolean, - /** Whether or not the Basic Authorization header should be sent at the token request. */ - useBasicAuthorizationHeader?: boolean + /** Format of data sent in the request body. Defaults to form. */ + bodyFormat?: "json" | "form", + /** + * Indicates the method used to send the client.id/client.secret authorization params at the token request. + * If set to body, the bodyFormat option will be used to format the credentials. + * Defaults to header + */ + authorizationMethod?: "header" | "body" }; } @@ -55,17 +62,19 @@ export interface AccessToken { /** Check if the access token is expired or not */ expired(): boolean; /** Refresh the access token */ - refresh(params: {}, callback: (error: any, result: AccessToken) => void): Bluebird; - refresh(callback?: (error: any, result: AccessToken) => void): Bluebird; + refresh(params?: {}): Promise; /** Revoke access or refresh token */ - revoke(tokenType: TokenType, callback?: (error: any) => void): Bluebird; + revoke(tokenType: TokenType): Promise; + /** Revoke both the existing access and refresh tokens */ + revokeAll(): Promise; } export type AuthorizationCode = string; export interface AuthorizationTokenConfig { + /** Authorization code (from previous step) */ code: AuthorizationCode; + /** A string that represents the callback uri */ redirect_uri: string; - scope?: string | string[]; } export interface PasswordTokenConfig { @@ -88,27 +97,32 @@ export interface OAuthClient { * Redirect the user to the autorization page * @return the absolute authorization url */ - authorizeURL(params?: { - /** A string that represents the registered application URI where the user is redirected after authentication */ - redirect_uri?: string, - /** A string or array of strings that represents the application privileges */ - scope?: string | string[], - /** A string that represents an option opaque value used by the client to main the state between the request and the callback */ - state?: string - }): string, + authorizeURL( + params?: { + /** A key-value pair where key is ModuleOptions#client.idParamName and the value represents the Client-ID */ + [ idParamName: string ]: string | undefined + } & { + /** A string that represents the registered application URI where the user is redirected after authentication */ + redirect_uri?: string, + /** A string or array of strings that represents the application privileges */ + scope?: string | string[], + /** A string that represents an option opaque value used by the client to main the state between the request and the callback */ + state?: string + } + ): string, /** Returns the Access Token object */ - getToken(params: AuthorizationTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + getToken(params: AuthorizationTokenConfig): Promise; }; ownerPassword: { /** Returns the Access Token Object */ - getToken(params: PasswordTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + getToken(params: PasswordTokenConfig): Promise; }; clientCredentials: { /** Returns the Access Token Object */ - getToken(params: ClientCredentialTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + getToken(params: ClientCredentialTokenConfig): Promise; }; accessToken: { diff --git a/types/simple-oauth2/simple-oauth2-tests.ts b/types/simple-oauth2/simple-oauth2-tests.ts index f83a616681..e066ad41c0 100644 --- a/types/simple-oauth2/simple-oauth2-tests.ts +++ b/types/simple-oauth2/simple-oauth2-tests.ts @@ -1,8 +1,11 @@ // off https://github.com/lelylan/simple-oauth2/blob/master/README.md // slightly changed to remove external dependencies +// Initialize the OAuth2 Library +import * as oauth2lib from "simple-oauth2"; + // Set the configuration settings -const credentials = { +const credentials: oauth2lib.ModuleOptions = { client: { id: '', secret: '' @@ -12,13 +15,10 @@ const credentials = { } }; -// Initialize the OAuth2 Library -// const oauth2 = require('simple-oauth2').create(credentials); -import oauth2lib = require("simple-oauth2"); const oauth2 = oauth2lib.create(credentials); // #Authorization Code flow -(() => { +(async () => { // Authorization oauth2 URI const authorizationUri = oauth2.authorizationCode.authorizeURL({ redirect_uri: 'http://localhost:3000/callback', @@ -36,57 +36,47 @@ const oauth2 = oauth2lib.create(credentials); scope: ['', ''] }; - // Callbacks // Save the access token - oauth2.authorizationCode.getToken(tokenConfig, (error, result) => { - if (error) { - console.log('Access Token Error', error.message); - return; - } + try { + const result = await oauth2.authorizationCode.getToken(tokenConfig); + const accessToken = oauth2.accessToken.create(result); + } catch (error) { + console.log('Access Token Error', error.message); + } +})(); - const token = oauth2.accessToken.create(result); - }); +// #Password Credentials Flow +(async () => { + const tokenConfig = { + username: 'username', + password: 'password', + scope: [ '', '' ], + }; - // Promises // Save the access token - oauth2.authorizationCode.getToken(tokenConfig) - .then((result) => { - const token = oauth2.accessToken.create(result); - }) - .catch((error) => { - console.log('Access Token Error', error.message); - }); + try { + const result = await oauth2.ownerPassword.getToken(tokenConfig); + const accessToken = oauth2.accessToken.create(result); + } catch (error) { + console.log('Access Token Error', error.message); + } })(); // #Client Credentials Flow -(() => { +(async () => { const tokenConfig = {}; - // Callbacks // Get the access token object for the client - oauth2.clientCredentials.getToken(tokenConfig, (error, result) => { - if (error) { - console.log('Access Token Error', error.message); - return; - } - - const token = oauth2.accessToken.create(result); - }); - - // Promises - // Get the access token object for the client - oauth2.clientCredentials - .getToken(tokenConfig) - .then((result) => { - const token = oauth2.accessToken.create(result); - }) - .catch((error) => { - console.log('Access Token error', error.message); - }); + try { + const result = await oauth2.clientCredentials.getToken(tokenConfig); + const accessToken = oauth2.accessToken.create(result); + } catch (error) { + console.log('Access Token error', error.message); + } })(); // #Access Token object -(() => { +(async () => { // Sample of a JSON access token (you got it through previous steps) const tokenObject = { access_token: '', @@ -95,62 +85,46 @@ const oauth2 = oauth2lib.create(credentials); }; // Create the access token wrapper - let token = oauth2.accessToken.create(tokenObject); + let accessToken = oauth2.accessToken.create(tokenObject); // Check if the token is expired. If expired it is refreshed. - if (token.expired()) { - // Callbacks - token.refresh((error, result) => { - token = result; - }); - - // Promises - token.refresh() - .then((result) => { - token = result; - }); + if (accessToken.expired()) { + try { + accessToken = await accessToken.refresh(); + } catch (error) { + console.log('Error refreshing access token: ', error.message); + } } - // Callbacks - // Revoke only the access token - token.revoke('access_token', (error) => { + // Revoke both access and refresh tokens + try { + // Revoke only the access token + await accessToken.revoke('access_token'); + // Session ended. But the refresh_token is still valid. + // Revoke the refresh token + await accessToken.revoke('refresh_token'); - // Revoke the refresh_token - token.revoke('refresh_token', (error) => { - console.log('token revoked.'); - }); - }); + console.log('Token revoked'); + } catch (error) { + console.log('Error revoking token: ', error.message); + } - // Promises - // Revoke only the access token - token.revoke('access_token') - .then(() => { - // Revoke the refresh token - return token.revoke('refresh_token'); - }) - .then(() => { - console.log('Token revoked'); - }) - .catch((error) => { - console.log('Error revoking token.', error.message); - }); + // or... + + try { + // Revokes both tokens, refresh token is only revoked if the access_token is properly revoked + await accessToken.revokeAll(); + } catch (error) { + console.log('Error revoking token: ', error.message); + } })(); // #Errors // not applicable, as those errors about missing authentication codes are already found by the typescript compiler // (function () { -// // Callbacks -// oauth2.authorizationCode.getToken({}, (error, token) => { -// if (error) { -// return console.log(error.message); -// } -// }); - -// // Promises -// oauth2.authorizationCode -// .getToken({}) +// oauth2.authorizationCode.getToken({}) // .catch((error) => { // console.log(error.message); // }); diff --git a/types/simple-oauth2/v1/index.d.ts b/types/simple-oauth2/v1/index.d.ts new file mode 100644 index 0000000000..30b1a72d98 --- /dev/null +++ b/types/simple-oauth2/v1/index.d.ts @@ -0,0 +1,133 @@ +// Type definitions for simple-oauth2 1.6 +// Project: https://github.com/lelylan/simple-oauth2 +// Definitions by: Michael Müller , +// Troy Lamerton +// Martín Rodriguez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +import Bluebird = require("bluebird"); + +/** Creates a new simple-oauth2 client with the passed configuration */ +export function create(options: ModuleOptions): OAuthClient; + +export interface ModuleOptions { + client: { + /** Service registered client id. Required. */ + id: string, + /** Service registered client secret. Required. */ + secret: string, + /** Parameter name used to send the client secret. Default to client_secret. */ + secretParamName?: string, + /** Parameter name used to send the client id. Default to client_id. */ + idParamName?: string + }; + auth: { + /** String used to set the host to request the tokens to. Required. */ + tokenHost: string, + /** String path to request an access token. Default to /oauth/token. */ + tokenPath?: string, + /** String path to revoke an access token. Default to /oauth/revoke. */ + revokePath?: string, + /** String used to set the host to request an "authorization code". Default to the value set on auth.tokenHost. */ + authorizeHost?: string, + /** String path to request an authorization code. Default to /oauth/authorize. */ + authorizePath?: string + }; + /** + * Used to set global options to the internal http library (wreck). + * All options except baseUrl are allowed + * Defaults to header.Accept = "application/json" + */ + http?: {}; + options?: { + /** Format of data sent in the request body. Defaults to form. */ + bodyFormat?: "json" | "form", + /** + * Indicates the method used to send the client.id/client.secret authorization params at the token request. + * If set to body, the bodyFormat option will be used to format the credentials. + * Defaults to header. + */ + authorizationMethod?: "header" | "body" + }; +} + +export type TokenType = "access_token" | "refresh_token"; + +export interface Token { + [x: string]: any; +} + +export interface AccessToken { + token: Token; + + /** Check if the access token is expired or not */ + expired(): boolean; + /** Refresh the access token */ + refresh(params: {}, callback: (error: any, result: AccessToken) => void): Bluebird; + refresh(callback?: (error: any, result: AccessToken) => void): Bluebird; + /** Revoke access or refresh token */ + revoke(tokenType: TokenType, callback?: (error: any) => void): Bluebird; +} + +export type AuthorizationCode = string; +export interface AuthorizationTokenConfig { + /** Authorization code (from previous step) */ + code: AuthorizationCode; + /** A string that represents the callback uri */ + redirect_uri: string; +} + +export interface PasswordTokenConfig { + /** A string that represents the registered username */ + username: string; + /** A string that represents the registered password. */ + password: string; + /** A string or array of strings that represents the application privileges */ + scope: string | string[]; +} + +export interface ClientCredentialTokenConfig { + /** A string that represents the application privileges */ + scope?: string | string[]; +} + +export interface OAuthClient { + authorizationCode: { + /** + * Redirect the user to the autorization page + * @return the absolute authorization url + */ + authorizeURL( + params?: { + /** A key-value pair where key is ModuleOptions#client.idParamName and the value represents the Client-ID */ + [ idParamName: string ]: string | undefined + } & { + /** A string that represents the registered application URI where the user is redirected after authentication */ + redirect_uri?: string, + /** A string or array of strings that represents the application privileges */ + scope?: string | string[], + /** A string that represents an option opaque value used by the client to main the state between the request and the callback */ + state?: string + } + ): string, + + /** Returns the Access Token object */ + getToken(params: AuthorizationTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + }; + + ownerPassword: { + /** Returns the Access Token Object */ + getToken(params: PasswordTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + }; + + clientCredentials: { + /** Returns the Access Token Object */ + getToken(params: ClientCredentialTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + }; + + accessToken: { + /** Creates an OAuth2.AccessToken instance */ + create(tokenToUse: Token): AccessToken; + }; +} diff --git a/types/simple-oauth2/v1/simple-oauth2-tests.ts b/types/simple-oauth2/v1/simple-oauth2-tests.ts new file mode 100644 index 0000000000..b3a8b2f952 --- /dev/null +++ b/types/simple-oauth2/v1/simple-oauth2-tests.ts @@ -0,0 +1,188 @@ +// off https://github.com/lelylan/simple-oauth2/blob/master/README.md +// slightly changed to remove external dependencies + +// Initialize the OAuth2 Library +import * as oauth2lib from "simple-oauth2"; + +// Set the configuration settings +const credentials: oauth2lib.ModuleOptions = { + client: { + id: '', + secret: '' + }, + auth: { + tokenHost: 'https://api.oauth.com' + } +}; + +const oauth2 = oauth2lib.create(credentials); + +// #Authorization Code flow +(() => { + // Authorization oauth2 URI + const authorizationUri = oauth2.authorizationCode.authorizeURL({ + redirect_uri: 'http://localhost:3000/callback', + scope: '', + state: '' + }); + + // Redirect example using Express (see http://expressjs.com/api.html#res.redirect) + // res.redirect(authorizationUri); + + // Get the access token object (the authorization code is given from the previous step). + const tokenConfig = { + code: '', + redirect_uri: 'http://localhost:3000/callback', + scope: ['', ''] + }; + + // Callbacks + // Save the access token + oauth2.authorizationCode.getToken(tokenConfig, (error, result) => { + if (error) { + console.log('Access Token Error', error.message); + return; + } + + const token = oauth2.accessToken.create(result); + }); + + // Promises + // Save the access token + oauth2.authorizationCode.getToken(tokenConfig) + .then((result) => { + const token = oauth2.accessToken.create(result); + }) + .catch((error) => { + console.log('Access Token Error', error.message); + }); +})(); + +// #Password Credentials Flow +(() => { + const tokenConfig = { + username: 'username', + password: 'password', + scope: [ '', '' ], + }; + + // Callbacks + // Save the access token + oauth2.ownerPassword.getToken(tokenConfig, (error, result) => { + if (error) { + console.log('Access Token Error', error.message); + return; + } + + const token = oauth2.accessToken.create(result); + }); + + // Promises + // Save the access token + oauth2.ownerPassword.getToken(tokenConfig) + .then((result) => { + const token = oauth2.accessToken.create(result); + }) + .catch((error) => { + console.log('Access Token Error', error.message); + }); +})(); + +// #Client Credentials Flow +(() => { + const tokenConfig = {}; + + // Callbacks + // Get the access token object for the client + oauth2.clientCredentials.getToken(tokenConfig, (error, result) => { + if (error) { + console.log('Access Token Error', error.message); + return; + } + + const token = oauth2.accessToken.create(result); + }); + + // Promises + // Get the access token object for the client + oauth2.clientCredentials.getToken(tokenConfig) + .then((result) => { + const token = oauth2.accessToken.create(result); + }) + .catch((error) => { + console.log('Access Token error', error.message); + }); +})(); + +// #Access Token object +(() => { + // Sample of a JSON access token (you got it through previous steps) + const tokenObject = { + access_token: '', + refresh_token: '', + expires_in: '7200' + }; + + // Create the access token wrapper + let accessToken = oauth2.accessToken.create(tokenObject); + + // Check if the token is expired. If expired it is refreshed. + if (accessToken.expired()) { + // Callbacks + accessToken.refresh((error, result) => { + accessToken = result; + }); + + // Promises + accessToken.refresh() + .then((result) => { + accessToken = result; + }); + } + + // Callbacks + // Revoke only the access token + accessToken.revoke('access_token', (error) => { + // Session ended. But the refresh_token is still valid. + + // Revoke the refresh_token + accessToken.revoke('refresh_token', (error) => { + console.log('token revoked.'); + }); + }); + + // Promises + // Revoke only the access token + accessToken.revoke('access_token') + .then(() => { + // Revoke the refresh token + return accessToken.revoke('refresh_token'); + }) + .then(() => { + console.log('Token revoked'); + }) + .catch((error) => { + console.log('Error revoking token.', error.message); + }); +})(); + +// #Errors +// not applicable, as those errors about missing authentication codes are already found by the typescript compiler + +// (function () { +// // Callbacks +// oauth2.authorizationCode.getToken({}, (error, token) => { +// if (error) { +// return console.log(error.message); +// } +// }); + +// // Promises +// oauth2.authorizationCode +// .getToken({}) +// .catch((error) => { +// console.log(error.message); +// }); + +// // => { "status": "401", "message": "Unauthorized" } +// })(); diff --git a/types/simple-oauth2/v1/tsconfig.json b/types/simple-oauth2/v1/tsconfig.json new file mode 100644 index 0000000000..f19c003707 --- /dev/null +++ b/types/simple-oauth2/v1/tsconfig.json @@ -0,0 +1,32 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "simple-oauth2": [ + "simple-oauth2/v1" + ], + "simple-oauth2/*": [ + "simple-oauth2/v1/*" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "simple-oauth2-tests.ts" + ] +} diff --git a/types/simple-oauth2/v1/tslint.json b/types/simple-oauth2/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/simple-oauth2/v1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/slack-mock/index.d.ts b/types/slack-mock/index.d.ts new file mode 100644 index 0000000000..2289e554b4 --- /dev/null +++ b/types/slack-mock/index.d.ts @@ -0,0 +1,200 @@ +// Type definitions for slack-mock 1.1 +// Project: https://github.com/Skellington-Closet/slack-mock +// Definitions by: Kris Kalavantavanich +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { IncomingHttpHeaders } from "http"; +import * as nock from "nock"; +import { Url } from "url"; +import * as WebSocket from "ws"; + +export = SlackMock; + +declare function SlackMock(config?: SlackMock.ConfigOptions): SlackMock.Instance; + +declare namespace SlackMock { + let instance: Instance; + + interface Instance { + events: Events; + incomingWebhooks: IncomingWebhooks; + interactiveButtons: InteractiveButtons; + outgoingWebhooks: OutgoingWebhooks; + rtm: Rtm; + slashCommands: SlashCommands; + web: Web; + + reset: () => void; + } + + interface ConfigOptions { + rtmPort?: number; + logLevel?: string; + } + + // Events + + type EventUrl = string | Url; + type EventHttpHeaders = IncomingHttpHeaders; + + interface Events { + send: (targetUrl: EventUrl, body: T) => Promise; + reset: () => void; + calls: Array>; + } + + interface EventCall { + url: EventUrl; + params: T; + headers: EventHttpHeaders; + statusCode: number; + } + + // Incoming Webhooks + + type IncomingWebhookUrl = string; + type IncomingWebhookHttpHeaders = nock.HttpHeaders; + + interface IncomingWebhooks { + addResponse: (opts: IncomingWebhookOptions) => void; + reset: () => void; + calls: Array>; + } + + interface IncomingWebhookOptions { + url?: IncomingWebhookUrl; + statusCode ?: number; + body ?: T; + headers ?: IncomingWebhookHttpHeaders; + } + + interface IncomingWebhookCall { + url: IncomingWebhookUrl; + params: T; + headers: IncomingWebhookHttpHeaders; + } + + // Interactive Buttons + + type InteractiveButtonUrl = string | Url; + type InteractiveButtonHttpHeaders = nock.HttpHeaders; + + interface InteractiveButtons { + send: (targetUrl: InteractiveButtonUrl, body: T) => Promise; + addResponse: (opts: InteractiveButtonOptions) => void; + reset: () => void; + calls: Array>; + } + + interface InteractiveButtonOptions { + url?: InteractiveButtonUrl; + statusCode ?: number; + body ?: T; + headers ?: InteractiveButtonHttpHeaders; + } + + interface InteractiveButtonCall { + url: InteractiveButtonUrl; + params: T; + headers: InteractiveButtonHttpHeaders; + statusCode: number; + type: InteractiveButtonCallType; + } + + enum InteractiveButtonCallType { + response = 'response', + response_url = 'response_url' + } + + // Outgoing Webhooks + + type OutgoingWebhookUrl = string | Url; + type OutgoingWebhookHttpHeaders = IncomingHttpHeaders; + + interface OutgoingWebhooks { + send: (targetUrl: OutgoingWebhookUrl, body: T) => Promise; + reset: () => void; + calls: Array>; + } + + interface OutgoingWebhookCall { + url: OutgoingWebhookUrl; + params: T; + headers: OutgoingWebhookHttpHeaders; + statusCode: number; + } + + // RTM + + interface Rtm { + clients: WebSocket[]; + send: (token: string, message: T) => Promise; + reset: () => void; + calls: Array>; + startServer: (token: string) => void; + stopServer: (token: string) => void; + } + + interface RtmCall { + message: T; + token: string; + rawMessage: WebSocket.Data; + } + + // Slash Commands + + type SlashCommandUrl = string | Url; + type SlashCommandHttpHeaders = IncomingHttpHeaders; + + interface SlashCommands { + send: (targetUrl: SlashCommandUrl, body: T) => Promise; + addResponse: (opts: SlashCommandOptions) => void; + reset: () => void; + calls: Array>; + } + + interface SlashCommandOptions { + url?: SlashCommandUrl; + statusCode ?: number; + body ?: T; + headers ?: SlashCommandHttpHeaders; + } + + interface SlashCommandCall { + url: SlashCommandUrl; + params: T; + headers: SlashCommandHttpHeaders; + statusCode: number; + type: SlashCommandCallType; + } + + enum SlashCommandCallType { + response = 'response', + response_url = 'response_url' + } + + // Web + + type WebUrl = string; + type WebHttpHeaders = nock.HttpHeaders; + + interface Web { + addResponse: (opts: WebOptions) => void; + reset: () => void; + calls: Array>; + } + + interface WebOptions { + url?: WebUrl; + statusCode ?: number; + body ?: T; + headers ?: WebHttpHeaders; + } + + interface WebCall { + url: WebUrl; + params: T; + headers: WebHttpHeaders; + } +} diff --git a/types/slack-mock/slack-mock-tests.ts b/types/slack-mock/slack-mock-tests.ts new file mode 100644 index 0000000000..5b5dabb9c1 --- /dev/null +++ b/types/slack-mock/slack-mock-tests.ts @@ -0,0 +1,103 @@ +import SlackMock = require("slack-mock"); + +// Initialization + +const slackMock = SlackMock.instance; +SlackMock({ + logLevel: "error", + rtmPort: 9090 +}); +SlackMock(); + +// Events +const eventPayload = { }; +slackMock.events.send('http://localhost:9000/event', eventPayload) + .then(() => { + slackMock.events.calls.length; + slackMock.events.calls[0].statusCode; + slackMock.events.calls[0].headers; + slackMock.events.calls[0].params; + slackMock.events.calls[0].url; + }); + +slackMock.events.reset(); + +// Incoming Webhooks +slackMock.incomingWebhooks.calls.length; +slackMock.incomingWebhooks.calls[0].params.text; + +// Interactive Buttons +slackMock.interactiveButtons.addResponse({ + statusCode: 201 +}); + +const interactiveButtonPayload = {text: 'abc'}; +slackMock.interactiveButtons.send('http://localhost:9000/button', interactiveButtonPayload) + .then(() => { + slackMock.interactiveButtons.calls.length; + slackMock.interactiveButtons.calls[0].params.text; + }); + +// Outgoing Webhooks +const outgoingWebhookPayload = {text: 'abc'}; +slackMock.outgoingWebhooks.send('http://localhost:9000/outgoing', outgoingWebhookPayload) + .then(() => { + slackMock.outgoingWebhooks.calls.length; + slackMock.outgoingWebhooks.calls[0].params.text; + }); + +// RTM +slackMock.rtm.send('1234', { + type: 'message', + channel: 'mockChannel', + user: 'usr', + text: 'hello'}) + .then(() => { + slackMock.rtm.calls.length; + slackMock.rtm.calls[0].message.text; + }); +slackMock.rtm.startServer('1234'); +slackMock.rtm.stopServer('1234'); + +// Slash Commands +const slashCommandPayload = { }; +slackMock.slashCommands.send('http://localhost:9000/slash', slashCommandPayload) + .then(() => { + slackMock.slashCommands.calls.length; + slackMock.slashCommands.calls[0].params.text; + slackMock.slashCommands.calls[0].params.response_type; + }); + +// Web (OAuth Example) + +const botToken = 'xoxb-XXXXXXXXXXXX-TTTTTTTTTTTTTT'; +slackMock.web.addResponse({ + url: 'https://slack.com/api/oauth.access', + statusCode: 200, + body: { + access_token: 'xoxp-XXXXXXXX-XXXXXXXX-XXXXX', + scope: 'incoming-webhook,commands,bot', + team_name: 'mockTeam', + team_id: 'Tmock', + bot: { + bot_user_id: 'Bmock', + bot_access_token: botToken + } + } +}); + +slackMock.web.addResponse({ + url: 'https://slack.com/api/rtm.start', + statusCode: 200, + body: { + ok: true, + self: { + name: 'mockSelf', + id: 'Bmock' + }, + team: { + name: 'mockTeam', + id: 'Tmock' + } + } +}); diff --git a/types/slack-mock/tsconfig.json b/types/slack-mock/tsconfig.json new file mode 100644 index 0000000000..e012cc79b1 --- /dev/null +++ b/types/slack-mock/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", + "slack-mock-tests.ts" + ] +} \ No newline at end of file diff --git a/types/slack-mock/tslint.json b/types/slack-mock/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/slack-mock/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/spectrum/index.d.ts b/types/spectrum/index.d.ts index bc94644a92..86b3077c04 100644 --- a/types/spectrum/index.d.ts +++ b/types/spectrum/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for spectrum 1.5.1 // Project: https://github.com/bgrins/spectrum/ // Definitions by: Mordechai Zuber +// Junyoung Clare Jang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -30,7 +31,7 @@ interface JQuery { /** * Gets the current value from the colorpicker. */ - spectrum(methodName: "get"): tinycolorInstance; + spectrum(methodName: "get"): tinycolor.Instance; /** * Sets the colorpickers value to update the original input. @@ -101,12 +102,12 @@ interface JQuery { /** * Called at the beginning of a drag event on either hue slider, alpha slider, or main color picker areas. */ - on(events: "dragstart.spectrum", handler: (eventObject: JQueryEventObject, color: tinycolorInstance) => any): JQuery; + on(events: "dragstart.spectrum", handler: (eventObject: JQueryEventObject, color: tinycolor.Instance) => any): JQuery; /** * Called at the end of a drag event on either hue slider, alpha slider, or main color picker areas. */ - on(events: "dragstop.spectrum", handler: (eventObject: JQueryEventObject, color: tinycolorInstance) => any): JQuery; + on(events: "dragstop.spectrum", handler: (eventObject: JQueryEventObject, color: tinycolor.Instance) => any): JQuery; } declare namespace Spectrum { @@ -263,18 +264,18 @@ declare namespace Spectrum { /** * Called as the original input changes. Only happens when the input is closed or the 'Choose' button is clicked. */ - change?: (color: tinycolorInstance) => void; + change?: (color: tinycolor.Instance) => void; /** * Called as the user moves around within the colorpicker. */ - move?: (color: tinycolorInstance) => void; + move?: (color: tinycolor.Instance) => void; /** * Called after the colorpicker is opened. This is ignored on a flat colorpicker. * Note, when any colorpicker on the page is shown it will hide any that are already open. */ - show?: (color: tinycolorInstance) => void; + show?: (color: tinycolor.Instance) => void; /** * Called after the colorpicker is hidden. @@ -282,12 +283,12 @@ declare namespace Spectrum { * Note, when any colorpicker on the page is shown it will hide any that are already open. * This event is ignored on a flat colorpicker. */ - hide?: (color: tinycolorInstance) => void; + hide?: (color: tinycolor.Instance) => void; /** * You can prevent the colorpicker from showing up if you return false in the beforeShow event. * This event is ignored on a flat colorpicker. */ - beforeShow?: (color: tinycolorInstance) => void; + beforeShow?: (color: tinycolor.Instance) => void; } } diff --git a/types/stylelint/index.d.ts b/types/stylelint/index.d.ts index 67316843a9..2068aff709 100644 --- a/types/stylelint/index.d.ts +++ b/types/stylelint/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for stylelint 7.11 +// Type definitions for stylelint 9.4 // Project: https://github.com/stylelint/stylelint // Definitions by: Alan Agius // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export type FormatterType = "json" | "string" | "verbose"; +export type FormatterType = "json" | "string" | "verbose" | "compact"; export type SyntaxType = "scss" | "sass" | "less" | "sugarss"; @@ -45,6 +45,7 @@ export interface LintResult { export namespace formatters { function json(results: LintResult[]): string; function string(results: LintResult[]): string; + function compact(results: LintResult[]): string; function verbose(results: LintResult[]): string; } diff --git a/types/stylelint/tslint.json b/types/stylelint/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/stylelint/tslint.json +++ b/types/stylelint/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/stylelint/v7/index.d.ts b/types/stylelint/v7/index.d.ts new file mode 100644 index 0000000000..67316843a9 --- /dev/null +++ b/types/stylelint/v7/index.d.ts @@ -0,0 +1,51 @@ +// Type definitions for stylelint 7.11 +// Project: https://github.com/stylelint/stylelint +// Definitions by: Alan Agius +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type FormatterType = "json" | "string" | "verbose"; + +export type SyntaxType = "scss" | "sass" | "less" | "sugarss"; + +export interface LinterOptions { + code?: string; + codeFilename?: string; + config?: JSON; + configBasedir?: string; + configFile?: string; + configOverrides?: JSON; + cache?: boolean; + cacheLocation?: string; + files?: string | string[]; + fix?: boolean; + formatter?: FormatterType; + ignoreDisables?: boolean; + reportNeedlessDisables?: boolean; + ignorePath?: boolean; + syntax?: SyntaxType; + customSyntax?: string; +} + +export interface LinterResult { + errored: boolean; + output: string; + postcssResults: any[]; + results: LintResult[]; +} + +export interface LintResult { + source: string; + errored: boolean | undefined; + ignored: boolean | undefined; + warnings: string[]; + deprecations: string[]; + invalidOptionWarnings: any[]; +} + +export namespace formatters { + function json(results: LintResult[]): string; + function string(results: LintResult[]): string; + function verbose(results: LintResult[]): string; +} + +export function lint(options?: LinterOptions): Promise; diff --git a/types/stylelint/v7/stylelint-tests.ts b/types/stylelint/v7/stylelint-tests.ts new file mode 100644 index 0000000000..785eb2e425 --- /dev/null +++ b/types/stylelint/v7/stylelint-tests.ts @@ -0,0 +1,24 @@ +import { LinterOptions, FormatterType, SyntaxType, lint, LintResult, LinterResult } from "stylelint"; + +const options: LinterOptions = { + code: "div { color: red }", + files: ["**/**.scss"], + formatter: "json", + cache: true, + cacheLocation: "./stylelint.cache.json", + ignoreDisables: true, + reportNeedlessDisables: true, + ignorePath: true, + syntax: "scss" +}; + +lint(options).then((x: LinterResult) => { + const err: boolean = x.errored; + const output: string = x.output; + const postcssResults: any[] = x.postcssResults; + const results: LintResult[] = x.results; +}); + +const formatter: FormatterType = "json"; + +const syntax: SyntaxType = "scss"; diff --git a/types/stylelint/v7/tsconfig.json b/types/stylelint/v7/tsconfig.json new file mode 100644 index 0000000000..b6f6796252 --- /dev/null +++ b/types/stylelint/v7/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "stylelint": [ + "stylelint/v7" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "stylelint-tests.ts" + ] +} diff --git a/types/stylelint/v7/tslint.json b/types/stylelint/v7/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/stylelint/v7/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/thepiratebay/index.d.ts b/types/thepiratebay/index.d.ts new file mode 100644 index 0000000000..20a1cc8945 --- /dev/null +++ b/types/thepiratebay/index.d.ts @@ -0,0 +1,69 @@ +// Type definitions for thepiratebay 1.4 +// Project: http://github.com/t3chnoboy/thepiratebay +// Definitions by: Jack Sorrell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function search(query?: string, options?: SearchOptions): Promise; +export function getTorrent(id: string | number | { link: string; [propName: string]: any; }): Promise; +export function getComments(id: string | number): Promise; +export function topTorrents(category?: number): Promise; +export function recentTorrents(): Promise; +export function userTorrents(user: string, options?: SearchOptions): Promise; +export function getTvShow(id: string | number): Promise; +export function getCategories(): Promise; + +export interface SearchOptions { + category?: string | number; + filter?: { verified?: boolean }; + page?: number; + orderBy?: string; + sortBy?: string; +} + +export interface Category { + id: string; + name: string; +} + +export interface CategoryGroup extends Category { + subcategories: Category[]; +} + +export interface Torrent { + id: string; + name: string; + size: string; + link: string; + seeders: string; + leechers: string; + uploadDate: string; + magnetLink: string; + uploader: string; + uploaderLink: string; +} + +export interface TorrentDetails extends Torrent { + description: string; +} + +export interface TorrentSearchResult extends Torrent { + category: Category; + subcategory: Category; + verified: boolean; +} + +export interface Comment { + user: string; + comment: string; +} + +export interface TVTorrent { + id: string; + title: string; + link: string; +} + +export interface TVSeason { + title: string; + torrents: TVTorrent[]; +} diff --git a/types/thepiratebay/thepiratebay-tests.ts b/types/thepiratebay/thepiratebay-tests.ts new file mode 100644 index 0000000000..76c56eb269 --- /dev/null +++ b/types/thepiratebay/thepiratebay-tests.ts @@ -0,0 +1,104 @@ +import * as PirateBay from 'thepiratebay'; + +// $ExpectType Promise +const searchResultPromise = PirateBay.search('Game of Thrones', { + category: 'all', + filter: { + verified: false + }, + page: 0, + orderBy: 'leeches', + sortBy: 'desc' +}); +searchResultPromise.then((res: PirateBay.TorrentSearchResult[]) => { + res[0].id; // $ExpectType string + res[0].name; // $ExpectType string + res[0].size; // $ExpectType string + res[0].link; // $ExpectType string + res[0].seeders; // $ExpectType string + res[0].leechers; // $ExpectType string + res[0].uploadDate; // $ExpectType string + res[0].magnetLink; // $ExpectType string + res[0].uploader; // $ExpectType string + res[0].uploaderLink; // $ExpectType string + + const category = res[0].category; // $ExpectType Category + category.id; // $ExpectType string + category.name; // $ExpectType string + + res[0].subcategory; // $ExpectType Category + res[0].verified; // $ExpectType boolean +}); +// $ExpectError +PirateBay.search(15); + +// $ExpectType Promise +const torrentPromise = PirateBay.getTorrent('15496322'); +torrentPromise.then((torrent: PirateBay.TorrentDetails) => { + torrent.id; // $ExpectType string + torrent.name; // $ExpectType string + torrent.size; // $ExpectType string + torrent.link; // $ExpectType string + torrent.seeders; // $ExpectType string + torrent.leechers; // $ExpectType string + torrent.uploadDate; // $ExpectType string + torrent.magnetLink; // $ExpectType string + torrent.uploader; // $ExpectType string + torrent.uploaderLink; // $ExpectType string + torrent.description; // $ExpectType string +}); +// $ExpectType Promise +PirateBay.getTorrent(15496322); +// $ExpectError +PirateBay.getTorrent(false); +// $ExpectType Promise +PirateBay.getTorrent('https://thepiratebay.org/torrent/15496322/Ubuntu_16.04.1_LTS_Desktop_64-bit'); +// $ExpectType Promise +PirateBay.getTorrent({ name: "ubuntu", link: 'https://thepiratebay.org/torrent/15496322/Ubuntu_16.04.1_LTS_Desktop_64-bit' }); + +// $ExpectType Promise +PirateBay.topTorrents(); +// $ExpectError +PirateBay.topTorrents(true); +// $ExpectType Promise +PirateBay.topTorrents(400); + +// $ExpectType Promise +PirateBay.recentTorrents(); +// $ExpectError +PirateBay.recentTorrents(10); + +// $ExpectError +PirateBay.userTorrents(); +// $ExpectType Promise +PirateBay.userTorrents('alice', { + page: 3, + orderBy: 'name', + sortBy: 'asc' +}); +// $ExpectType Promise +PirateBay.userTorrents('bob'); + +// $ExpectType Promise +const categoryGroup = PirateBay.getCategories(); +categoryGroup.then((groups: PirateBay.CategoryGroup[]) => { + groups[0].id; // $ExpectType string + groups[0].name; // $ExpectType string + groups[0].subcategories; // $ExpectType Category[] +}); +// $ExpectError +PirateBay.getCategories(154); + +// $ExpectError +PirateBay.getTvShow(); +// $ExpectType Promise +const tvShow = PirateBay.getTvShow(15); +tvShow.then((seasons: PirateBay.TVSeason[]) => { + seasons[0].title; // $ExpectType string + const torrents = seasons[0].torrents; // $ExpectType TVTorrent[] + torrents[0].id; // $ExpectType string + torrents[0].title; // $ExpectType string + torrents[0].link; // $ExpectType string +}); +// $ExpectType Promise +PirateBay.getTvShow('15'); diff --git a/types/thepiratebay/tsconfig.json b/types/thepiratebay/tsconfig.json new file mode 100644 index 0000000000..1d491e4d75 --- /dev/null +++ b/types/thepiratebay/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", + "thepiratebay-tests.ts" + ] +} diff --git a/types/thepiratebay/tslint.json b/types/thepiratebay/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/thepiratebay/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/tinajs__tina-redux/index.d.ts b/types/tinajs__tina-redux/index.d.ts new file mode 100644 index 0000000000..e48665e696 --- /dev/null +++ b/types/tinajs__tina-redux/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for @tinajs/tina-redux 1.4 +// Project: https://github.com/tinajs/tina-redux +// Definitions by: Jiayu Liu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/tinajs__tina-redux +// TypeScript Version: 2.3 + +import { Store, Dispatch } from "redux"; + +type MapStateToProps = (state: any) => any; +type mapDispatchToProps = (dispatch: Dispatch) => any; + +interface HOC { + onLoad: () => void; + onUnload: () => void; + methods: object; +} + +declare class TinaRedux { + constructor(reduxStore: Store); + connect(mapState?: MapStateToProps, mapDispatch?: mapDispatchToProps): HOC; +} + +export = TinaRedux; diff --git a/types/tinajs__tina-redux/package.json b/types/tinajs__tina-redux/package.json new file mode 100644 index 0000000000..7f5b19d45b --- /dev/null +++ b/types/tinajs__tina-redux/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "redux": "^4.0.0" + } +} diff --git a/types/tinajs__tina-redux/tinajs__tina-redux-tests.ts b/types/tinajs__tina-redux/tinajs__tina-redux-tests.ts new file mode 100644 index 0000000000..d4a7c2225f --- /dev/null +++ b/types/tinajs__tina-redux/tinajs__tina-redux-tests.ts @@ -0,0 +1,51 @@ +import { createStore, combineReducers, Action } from "redux"; +import TinaRedux from "@tinajs/tina-redux"; + +interface Todo { + id: number; + text: string; + completed: boolean; +} + +interface TodoAction extends Action, Todo {} + +const intialState: Todo[] = [ + { id: 1, text: "Star Tina.js", completed: false }, + { id: 2, text: "Star Tina-Redux", completed: true }, + { id: 3, text: "Build a mini-program with Tina.js", completed: false }, + { id: 4, text: "Add to Showcase of Tina.js", completed: false } +]; + +const todos = (state = intialState, action: TodoAction) => { + switch (action.type) { + case "ADD_TODO": + return [ + ...state, + { + id: action.id, + text: action.text, + completed: false + } + ]; + case "TOGGLE_TODO": + return state.map( + todo => + todo.id === action.id + ? { ...todo, completed: !todo.completed } + : todo + ); + case "CLEAR_COMPLETED_TODOS": + return state.filter(todo => !todo.completed); + default: + return state; + } +}; + +const todoApp = combineReducers({ + todos +}); + +const reduxStore = createStore(todoApp); +const store = new TinaRedux(reduxStore); + +export default store; diff --git a/types/tinajs__tina-redux/tsconfig.json b/types/tinajs__tina-redux/tsconfig.json new file mode 100644 index 0000000000..c3b4905b15 --- /dev/null +++ b/types/tinajs__tina-redux/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "allowSyntheticDefaultImports": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@tinajs/tina": ["tinajs__tina"], + "@tinajs/tina-redux": ["tinajs__tina-redux"] + } + }, + "files": ["index.d.ts", "tinajs__tina-redux-tests.ts"] +} diff --git a/types/tinajs__tina-redux/tslint.json b/types/tinajs__tina-redux/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/tinajs__tina-redux/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/tinycolor2/index.d.ts b/types/tinycolor2/index.d.ts index 921d8a4f08..4d28d623ac 100644 --- a/types/tinycolor2/index.d.ts +++ b/types/tinycolor2/index.d.ts @@ -1,393 +1,673 @@ -// Type definitions for tinycolor v1.4.1 +// Type definitions for tinycolor 1.4 // Project: https://github.com/bgrins/TinyColor -// Definitions by: Mordechai Zuber , Geert Jansen , Niels van Hoorn +// Definitions by: Mordechai Zuber , +// Geert Jansen , +// Niels van Hoorn , +// Junyoung Clare Jang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 -declare var tinycolor: tinycolor; +declare namespace tinycolor { + type ColorInputWithoutInstance = + | string + | ColorFormats.PRGB + | ColorFormats.PRGBA + | ColorFormats.RGB + | ColorFormats.RGBA + | ColorFormats.HSL + | ColorFormats.HSLA + | ColorFormats.HSV + | ColorFormats.HSVA + ; + type ColorInput = ColorInputWithoutInstance | Instance; -interface tinycolor { + namespace ColorFormats { + interface Alpha { + a: number; + } - /** - * Create a tinycolor instance of the color named. - * - * @param color - the color as a string to create an instance for. - */ - (color: string): tinycolorInstance; + interface PRGB { + r: string; + g: string; + b: string; + } - /** - * Create a tinycolor instance with the given RGB values. - * - * @param color - the rgb values to apply to the new instance. - */ - (color: ColorFormats.RGB): tinycolorInstance; + interface PRGBA extends PRGB, Alpha {} - /** - * Create a tinycolor instance with the given RGBA values. - * - * @param color - the rgba values to apply to the new instance. - */ - (color: ColorFormats.RGBA): tinycolorInstance; + interface RGB { + r: number; + g: number; + b: number; + } - /** - * Create a tinycolor instance with the given HSL values. - * - * @param color - the hsl values to apply to the new instance. - */ - (color: ColorFormats.HSL): tinycolorInstance; + interface RGBA extends RGB, Alpha {} - /** - * Create a tinycolor instance with the given HSLA values. - * - * @param color - the hsla values to apply to the new instance. - */ - (color: ColorFormats.HSLA): tinycolorInstance; + interface HSL { + h: number; + s: number; + l: number; + } - /** - * Create a tinycolor instance with the given HSV values. - * - * @param color - the hsv values to apply to the new instance. - */ - (color: ColorFormats.HSV): tinycolorInstance; + interface HSLA extends HSL, Alpha {} - /** - * Create a tinycolor instance with the given HSVA values. - * - * @param color - the hsva values to apply to the new instance. - */ - (color: ColorFormats.HSVA): tinycolorInstance; + interface HSV { + h: number; + s: number; + v: number; + } - /** - * Create a tinycolor instance based off the relative values. - * Works with any color formats - * - * @param ratio - the relative color/hue values to apply to the new instance. - */ - fromRatio(ratio: any): tinycolorInstance; // any of the interfaces defined in the ColorFormats module. + interface HSVA extends HSV { + a: number; + } + } - /** - * Compares the two colors and returns the difference between their brightness and color/hue - * - * @param firstColor - the first color to be used in the comparison. - * @param secondColor - the second color to be used in the comparison. - */ - readability(firstColor: ColorInput, secondColor: ColorInput): Readable.Readable; + interface ConstructorOptions { + format?: string; + gradientType?: boolean; + } - /** - * Ensure that foreground and background color combinations meet WCAG2 guidelines. - * - * @param foreColor - the fore color wanted. - * @param backColor - the back color wanted. - * @param wcag2 - The 'level' property states 'AA' or 'AAA' - if missing or invalid, it defaults to 'AA'; the 'size' property states 'large' or 'small' - if missing or invalid, it defaults to 'small'. If the entire object is absent, isReadable defaults to {level:"AA",size:"small"}. - */ - isReadable(foreColor: ColorInput, backColor: ColorInput, wcag2?: {level?: string, size?: string}): boolean; + interface WCAG2Options { + level?: "AA" | "AAA"; + size?: "large" | "small"; + } - /** - * Given a base color and a list of possible foreground or background colors for that base, - * returns the most readable color. Optionally returns Black or White if the most readable color is unreadable. - * - * @param color - the base color. - * @param colorsToCompare - array of colors to pick the most readable one from. - * @param args - and object with extra arguments - */ - mostReadable(color: ColorInput, colorsToCompare: ColorInput[], args?: {includeFallbackColors?: boolean, level?: string, size?: string}): tinycolorInstance; + interface MostReadableArgs extends WCAG2Options { + includeFallbackColors?: boolean; + } - /**/ - mix(color1: ColorInput, color2: ColorInput, amount?: number): tinycolorInstance; + interface Constructor { + /** + * Create a tinycolor instance of the color named. + * + * @param color - the color as one of the valid color input format. + */ + new (color?: ColorInput, opts?: ConstructorOptions): Instance; + (color?: ColorInput, opts?: ConstructorOptions): Instance; - /** - * Can be called with any tinycolor input - */ - equals(color1: ColorInput, color2: ColorInput): boolean; + /** + * Create a tinycolor instance based off the relative values. + * Works with any color formats + * + * @param ratio - the relative color/hue values to apply to the new instance. + */ + fromRatio(ratio?: ColorInputWithoutInstance): Instance; - /** - * Returns a random color - */ - random(): tinycolorInstance; + /** + * Compares two colors. Each colors can be any color inputs. + */ + equals(color1?: ColorInput, color2?: ColorInput): boolean; - /** - * key: hex value - * value: string name ex. hexnames["f00"] --> "red" - */ - hexNames: { [key: string]: string }; + /** + * Returns a random color + */ + random(): Instance; - /** - * key: 'real' color name - * value: hex value ex. names["red"] --> "f00" - */ - names: { [key: string]: string }; -} + mix(color1: ColorInput, color2: ColorInput, amount?: number): Instance; -interface tinycolorInstance { + /** + * Compares the two colors and returns the constrast between two colors as a number. + * + * @param color1 - the first color to be used in the comparison. + * @param color2 - the second color to be used in the comparison. + */ + readability(color1: ColorInput, color2: ColorInput): number; - /** - * Return an indication whether the color was successfully parsed. - */ - isValid(): boolean; + /** + * Ensure that foreground and background color combinations meet WCAG2 guidelines. + * + * @param color1 - the fore color wanted. + * @param color2 - the back color wanted. + * @param wcag2 - WCAG option. If the entire object is absent, function use the default of {level:"AA",size:"small"}. + * @param wcag2.level - The 'level' property states 'AA' or 'AAA' + * if missing or invalid, it defaults to 'AA' + * @param wcag2.size - The 'size' property states 'large' or 'small' + * if missing or invalid, it defaults to 'small'. + */ + isReadable(color1: ColorInput, color2: ColorInput, wcag2?: WCAG2Options): boolean; - /** - * Return an indication whether the color's perceived brightness is light. - */ - isLight(): boolean; + /** + * Given a base color and a list of possible foreground or background colors for that base, + * returns the most readable color. Optionally returns Black or White if the most readable color is unreadable. + * + * @param color - the base color. + * @param colorsToCompare - array of colors to pick the most readable one from. + * @param args - and object with extra arguments + */ + mostReadable(baseColor: ColorInput, colorList: ColorInput[], args?: MostReadableArgs): Instance; - /** - * Return an indication whether the color's perceived brightness is dark. - */ - isDark(): boolean; + /** + * key: 'real' color name + * value: hex value ex. names["red"] --> "f00" + */ + names: { + aliceblue: "f0f8ff"; + antiquewhite: "faebd7"; + aqua: "0ff"; + aquamarine: "7fffd4"; + azure: "f0ffff"; + beige: "f5f5dc"; + bisque: "ffe4c4"; + black: "000"; + blanchedalmond: "ffebcd"; + blue: "00f"; + blueviolet: "8a2be2"; + brown: "a52a2a"; + burlywood: "deb887"; + burntsienna: "ea7e5d"; + cadetblue: "5f9ea0"; + chartreuse: "7fff00"; + chocolate: "d2691e"; + coral: "ff7f50"; + cornflowerblue: "6495ed"; + cornsilk: "fff8dc"; + crimson: "dc143c"; + cyan: "0ff"; + darkblue: "00008b"; + darkcyan: "008b8b"; + darkgoldenrod: "b8860b"; + darkgray: "a9a9a9"; + darkgreen: "006400"; + darkgrey: "a9a9a9"; + darkkhaki: "bdb76b"; + darkmagenta: "8b008b"; + darkolivegreen: "556b2f"; + darkorange: "ff8c00"; + darkorchid: "9932cc"; + darkred: "8b0000"; + darksalmon: "e9967a"; + darkseagreen: "8fbc8f"; + darkslateblue: "483d8b"; + darkslategray: "2f4f4f"; + darkslategrey: "2f4f4f"; + darkturquoise: "00ced1"; + darkviolet: "9400d3"; + deeppink: "ff1493"; + deepskyblue: "00bfff"; + dimgray: "696969"; + dimgrey: "696969"; + dodgerblue: "1e90ff"; + firebrick: "b22222"; + floralwhite: "fffaf0"; + forestgreen: "228b22"; + fuchsia: "f0f"; + gainsboro: "dcdcdc"; + ghostwhite: "f8f8ff"; + gold: "ffd700"; + goldenrod: "daa520"; + gray: "808080"; + green: "008000"; + greenyellow: "adff2f"; + grey: "808080"; + honeydew: "f0fff0"; + hotpink: "ff69b4"; + indianred: "cd5c5c"; + indigo: "4b0082"; + ivory: "fffff0"; + khaki: "f0e68c"; + lavender: "e6e6fa"; + lavenderblush: "fff0f5"; + lawngreen: "7cfc00"; + lemonchiffon: "fffacd"; + lightblue: "add8e6"; + lightcoral: "f08080"; + lightcyan: "e0ffff"; + lightgoldenrodyellow: "fafad2"; + lightgray: "d3d3d3"; + lightgreen: "90ee90"; + lightgrey: "d3d3d3"; + lightpink: "ffb6c1"; + lightsalmon: "ffa07a"; + lightseagreen: "20b2aa"; + lightskyblue: "87cefa"; + lightslategray: "789"; + lightslategrey: "789"; + lightsteelblue: "b0c4de"; + lightyellow: "ffffe0"; + lime: "0f0"; + limegreen: "32cd32"; + linen: "faf0e6"; + magenta: "f0f"; + maroon: "800000"; + mediumaquamarine: "66cdaa"; + mediumblue: "0000cd"; + mediumorchid: "ba55d3"; + mediumpurple: "9370db"; + mediumseagreen: "3cb371"; + mediumslateblue: "7b68ee"; + mediumspringgreen: "00fa9a"; + mediumturquoise: "48d1cc"; + mediumvioletred: "c71585"; + midnightblue: "191970"; + mintcream: "f5fffa"; + mistyrose: "ffe4e1"; + moccasin: "ffe4b5"; + navajowhite: "ffdead"; + navy: "000080"; + oldlace: "fdf5e6"; + olive: "808000"; + olivedrab: "6b8e23"; + orange: "ffa500"; + orangered: "ff4500"; + orchid: "da70d6"; + palegoldenrod: "eee8aa"; + palegreen: "98fb98"; + paleturquoise: "afeeee"; + palevioletred: "db7093"; + papayawhip: "ffefd5"; + peachpuff: "ffdab9"; + peru: "cd853f"; + pink: "ffc0cb"; + plum: "dda0dd"; + powderblue: "b0e0e6"; + purple: "800080"; + rebeccapurple: "663399"; + red: "f00"; + rosybrown: "bc8f8f"; + royalblue: "4169e1"; + saddlebrown: "8b4513"; + salmon: "fa8072"; + sandybrown: "f4a460"; + seagreen: "2e8b57"; + seashell: "fff5ee"; + sienna: "a0522d"; + silver: "c0c0c0"; + skyblue: "87ceeb"; + slateblue: "6a5acd"; + slategray: "708090"; + slategrey: "708090"; + snow: "fffafa"; + springgreen: "00ff7f"; + steelblue: "4682b4"; + tan: "d2b48c"; + teal: "008080"; + thistle: "d8bfd8"; + tomato: "ff6347"; + turquoise: "40e0d0"; + violet: "ee82ee"; + wheat: "f5deb3"; + white: "fff"; + whitesmoke: "f5f5f5"; + yellow: "ff0"; + yellowgreen: "9acd32"; + }; - /** - * Returns the format used to create the tinycolor instance. - */ - getFormat(): string; + /** + * key: hex value + * value: string name ex. hexnames["f00"] --> "red" + */ + hexNames: { + "f0f8ff": "aliceblue"; + "faebd7": "antiquewhite"; + "0ff": "aqua" | "cyan"; + "7fffd4": "aquamarine"; + "f0ffff": "azure"; + "f5f5dc": "beige"; + "ffe4c4": "bisque"; + "000": "black"; + "ffebcd": "blanchedalmond"; + "00f": "blue"; + "8a2be2": "blueviolet"; + "a52a2a": "brown"; + "deb887": "burlywood"; + "ea7e5d": "burntsienna"; + "5f9ea0": "cadetblue"; + "7fff00": "chartreuse"; + "d2691e": "chocolate"; + "ff7f50": "coral"; + "6495ed": "cornflowerblue"; + "fff8dc": "cornsilk"; + "dc143c": "crimson"; + "00008b": "darkblue"; + "008b8b": "darkcyan"; + "b8860b": "darkgoldenrod"; + "a9a9a9": "darkgray" | "darkgrey"; + "006400": "darkgreen"; + "bdb76b": "darkkhaki"; + "8b008b": "darkmagenta"; + "556b2f": "darkolivegreen"; + "ff8c00": "darkorange"; + "9932cc": "darkorchid"; + "8b0000": "darkred"; + "e9967a": "darksalmon"; + "8fbc8f": "darkseagreen"; + "483d8b": "darkslateblue"; + "2f4f4f": "darkslategray" | "darkslategrey"; + "00ced1": "darkturquoise"; + "9400d3": "darkviolet"; + "ff1493": "deeppink"; + "00bfff": "deepskyblue"; + "696969": "dimgray" | "dimgrey"; + "1e90ff": "dodgerblue"; + "b22222": "firebrick"; + "fffaf0": "floralwhite"; + "228b22": "forestgreen"; + "f0f": "fuchsia" | "magenta"; + "dcdcdc": "gainsboro"; + "f8f8ff": "ghostwhite"; + "ffd700": "gold"; + "daa520": "goldenrod"; + "808080": "gray" | "grey"; + "008000": "green"; + "adff2f": "greenyellow"; + "f0fff0": "honeydew"; + "ff69b4": "hotpink"; + "cd5c5c": "indianred"; + "4b0082": "indigo"; + "fffff0": "ivory"; + "f0e68c": "khaki"; + "e6e6fa": "lavender"; + "fff0f5": "lavenderblush"; + "7cfc00": "lawngreen"; + "fffacd": "lemonchiffon"; + "add8e6": "lightblue"; + "f08080": "lightcoral"; + "e0ffff": "lightcyan"; + "fafad2": "lightgoldenrodyellow"; + "d3d3d3": "lightgray" | "lightgrey"; + "90ee90": "lightgreen"; + "ffb6c1": "lightpink"; + "ffa07a": "lightsalmon"; + "20b2aa": "lightseagreen"; + "87cefa": "lightskyblue"; + "789": "lightslategray" | "lightslategrey"; + "b0c4de": "lightsteelblue"; + "ffffe0": "lightyellow"; + "0f0": "lime"; + "32cd32": "limegreen"; + "faf0e6": "linen"; + "800000": "maroon"; + "66cdaa": "mediumaquamarine"; + "0000cd": "mediumblue"; + "ba55d3": "mediumorchid"; + "9370db": "mediumpurple"; + "3cb371": "mediumseagreen"; + "7b68ee": "mediumslateblue"; + "00fa9a": "mediumspringgreen"; + "48d1cc": "mediumturquoise"; + "c71585": "mediumvioletred"; + "191970": "midnightblue"; + "f5fffa": "mintcream"; + "ffe4e1": "mistyrose"; + "ffe4b5": "moccasin"; + "ffdead": "navajowhite"; + "000080": "navy"; + "fdf5e6": "oldlace"; + "808000": "olive"; + "6b8e23": "olivedrab"; + "ffa500": "orange"; + "ff4500": "orangered"; + "da70d6": "orchid"; + "eee8aa": "palegoldenrod"; + "98fb98": "palegreen"; + "afeeee": "paleturquoise"; + "db7093": "palevioletred"; + "ffefd5": "papayawhip"; + "ffdab9": "peachpuff"; + "cd853f": "peru"; + "ffc0cb": "pink"; + "dda0dd": "plum"; + "b0e0e6": "powderblue"; + "800080": "purple"; + "663399": "rebeccapurple"; + "f00": "red"; + "bc8f8f": "rosybrown"; + "4169e1": "royalblue"; + "8b4513": "saddlebrown"; + "fa8072": "salmon"; + "f4a460": "sandybrown"; + "2e8b57": "seagreen"; + "fff5ee": "seashell"; + "a0522d": "sienna"; + "c0c0c0": "silver"; + "87ceeb": "skyblue"; + "6a5acd": "slateblue"; + "708090": "slategray" | "slategrey"; + "fffafa": "snow"; + "00ff7f": "springgreen"; + "4682b4": "steelblue"; + "d2b48c": "tan"; + "008080": "teal"; + "d8bfd8": "thistle"; + "ff6347": "tomato"; + "40e0d0": "turquoise"; + "ee82ee": "violet"; + "f5deb3": "wheat"; + "fff": "white"; + "f5f5f5": "whitesmoke"; + "ff0": "yellow"; + "9acd32": "yellowgreen"; + }; + } - /** - * Returns the input passed into the constructer used to create the tinycolor instance. - */ - getOriginalInput(): any; // any of the interfaces in ColorFormats or a string + interface Instance { + /** + * Return an indication whether the color's perceived brightness is dark. + */ + isDark(): boolean; - /** - * Returns the alpha value of the color - */ - getAlpha(): number; + /** + * Return an indication whether the color's perceived brightness is light. + */ + isLight(): boolean; - /** - * Returns the perceived brightness of the color, from 0-255. - */ - getBrightness(): number; + /** + * Return an indication whether the color was successfully parsed. + */ + isValid(): boolean; - /** - * Returns the perceived luminance of a color, from 0-1. - */ - getLuminance(): number; + /** + * Returns the input passed into the constructer used to create the tinycolor instance. + */ + getOriginalInput(): ColorInput; - /** - * Sets the alpha value on the current color. - * - * @param alpha - The new alpha value. The accepted range is 0-1. - */ - setAlpha(alpha: number): tinycolorInstance; + /** + * Returns the format used to create the tinycolor instance. + */ + getFormat(): string; - /** - * Returns the object as a HSVA object. - */ - toHsv(): ColorFormats.HSVA; + /** + * Returns the alpha value of the color + */ + getAlpha(): number; - /** - * Returns the hsva values interpolated into a string with the following format: - * "hsva(xxx, xxx, xxx, xx)". - */ - toHsvString(): string; + /** + * Returns the perceived brightness of the color, from 0-255. + */ + getBrightness(): number; - /** - * Returns the object as a HSLA object. - */ - toHsl(): ColorFormats.HSLA; + /** + * Returns the perceived luminance of a color, from 0-1. + */ + getLuminance(): number; - /** - * Returns the hsla values interpolated into a string with the following format: - * "hsla(xxx, xxx, xxx, xx)". - */ - toHslString(): string; + /** + * Sets the alpha value on the current color. + * + * @param alpha - The new alpha value. The accepted range is 0-1. + */ + setAlpha(alpha: number): Instance; - /** - * Returns the hex value of the color. - */ - toHex(): string; + /** + * Returns the object as a HSVA object. + */ + toHsv(): ColorFormats.HSVA; - /** - * Returns the hex value of the color -with a # appened. - */ - toHexString(): string; + /** + * Returns the hsva values interpolated into a string with the following format: + * "hsva(xxx, xxx, xxx, xx)". + */ + toHsvString(): string; - /** - * Returns the hex 8 value of the color. - */ - toHex8(): string; + /** + * Returns the object as a HSLA object. + */ + toHsl(): ColorFormats.HSLA; - /** - * Returns the hex 8 value of the color -with a # appened. - */ - toHex8String(): string; + /** + * Returns the hsla values interpolated into a string with the following format: + * "hsla(xxx, xxx, xxx, xx)". + */ + toHslString(): string; - /** - * Returns the object as a RGBA object. - */ - toRgb(): ColorFormats.RGBA; + /** + * Returns the hex value of the color. + */ + toHex(): string; - /** - * Returns the RGBA values interpolated into a string with the following format: - * "RGBA(xxx, xxx, xxx, xx)". - */ - toRgbString(): string; + /** + * Returns the hex value of the color -with a # appened. + */ + toHexString(): string; - /** - * Returns the object as a RGBA object. - */ - toPercentageRgb(): ColorFormats.RGBA; + /** + * Returns the hex 8 value of the color. + */ + toHex8(): string; - /** - * Returns the RGBA relative values interpolated into a string with the following format: - * "RGBA(xxx, xxx, xxx, xx)". - */ - toPercentageRgbString(): string; + /** + * Returns the hex 8 value of the color -with a # appened. + */ + toHex8String(): string; - /** - * The 'real' name of the color -if there is one. - */ - toName(): string; + /** + * Returns the object as a RGBA object. + */ + toRgb(): ColorFormats.RGBA; - /** - * Returns the color represented as a Microsoft filter for use in old versions of IE. - */ - toFilter(): string; + /** + * Returns the RGBA values interpolated into a string with the following format: + * "RGBA(xxx, xxx, xxx, xx)". + */ + toRgbString(): string; - /** - * String representation of the color. - * - * @param format - The format to be used when displaying the string representation. - * The accepted values are: "rgb", "prgb", "hex6", "hex3", "hex8", "name", "hsl", "hsv". - */ - toString(format?: string): string; + /** + * Returns the object as a RGBA object. + */ + toPercentageRgb(): ColorFormats.PRGBA; - /** - * Lighten the color a given amount. Providing 100 will always return white. - * - * @param amount - The amount to lighten by. The valid range is 0 to 100. - * Default value: 10. - */ - lighten(amount?: number): tinycolorInstance; + /** + * Returns the RGBA relative values interpolated into a string with the following format: + * "RGBA(xxx, xxx, xxx, xx)". + */ + toPercentageRgbString(): string; - /** - * Brighten the color a given amount. - * - * @param amount - The amount to brighten by. The valid range is 0 to 100. - * Default value: 10. - */ - brighten(amount?: number): tinycolorInstance; + /** + * The 'real' name of the color -if there is one. + */ + toName(): string | false; - /** - * Darken the color a given amount. - * Providing 100 will always return black. - * - * @param amount - The amount to darken by. The valid range is 0 to 100. - * Default value: 10. - */ - darken(amount?: number): tinycolorInstance; - /** - * Desaturate the color a given amount. - * Providing 100 will is the same as calling greyscale. - * - * @param amount - The amount to desaturate by. The valid range is 0 to 100. - * Default value: 10. - */ - desaturate(amount?: number): tinycolorInstance; + /** + * Returns the color represented as a Microsoft filter for use in old versions of IE. + */ + toFilter(): string; - /** - * Saturate the color a given amount. - * - * @param amount - The amount to saturate by. The valid range is 0 to 100. - * Default value: 10. - */ - saturate(amount?: number): tinycolorInstance; + /** + * String representation of the color. + * + * @param format - The format to be used when displaying the string representation. + * The accepted values are: "rgb", "prgb", "hex6", "hex3", "hex8", "name", "hsl", "hsv". + */ + toString(format?: "rgb" | "prgb" | "hex" | "hex6" | "hex3" | "hex4" | "hex8" | "name" | "hsl" | "hsv"): string; - /** - * Completely desaturates a color into greyscale. - * Same as calling desaturate(100). - */ - greyscale(): tinycolorInstance; + /** + * Gets a new instance with the current color + */ + clone(): Instance; - /** - * Spin the hue a given amount. Calling with 0, 360, or -360 will do nothing. - * - * @param amount - The amount to spin by. The valid range is -360 to 360. - * Default value: 0. - */ - spin(amount?: number): tinycolorInstance; + /** + * Lighten the color a given amount. Providing 100 will always return white. + * + * @param amount - The amount to lighten by. The valid range is 0 to 100. + * Default value: 10. + */ + lighten(amount?: number): Instance; - /** - * Gets an analogous color scheme based off of the current color. - * - * @param results - The amount of results to return. - * Default value: 6. - * @param slices - The amount to slice the input color by. - * Default value: 30. - */ - analogous(results?: number, slices?: number): tinycolorInstance[]; + /** + * Brighten the color a given amount. + * + * @param amount - The amount to brighten by. The valid range is 0 to 100. + * Default value: 10. + */ + brighten(amount?: number): Instance; - /** - * Gets a monochromatic color scheme based off of the current color. - * - * @param results - The amount of results to return. - * Default value: 6. - */ - monochromatic(results?: number): tinycolorInstance[]; + /** + * Darken the color a given amount. + * Providing 100 will always return black. + * + * @param amount - The amount to darken by. The valid range is 0 to 100. + * Default value: 10. + */ + darken(amount?: number): Instance; + /** + * Desaturate the color a given amount. + * Providing 100 will is the same as calling greyscale. + * + * @param amount - The amount to desaturate by. The valid range is 0 to 100. + * Default value: 10. + */ + desaturate(amount?: number): Instance; - /** - * Gets a split complement color scheme based off of the current color. - */ - splitcomplement(): tinycolorInstance[]; + /** + * Saturate the color a given amount. + * + * @param amount - The amount to saturate by. The valid range is 0 to 100. + * Default value: 10. + */ + saturate(amount?: number): Instance; - /** - * Gets a triad based off of the current color. - */ - triad(): tinycolorInstance[]; + /** + * Completely desaturates a color into greyscale. + * Same as calling desaturate(100). + */ + greyscale(): Instance; - /** - * Gets a tetrad based off of the current color. - */ - tetrad(): tinycolorInstance[]; + /** + * Spin the hue a given amount. Calling with 0, 360, or -360 will do nothing. + * + * @param amount - The amount to spin by. The valid range is -360 to 360. + */ + spin(amount: number): Instance; - /** - * Gets the complement of the current color - */ - complement(): tinycolorInstance; + /** + * Gets an analogous color scheme based off of the current color. + * + * @param results - The amount of results to return. + * Default value: 6. + * @param slices - The amount to slice the input color by. + * Default value: 30. + */ + analogous(results?: number, slices?: number): Instance[]; - /** - * Gets a new instance with the current color - */ - clone(): tinycolorInstance; -} + /** + * Gets the complement of the current color + */ + complement(): Instance; -declare namespace Readable { - interface Readable { - brightness: number; - color: number; + /** + * Gets a monochromatic color scheme based off of the current color. + * + * @param results - The amount of results to return. + * Default value: 6. + */ + monochromatic(results?: number): Instance[]; + + /** + * Gets a split complement color scheme based off of the current color. + */ + splitcomplement(): [Instance, Instance, Instance]; + + /** + * Gets a triad based off of the current color. + */ + triad(): [Instance, Instance, Instance]; + + /** + * Gets a tetrad based off of the current color. + */ + tetrad(): [Instance, Instance, Instance, Instance]; } } -declare namespace ColorFormats { - interface RGB { - r: number; - g: number; - b: number; - } - - interface RGBA extends RGB { - a: number - } - - interface HSL { - h: number; - s: number; - l: number; - } - - interface HSLA extends HSL { - a: number; - } - - interface HSV { - h: number; - s: number; - v: number; - } - - interface HSVA extends HSV { - a: number; - } -} - -type ColorInput = string | ColorFormats.RGB | ColorFormats.RGBA | ColorFormats.HSL | ColorFormats.HSLA | ColorFormats.HSV | ColorFormats.HSVA | tinycolorInstance - -declare module 'tinycolor2' { - export = tinycolor; -} \ No newline at end of file +declare const tinycolor: tinycolor.Constructor; +export = tinycolor; +export as namespace tinycolor; diff --git a/types/tinycolor2/tinycolor2-tests.ts b/types/tinycolor2/tinycolor2-tests.ts index f6a6634f5f..96eb31ed23 100644 --- a/types/tinycolor2/tinycolor2-tests.ts +++ b/types/tinycolor2/tinycolor2-tests.ts @@ -1,126 +1,200 @@ - - /* * Not all possible formats for construction are displayed. * To see a complete list please view: https://github.com/bgrins/TinyColor */ -var tester: tinycolorInstance = tinycolor("red"); +const testColor: tinycolor.Instance = tinycolor("red"); /* Constructor Tests*/ // string -tester = tinycolor("#ffffff"); +// $ExpectType Instance +tinycolor("#ffffff"); -//rgb && rgba -tester = tinycolor({ r: 40, g: 30, b: 20 }); -tester = tinycolor({ r: 255, g: 20, b: 10, a: 0 }); -tester = tinycolor.fromRatio({ r: 0.5, g: 0.2, b: 1, a: 0 }); -tester = tinycolor.fromRatio({ r: 1, g: 0, b: 0.7, a: 0 }); +// rgb && rgba +// $ExpectType Instance +tinycolor({ r: 40, g: 30, b: 20 }); +// $ExpectType Instance +tinycolor({ r: 255, g: 20, b: 10, a: 0 }); +// $ExpectType Instance +tinycolor.fromRatio({ r: 0.5, g: 0.2, b: 1, a: 0 }); +// $ExpectType Instance +tinycolor.fromRatio({ r: 1, g: 0, b: 0.7, a: 0 }); -//hsl && hsla -tester = tinycolor({ h: 0, s: 0, l: 0 }); -tester = tinycolor({ h: 0, s: 0, l: 0, a: 0 }); -tester = tinycolor.fromRatio({ h: 0.5, s: 0.2, l: 1, a: 0 }); +// hsl && hsla +// $ExpectType Instance +tinycolor({ h: 0, s: 0, l: 0 }); +// $ExpectType Instance +tinycolor({ h: 0, s: 0, l: 0, a: 0 }); +// $ExpectType Instance +tinycolor.fromRatio({ h: 0.5, s: 0.2, l: 1, a: 0 }); -//hsv && hsva -tester = tinycolor({ h: 0, s: 0, v: 0 }); -tester = tinycolor({ h: 0, s: 0, v: 0, a: 0 }); +// hsv && hsva +// $ExpectType Instance +tinycolor({ h: 0, s: 0, v: 0 }); +// $ExpectType Instance +tinycolor({ h: 0, s: 0, v: 0, a: 0 }); -//tinycolor static methods -tester = tinycolor.mix(tester, tester); -tester = tinycolor.mix("#ff0000", "#00ff00"); -tester = tinycolor.mix(tester, tester, 50); -tester = tinycolor.random(); -var isEqual = tinycolor.equals(tester, tester); +// tinycolor static methods +// $ExpectType Instance +tinycolor.mix(testColor, testColor); +// $ExpectType Instance +tinycolor.mix("#ff0000", "#00ff00"); +// $ExpectType Instance +tinycolor.mix(testColor, testColor, 50); +// $ExpectType Instance +tinycolor.random(); -/*Tinycolor object properties*/ +// $ExpectType boolean +tinycolor.equals(testColor, testColor); -var readable: Readable.Readable = tinycolor.readability(tester, tester); -var isReadable: boolean = tinycolor.isReadable(tester, tester); -var isReadable: boolean = tinycolor.isReadable(tester, tester, {size: "small"}); -tester = tinycolor.mostReadable(tester, [tester, tester, tester]); -tester = tinycolor.mostReadable(tester, [tester, tester, tester], {size: "large", level:"AA"}); +// $ExpectType number +tinycolor.readability(testColor, testColor); +// $ExpectType boolean +tinycolor.isReadable(testColor, testColor); +// $ExpectType boolean +tinycolor.isReadable(testColor, testColor, {size: "small"}); +// $ExpectType Instance +tinycolor.mostReadable(testColor, [testColor, testColor, testColor]); +// $ExpectType Instance +tinycolor.mostReadable(testColor, [testColor, testColor, testColor], {size: "large", level: "AA"}); -var hexNames: { [key: string]: string } = tinycolor.hexNames; -var names: { [key: string]: string } = tinycolor.names; +const hexNames: { [key: string]: string } = tinycolor.hexNames; +const names: { [key: string]: string } = tinycolor.names; +// $ExpectType "linen" +tinycolor.hexNames["faf0e6"]; +// $ExpectType "yellow" +tinycolor.hexNames["ff0"]; +// $ExpectType "f0f8ff" +tinycolor.names["aliceblue"]; +// $ExpectType "808080" +tinycolor.names["gray"]; -/*Instance Methods*/ +/* Instance Methods */ -//check properties -var isValid: boolean = tester.isValid(); -var isLight: boolean = tester.isLight(); -var isDark: boolean = tester.isDark(); +// check properties +// $ExpectType boolean +testColor.isValid(); +// $ExpectType boolean +testColor.isLight(); +// $ExpectType boolean +testColor.isDark(); -//get properties -var alpha: number = tester.getAlpha(); -var brightness: number = tester.getBrightness(); -var format: string = tester.getFormat(); -var originalInput: any = tester.getOriginalInput(); +// get properties +const alpha: number = testColor.getAlpha(); +// $ExpectType number +testColor.getBrightness(); +// $ExpectType string +testColor.getFormat(); +// $ExpectType ColorInput +testColor.getOriginalInput(); -//set properties -tester = tester.setAlpha(alpha); +// set properties +// $ExpectType Instance +testColor.setAlpha(alpha); -//representations -var hsva: ColorFormats.HSVA = tester.toHsv(); -var hsvString: string = tester.toHsvString(); +// representations +// $ExpectType HSVA +testColor.toHsv(); +// $ExpectType string +testColor.toHsvString(); -var hsl: ColorFormats.HSLA = tester.toHsl(); -var hslString: string = tester.toHslString(); +// $ExpectType HSLA +testColor.toHsl(); +// $ExpectType string +testColor.toHslString(); -var hex: string = tester.toHex(); -var hexString: string = tester.toHexString(); +// $ExpectType string +testColor.toHex(); +// $ExpectType string +testColor.toHexString(); -var hex8: string = tester.toHex8(); -var hex8String: string = tester.toHex8String(); +// $ExpectType string +testColor.toHex8(); +// $ExpectType string +testColor.toHex8String(); -var rgba: ColorFormats.RGBA = tester.toRgb(); -var rgbString: string = tester.toString(); +// $ExpectType RGBA +testColor.toRgb(); +// $ExpectType string +testColor.toString(); -var percentageRGBA: ColorFormats.RGBA = tester.toPercentageRgb(); -var percentageRGBString: string = tester.toPercentageRgbString(); +// $ExpectType PRGBA +testColor.toPercentageRgb(); +// $ExpectType string +testColor.toPercentageRgbString(); -var name_: string = tester.toName(); -var filter: string = tester.toFilter(); -var sString: string = tester.toString(); -sString = tester.toString("rgb"); -sString = tester.toString("prgb"); -sString = tester.toString("hex6"); -sString = tester.toString("hex3"); -sString = tester.toString("hex8"); -sString = tester.toString("name"); -sString = tester.toString("hsl"); -sString = tester.toString("hsv"); +// $ExpectType string | false +testColor.toName(); +// $ExpectType string +testColor.toFilter(); +// $ExpectType string +testColor.toString(); +// $ExpectType string +testColor.toString("rgb"); +// $ExpectType string +testColor.toString("prgb"); +// $ExpectType string +testColor.toString("hex6"); +// $ExpectType string +testColor.toString("hex3"); +// $ExpectType string +testColor.toString("hex8"); +// $ExpectType string +testColor.toString("name"); +// $ExpectType string +testColor.toString("hsl"); +// $ExpectType string +testColor.toString("hsv"); -//color modifications -tester = tester.lighten(); -tester = tester.lighten(20); +// color modifications +// $ExpectType Instance +testColor.lighten(); +// $ExpectType Instance +testColor.lighten(20); -tester = tester.brighten(); -tester = tester.brighten(20); +// $ExpectType Instance +testColor.brighten(); +// $ExpectType Instance +testColor.brighten(20); -tester = tester.darken(); -tester = tester.darken(20); +// $ExpectType Instance +testColor.darken(); +// $ExpectType Instance +testColor.darken(20); -tester = tester.desaturate(); -tester = tester.desaturate(20); +// $ExpectType Instance +testColor.desaturate(); +// $ExpectType Instance +testColor.desaturate(20); -tester = tester.saturate(); -tester = tester.saturate(20); +// $ExpectType Instance +testColor.saturate(); +// $ExpectType Instance +testColor.saturate(20); -tester = tester.spin(); -tester = tester.spin(20); +// $ExpectType Instance +testColor.spin(20); -tester = tester.greyscale(); +// $ExpectType Instance +testColor.greyscale(); -//color combinations -var colors: tinycolorInstance[] = tester.analogous(); -colors = tester.analogous(6, 30); +// color combinations +// $ExpectType Instance[] +testColor.analogous(); +// $ExpectType Instance[] +testColor.analogous(6, 30); -colors = tester.monochromatic(); -colors = tester.monochromatic(10); +// $ExpectType Instance[] +testColor.monochromatic(); +// $ExpectType Instance[] +testColor.monochromatic(10); -colors = tester.splitcomplement(); -colors = tester.triad(); -colors = tester.tetrad(); +// $ExpectType [Instance, Instance, Instance] +testColor.splitcomplement(); +// $ExpectType [Instance, Instance, Instance] +testColor.triad(); +// $ExpectType [Instance, Instance, Instance, Instance] +testColor.tetrad(); -tester = tester.complement(); \ No newline at end of file +// $ExpectType Instance +testColor.complement(); diff --git a/types/tinycolor2/tslint.json b/types/tinycolor2/tslint.json index a41bf5d19a..64aace11d6 100644 --- a/types/tinycolor2/tslint.json +++ b/types/tinycolor2/tslint.json @@ -1,79 +1,6 @@ { "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 + "max-line-length": false } } diff --git a/types/twit/index.d.ts b/types/twit/index.d.ts index 9918d58470..ce8484bbe1 100644 --- a/types/twit/index.d.ts +++ b/types/twit/index.d.ts @@ -4,6 +4,7 @@ // sapphiredev // abraham // siwalik +// plhery // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -271,6 +272,8 @@ declare module 'twit' { include_rts?: boolean, skip_status?: boolean, url?: string, + include_user_entities?: boolean, + stringify_ids?: boolean, } export interface PromiseResponse { data: Response, diff --git a/types/umzug/index.d.ts b/types/umzug/index.d.ts index f74c5933be..a163ea01d9 100644 --- a/types/umzug/index.d.ts +++ b/types/umzug/index.d.ts @@ -1,13 +1,15 @@ -// Type definitions for Umzug v2.1.0 +// Type definitions for Umzug v2.2.0 // Project: https://github.com/sequelize/umzug // Definitions by: Ivan Drinchev // Margus Lamp // Troy McKinnon +// Emmanuel Gautier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import { EventEmitter } from 'events'; import Sequelize = require("sequelize"); +import MongoDB = require("mongodb"); declare namespace umzug { @@ -116,6 +118,27 @@ declare namespace umzug { } + interface MongoDBStorageOptions extends Storage { + + /** + * The MongoDB database connection instance. + */ + connection?: MongoDB.Db; + + /** + * The to be used Mongo collection cursor. + * Defaults to collection created from collectionName attribute. + */ + collection?: MongoDB.Collection; + + /** + * The name of the collection used by the connection. + * Defaults to 'migrations' + */ + collectionName?: string; + + } + interface ExecuteOptions { migrations?: Array; method?: string; @@ -125,12 +148,12 @@ declare namespace umzug { /** * The storage. */ - storage?: "json" | "sequelize" | Storage; + storage?: "json" | "sequelize" | "mongodb" | Storage; /** * The options for the storage. */ - storageOptions?: JSONStorageOptions | SequelizeStorageOptions | Object; + storageOptions?: JSONStorageOptions | SequelizeStorageOptions | MongoDBStorageOptions | Object; /** * The logging function. diff --git a/types/umzug/umzug-tests.ts b/types/umzug/umzug-tests.ts index 95ccf15665..730f350315 100644 --- a/types/umzug/umzug-tests.ts +++ b/types/umzug/umzug-tests.ts @@ -1,5 +1,6 @@ import Umzug = require('umzug'); import Sequelize = require('sequelize'); +import MongoDB = require('mongodb'); let someVar: Umzug.Umzug; const umzug = new Umzug({}); @@ -44,7 +45,7 @@ umzug.on('reverted', (name: string, migration: Umzug.Migration) => null); new Umzug({ // The storage. - // Possible values: 'json', 'sequelize', an object + // Possible values: 'json', 'sequelize', 'mongodb' an object storage: 'json', // The options for the storage. @@ -80,7 +81,7 @@ new Umzug({ new Umzug({ // The storage. - // Possible values: 'json', 'sequelize', an object + // Possible values: 'json', 'sequelize', 'mongodb' an object storage: 'json', storageOptions: { path: '/db/sequelize-meta.json', @@ -121,3 +122,30 @@ new Umzug({ }, }); + +const mongodb = new MongoDB.Db('database', new MongoDB.Server('host', 21017)); + +new Umzug({ + // The storage. + // Possible values: 'json', 'sequelize', 'mongodb' an object + storage: 'mongodb', + storageOptions: { + /** + * The MongoDB database connection instance. + */ + connection: mongodb, + + /** + * The to be used Mongo collection cursor. + * Defaults to collection created from collectionName attribute. + */ + collection: mongodb.collection, + + /** + * The name of the collection used by the connection. + * Defaults to 'migrations' + */ + collectionName: 'migrations' + }, + +}); diff --git a/types/uri-templates/index.d.ts b/types/uri-templates/index.d.ts index ad8cead946..d378de8a4f 100644 --- a/types/uri-templates/index.d.ts +++ b/types/uri-templates/index.d.ts @@ -1,16 +1,19 @@ -// Type definitions for uri-templates 0.1.2 +// Type definitions for uri-templates 0.1.9 // Project: https://github.com/geraintluff/uri-templates // Definitions by: Bart van der Schoor +// Bartek Szczepański // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - declare function utpl(template: string): utpl.URITemplate; declare namespace utpl { export interface URITemplate { - fillFromObject(vars: Object): string; + fillFromObject(vars: { [key: string]: string }): string; fill(callback: (varName: string) => string): string; - fromUri(uri: string): Object; + fill(vars: { [key: string]: string }): string; + fromUri(uri: string): { [key: string]: string }; + varNames: string[]; + template: string; } } diff --git a/types/uri-templates/uri-templates-tests.ts b/types/uri-templates/uri-templates-tests.ts index 0aeb5e0bfe..d29b801de1 100644 --- a/types/uri-templates/uri-templates-tests.ts +++ b/types/uri-templates/uri-templates-tests.ts @@ -1,15 +1,23 @@ - import utmpl = require('uri-templates'); import URITemplate = utmpl.URITemplate; -var str: string; -var u: URITemplate; -var obj: Object; +let str: string; +let u: URITemplate; +const obj = { test: 'test1' }; u = utmpl(str); str = u.fillFromObject(obj); -str = u.fill((key) => { - return str; +str = u.fill(key => { + return str; }); -obj = u.fromUri(str); +str = u.fill(obj); +const newObj = u.fromUri(str); + +let varNames: string[]; + +varNames = u.varNames; + +let template: string; + +template = u.template; diff --git a/types/url-regex/index.d.ts b/types/url-regex/index.d.ts index ed51c6e34d..58f3793baa 100644 --- a/types/url-regex/index.d.ts +++ b/types/url-regex/index.d.ts @@ -1,12 +1,15 @@ -// Type definitions for url-regex 4.0 +// Type definitions for url-regex 4.1 // Project: https://github.com/kevva/url-regex // Definitions by: Daniel Perez Alvarez +// sosukesuzuki // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** Regular expression for matching URLs. */ declare function urlRegex(options?: { /** Only match an exact string. Useful with RegExp#test to check if a string is a URL. */ exact?: boolean; + /** Force URLs to start with a valid protocol or www. If set to false it'll match the TLD against a list of valid TLDs(https://github.com/stephenmathieson/node-tlds). */ + strict?: boolean; }): RegExp; export = urlRegex; diff --git a/types/url-regex/url-regex-tests.ts b/types/url-regex/url-regex-tests.ts index 2a2db45a28..de62d9a796 100644 --- a/types/url-regex/url-regex-tests.ts +++ b/types/url-regex/url-regex-tests.ts @@ -8,4 +8,6 @@ urlRegex({exact: true}).test('https://github.com foo bar'); urlRegex({exact: true}).test('https://github.com'); +urlRegex({exact: true, strict: false}).test('github.com'); + 'foo https://github.com bar //google.com'.match(urlRegex()); diff --git a/types/video.js/index.d.ts b/types/video.js/index.d.ts index f18ff8890e..6e5863500d 100644 --- a/types/video.js/index.d.ts +++ b/types/video.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Video.js 6.2 +// Type definitions for Video.js 7.0 // Project: https://github.com/videojs/video.js // Definitions by: Vincent Bortone // Simon Clériot @@ -15,285 +15,6629 @@ // Javascript, whether the browser is playing the video through HTML5 // video, Flash, or any other supported playback technologies. -declare function videojs( - id: any, - options?: videojs.PlayerOptions, - ready?: () => void -): videojs.Player; -export default videojs; +/** + * Doubles as the main function for users to create a inplayer instance and also + * the main library object. + * The `videojs` function can be used to initialize or retrieve a player. + * + * @param id + * Video element or video element ID + * + * @param [options] + * Optional options object for config/settings + * + * @param [ready] + * Optional ready callback + * + * @return A player instance + */ +declare function videojs(id: any, options?: videojs.PlayerOptions, ready?: () => void): videojs.Player; +export = videojs; export as namespace videojs; declare namespace videojs { - const getComponent: typeof Component.getComponent; - const registerComponent: typeof Component.registerComponent; - const getPlugin: typeof Plugin.getPlugin; - function registerPlugin( - pluginName: string, - pluginFn: (this: Player, ...parameters: any[]) => void - ): void; - function addLanguage(lang: string, data: { [key: string]: string }): void; - function mergeOptions( - option: A, - option2?: B, - option3?: C, - option4?: D, - option5?: E, - option6?: F - ): A & B & C & D & E & F; + /** + * Adding languages so that they're available to all players. + * Example: `addLanguage('es', { 'Hello': 'Hola' });` + * + * @param code + * The language code or dictionary property + * + * @param data + * The data values to be translated + * + * @return The resulting language dictionary object + */ + function addLanguage(code: string, data: LanguageTranslations): LanguageTranslations; - interface PlayerOptions { - aspectRatio?: string; - autoplay?: boolean; - autoSetup?: boolean; - children?: string[]; - controlBar?: { - volumePanel?: { - inline?: boolean; - vertical?: boolean; - }; - }; - controls?: boolean; - defaultVolume?: number; - fluid?: boolean; - height?: number; - html5?: any; - inactivityTimeout?: number; - language?: string; - languages?: { [key: string]: string }; - loop?: boolean; - muted?: boolean; - nativeControlsForTouch?: boolean; - notSupportedMessage?: string; - playbackRates?: number[]; - plugins?: any; - poster?: string; - preload?: string; - sourceOrder?: boolean; - sources?: Source[]; - src?: string; - techCanOverridePoster?: boolean; - techOrder?: string[]; - width?: number; - } + /** + * Bind (a.k.a proxy or Context). A simple method for changing the context of a function + * It also stores a unique id on the function so it can be easily removed from events. + * + * @param context + * The object to bind as scope. + * + * @param fn + * The function to be bound to a scope. + * + * @param [uid] + * An optional unique ID for the function to be set + * + * @return The new function that will be bound into the context given + */ + function bind any)>(context: any, fn: F, uid?: number): F; - interface Source { - type: string; - src: string; - } + /** + * Should create a fake `TimeRange` object which mimics an HTML5 time range instance. + * + * @param start + * The start of a single range or an array of ranges + * + * @param end + * The end of a single range. + */ + function createTimeRanges(start?: number | TimeRange[], end?: number): TimeRange; - interface Dimensions { - width: number; - height: number; - } + /** + * A suite of browser and device tests from {@link browser}. + * + */ + const browser: Browser; - class EventTarget { - addEventListener( - type: string | string[], - callback: (eventObject: Event) => void - ): void; - dispatchEvent(event: string | Event | { [key: string]: any }): void; - off( - type?: string | string[], - callback?: (eventObject: Event) => void - ): void; - on( - type: string | string[], - callback: (eventObject: Event) => void - ): void; - one( - type: string | string[], - callback: (eventObject: Event) => void - ): void; - removeEventListener( - type?: string | string[], - callback?: (eventObject: Event) => void - ): void; - trigger(event: string | Event | { [key: string]: any }): void; - } + const dom: Dom; - class Component extends EventTarget { - constructor(player: Player, options: any); + /** + * Format seconds as a time string, H:MM:SS or M:SS. Supplying a guide (in seconds) + * will force a number of leading zeros to cover the length of the guide. + * + * @param seconds + * Number of seconds to be turned into a string + * + * @param guide + * Number (in seconds) to model the string after + * + * @return Time formatted as H:MM:SS or M:SS + */ + function formatTime(seconds: number, guide: number): string; - static getComponent(name: "Player" | "player"): typeof Player; - static getComponent(name: "Button" | "button"): typeof Button; - static getComponent( - name: "ClickableComponent" | "clickablecomponent" - ): typeof ClickableComponent; - static getComponent( - name: "ModalDialog" | "modaldialog" - ): typeof ModalDialog; - static getComponent( - name: "ControlBar" | "controlbar" - ): typeof ControlBar; - static getComponent( - name: "Component" | "component" | string - ): typeof Component; - static registerComponent( - name: string, - ComponentToRegister: typeof Component - ): typeof Component; + /** + * Returns an array of all current players. + * + * @return An array of all players. The array will be in the order that + * `Object.keys` provides, which could potentially vary between + * JavaScript engines. + * + */ + function getAllPlayers(): Player[]; - $(selector: string, context?: string | Element): Element; - $$(selector: string, context?: string | Element): NodeList; - addChild( - component: string, - optionsopt?: any, - indexopt?: number - ): Component; - addChild( - component: Element, - optionsopt?: any, - indexopt?: number - ): Element; - addChild( - component: T, - optionsopt?: any, - indexopt?: number - ): T; - addClass(classToAdd: string): void; - blur(): void; - buildCSSClass(): string; - cancelAnimationFrame(id: number): number; - children(): Component[]; - controlText(key: string): string; - clearInterval(intervalId: number): number; - clearTimeout(timeoutId: number): number; - contentEl(): Element; - createEl( - tagNameopt?: string, - properties?: any, - attributes?: any - ): Element; - currentDimension(widthOrHeight: "width" | "height"): number; - currentDimensions(): Dimensions; - currentHeight(): number; - currentWidth(): number; - dimension(widthOrHeight: "width" | "height"): number; - dimension( - widthOrHeight: "width" | "height", - num: string | number, - skipListenersopt?: boolean - ): void; - dimensions(width: string | number, height: string | number): void; - dispose(): void; - el(): Element; - enableTouchActivity(): void; - focus(): void; - getAttribute(attribute: string): string | null; - getChild(name: string): Component | undefined; - getChildById(id: string): Component | undefined; - hasClass(classToCheck: string): boolean; - height(): number | string; - height(num: number | string, skipListeners?: boolean): void; - hide(): void; - id(): string; - initChildren(): void; - localize(key: string, tokens?: string[], defaultValue?: string): string; - name(): string; - options(obj: any): any; - played(): TimeRanges; - player(): Player; - ready(callback: (this: this) => void): this; - removeAttribute(attribute: string): void; - removeChild(component: Component): void; - removeClass(classToRemove: string): void; - requestAnimationFrame(fn: () => void): number; - setAttribute(attribute: string, value: string): void; - setInterval(fn: () => void, interval: number): number; - setTimeout(fn: () => void, timeout: number): number; - show(): void; - toggleClass( - classToToggle: string, - predicate?: - | boolean - | ((element: Element, classToToggle: string) => boolean) - ): void; - trigger(eventName: string, ...parameters: any[]): void; - triggerReady(): void; - width(): string | number; - width(num: number, skipListeners?: number): void; - } + /** + * Get a component class object by name + * + * @borrows Component.getComponent as getComponent + */ + const getComponent: typeof Component.getComponent; - class ControlBar extends Component {} + /** + * Get a single player based on an ID or DOM element. + * + * This is useful if you want to check if an element or ID has an associated + * Video.js player, but not create one if it doesn't. + * + * @param id + * An HTML element - `

  • ` + */ + interface MenuItem extends ClickableComponent { + options_: MenuItemOptions; + + /** + * Create the `MenuItem's DOM element + * + * @param [type=li] + * Element's node type, not actually used, always set to `li`. + * + * @param [props={}] + * An object of properties that should be set on the element + * + * @param [attrs={}] + * An object of attributes that should be set on the element + * + * @return The element that gets created. + */ + createEl(type: string, props?: any, attrs?: any): HTMLLIElement; + + /** + * Any click on a `MenuItem` puts it into the selected state. + * See {@link ClickableComponent#handleClick} for instances where this is called. + * + * @param event + * The `keydown`, `tap`, or `click` event that caused this function to be + * called. + * + * @listens tap + * @listens click + */ + handleClick(event: EventTarget.Event): void; + + /** + * Set the state for this menu item as selected or not. + * + * @param selected + * if the menu item is selected or not + */ + selected(selected: boolean): void; + } + + const MenuItem: { + prototype: MenuItem; + + /** + * Creates an instance of the this class. + * + * @param player + * The `Player` that this class should be attached to. + * + * @param [options={}] + * The key/value store of player options. + * + */ + new (player: Player, options?: MenuItemOptions): MenuItem; + }; + + interface MenuItemOptions extends ComponentOptions { + label?: string; + multiSelectable?: boolean; + selectable?: boolean; + selected?: boolean; + } + + interface Middleware { + /** + * + * @param src + * @param next + */ + setSource: (src: Tech.SourceObject, next: (err: any, next: (src: Tech.SourceObject) => void) => void) => void; + } + + /** + * The `ModalDialog` displays over the video and its controls, which blocks + * interaction with the player until it is closed. + * + * Modal dialogs include a "Close" button and will close when that button + * is activated - or when ESC is pressed anywhere. + */ + interface ModalDialog extends Component { + options_: ModalDialogOptions; + + closeable_: boolean; + + /** + * Builds the default DOM `className`. + * + * @return The DOM `className` for this object. + */ + buildCSSClass(): string; + + /** + * Closes the modal, does nothing if the `ModalDialog` is + * not open. + * + * @fires ModalDialog#beforemodalclose + * @fires ModalDialog#modalclose + */ + close(): void; + + /** + * Check to see if the `ModalDialog` is closeable via the UI. + * + * @param [value] + * If given as a boolean, it will set the `closeable` option. + * + * @return Returns the final value of the closable option. + */ + closeable(value: boolean): boolean; + + /** + * Gets or sets the modal content, which gets normalized before being + * rendered into the DOM. + * + * This does not update the DOM or fill the modal, but it is called during + * that process. + * + * @param [value] + * If defined, sets the internal content value to be used on the + * next call(s) to `fill`. This value is normalized before being + * inserted. To "clear" the internal content value, pass `null`. + * + * @return The current content of the modal dialog + */ + content(value: Content): any; + + /** + * Create the `ModalDialog`'s DOM element + * + * @return The DOM element that gets created. + */ + createEl(): HTMLDivElement; + + /** + * Returns the description string for this modal. Primarily used for + * accessibility. + * + * @return The localized or raw description of this modal. + */ + description(): string; + + dispose(): void; + + /** + * Empties the content element. This happens anytime the modal is filled. + * + * @fires ModalDialog#beforemodalempty + * @fires ModalDialog#modalempty + */ + empty(): void; + + /** + * Fill the modal's content element with the modal's "content" option. + * The content element will be emptied before this change takes place. + */ + fill(): void; + + /** + * Fill the modal's content element with arbitrary content. + * The content element will be emptied before this change takes place. + * + * @fires ModalDialog#beforemodalfill + * @fires ModalDialog#modalfill + * + * @param [content] + * The same rules apply to this as apply to the `content` option. + */ + fillWith(content: Content): void; + + /** + * Keydown handler. Attached when modal is focused. + * + * @listens keydown + */ + handleKeyDown(): void; + + /** + * Handles `keydown` events on the document, looking for ESC, which closes + * the modal. + * + * @param e + * The keypress that triggered this event. + * + * @listens keydown + */ + handleKeyPress(e: EventTarget.Event): void; + + /** + * Returns the label string for this modal. Primarily used for accessibility. + * + * @return the localized or raw label of this modal. + */ + label(): string; + + /** + * Opens the modal. + * + * @fires ModalDialog#beforemodalopen + * @fires ModalDialog#modalopen + */ + open(): void; + + /** + * If the `ModalDialog` is currently open or closed. + * + * @param [value] + * If given, it will open (`true`) or close (`false`) the modal. + * + * @return the current open state of the modaldialog + */ + opened(value?: boolean): boolean; + } + + const ModalDialog: { + prototype: ModalDialog; + + /** + * Create an instance of this class. + * + * @param player + * The `Player` that this class should be attached to. + * + * @param [options] + * The key/value store of player options. + */ + new (player: Player, options?: ModalDialogOptions): ModalDialog; + }; + + /** + * Options for this class + * + * @param [content=undefined] + * Provide customized content for this modal. + * + * @param [description] + * A text description for the modal, primarily for accessibility. + * + * @param [fillAlways=false] + * Normally, modals are automatically filled only the first time + * they open. This tells the modal to refresh its content + * every time it opens. + * + * @param [label] + * A text label for the modal, primarily for accessibility. + * + * @param [temporary=true] + * If `true`, the modal can only be opened once; it will be + * disposed as soon as it's closed. + * + * @param [uncloseable=false] + * If `true`, the user will not be able to close the modal + * through the UI in the normal ways. Programmatic closing is + * still possible. + */ + interface ModalDialogOptions extends ComponentOptions { + content?: any; + description?: string; + fillAlways?: boolean; + label?: string; + temporary?: boolean; + uncloseable?: boolean; + } + + /** + * The {@link MouseTimeDisplay} component tracks mouse movement over the + * {@link ProgressControl}. It displays an indicator and a {@link TimeTooltip} + * indicating the time which is represented by a given point in the + * {@link ProgressControl}. + */ + interface MouseTimeDisplay extends Component { + /** + * Create the DOM element for this class. + * + * @return The element that was created. + */ + createEl(): HTMLDivElement; + + /** + * Enqueues updates to its own DOM as well as the DOM of its + * {@link TimeTooltip} child. + * + * @param seekBarRect + * The `ClientRect` for the {@link SeekBar} element. + * + * @param seekBarPoint + * A number from 0 to 1, representing a horizontal reference point + * from the left edge of the {@link SeekBar} + */ + update(seekBarRect: ClientRect, seekBarPoint: number): void; + } + + const MouseTimeDisplay: { + prototype: MouseTimeDisplay; + + /** + * Creates an instance of this class. + * + * @param player + * The {@link Player} that this class should be attached to. + * + * @param [options] + * The key/value store of player options. + */ + new (player: Player, options?: ComponentOptions): MouseTimeDisplay + }; + + /** + * An instance of the `Player` class is created when any of the Video.js setup methods + * are used to initialize a video. + * + * After an instance has been created it can be accessed globally in two ways: + * 1. By calling `videojs('example_video_1');` + * 2. By using it directly via `videojs.players.example_video_1;` + */ + interface Player extends Component { + bigPlayButton: Button; + + controlBar: ControlBar; + + errorDisplay: ModalDialog; + + loadingSpinner: Component; + + options_: PlayerOptions; + + userActivity_: boolean; + + userActive_: boolean; + + /** + * A getter/setter for the `Player`'s aspect ratio. + * + * @param [ratio] + * The value to set the `Player's aspect ratio to. + * + * @return - The current aspect ratio of the `Player` when getting. + * - undefined when setting + */ + aspectRatio(ratio: string): void; + + aspectRatio(): string; + + /** + * Get or set the autoplay option. When this is a boolean it will + * modify the attribute on the tech. When this is a string the attribute on + * the tech will be removed and `Player` will handle autoplay on loadstarts. + * + * @param [value] + * - true: autoplay using the browser behavior + * - false: do not autoplay + * - 'play': call play() on every loadstart + * - 'muted': call muted() then play() on every loadstart + * - 'any': call play() on every loadstart. if that fails call muted() then play(). + * - *: values other than those listed here will be set `autoplay` to true + * + * @return The current value of autoplay when getting + */ + autoplay(value?: boolean): void; + + autoplay(): boolean; + + /** + * Create a remote {@link TextTrack} and an {@link HTMLTrackElement}. It will + * automatically removed from the video element whenever the source changes, unless + * manualCleanup is set to false. + * + * @param options + * Options to pass to {@link HTMLTrackElement} during creation. See + * {@link HTMLTrackElement} for object properties that you should use. + * + * @param [manualCleanup=true] if set to false, the TextTrack will be + * + * @return the HTMLTrackElement that was created and added + * to the HtmlTrackElementList and the remote + * TextTrackList + */ + addRemoteTextTrack(options: TextTrackOptions, manualCleanup: boolean): HTMLTrackElement; + + /** + * A helper method for adding a {@link TextTrack} to our + * {@link TextTrackList}. + * + * In addition to the W3C settings we allow adding additional info through options. + * + * @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack + * + * @param [kind] + * the kind of TextTrack you are adding + * + * @param [label] + * the label to give the TextTrack label + * + * @param [language] + * the language to set on the TextTrack + * + * @return the TextTrack that was added or undefined + * if there is no tech + */ + addTextTrack(kind?: string, label?: string, language?: string): void; + + /** + * Get a TimeRange object with an array of the times of the video + * that have been downloaded. If you just want the percent of the + * video that's been downloaded, use bufferedPercent. + * + * @see [Buffered Spec]{@link http://dev.w3.org/html5/spec/video.html#dom-media-buffered} + * + * @return A mock TimeRange object (following HTML spec) + */ + buffered(): TimeRange; + + /** + * Get the ending time of the last buffered time range + * This is used in the progress bar to encapsulate all time ranges. + * + * @return The end of the last buffered time range + */ + bufferedEnd(): number; + + /** + * Get the percent (as a decimal) of the video that's been downloaded. + * This method is not a part of the native HTML video API. + * + * @return A decimal between 0 and 1 representing the percent + * that is buffered 0 being 0% and 1 being 100% + */ + bufferedPercent(): number; + + /** + * Check whether the player can play a given mimetype + * + * @see https://www.w3.org/TR/2011/WD-html5-20110113/video.html#dom-navigator-canplaytype + * + * @param type + * The mimetype to check + * + * @return 'probably', 'maybe', or '' (empty string) + */ + canPlayType(type: string): 'probably' | 'maybe' | ''; + + cancelFullScreen(): Player; + + /** + * Get or set whether or not the controls are showing. + * + * @fires Player#controlsenabled + * + * @param [bool] + * - true to turn controls on + * - false to turn controls off + * + * @return The current value of controls when getting + */ + controls(bool?: boolean): void; + + controls(): boolean; + + /** + * Create the `Player`'s DOM element. + * + * @return The DOM element that gets created. + */ + createEl(): Element; + + /** + * Creates a simple modal dialog (an instance of the {@link ModalDialog} + * component) that immediately overlays the player with arbitrary + * content and removes itself when closed. + * + * @param content + * Same as {@link ModalDialog#content}'s param of the same name. + * The most straight-forward usage is to provide a string or DOM + * element. + * + * @param [options] + * Extra options which will be passed on to the {@link ModalDialog}. + * @check + * @return the {@link ModalDialog} that was created + */ + createModal(content: string | (() => any) | Element | any[], options: any): ModalDialog; + + /** + * Returns the current source object. + * + * @return The current source object + */ + currentSource(): Tech.SourceObject; + + /** + * Returns all of the current source objects. + * + * @return The current source objects + */ + currentSources(): Tech.SourceObject[]; + + /** + * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4 + * Can be used in conjunction with `currentType` to assist in rebuilding the current source object. + * + * @return The current source + */ + currentSrc(): string; + + /** + * Get or set the current time (in seconds) + * + * @param [seconds] + * The time to seek to in seconds + * + * @return - the current time in seconds when getting + */ + currentTime(seconds: number): void; + + currentTime(): number; + + /** + * Get the current source type e.g. video/mp4 + * This can allow you rebuild the current source object so that you could load the same + * source and tech later + * + * @return The source MIME type + */ + currentType(): string; + + /** + * Get the current defaultMuted state, or turn defaultMuted on or off. defaultMuted + * indicates the state of muted on initial playback. + * + * ```js + * var myPlayer = videojs('some-player-id'); + * + * myPlayer.src("http://www.example.com/path/to/video.mp4"); + * + * // get, should be false + * console.log(myPlayer.defaultMuted()); + * // set to true + * myPlayer.defaultMuted(true); + * // get should be true + * console.log(myPlayer.defaultMuted()); + * ``` + * + * @param [defaultMuted] + * - true to mute + * - false to unmute + * + * @return - true if defaultMuted is on and getting + * - false if defaultMuted is off and getting + * - A reference to the current player when setting + */ + defaultMuted(defaultMuted: boolean): void; + + defaultMuted(): boolean; + + /** + * Gets or sets the current default playback rate. A default playback rate of + * 1.0 represents normal speed and 0.5 would indicate half-speed playback, for instance. + * defaultPlaybackRate will only represent what the initial playbackRate of a video was, not + * not the current playbackRate. + * + * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-defaultplaybackrate + * + * @param [rate] + * New default playback rate to set. + * + * @return - The default playback rate when getting or 1.0 + * - the player when setting + */ + defaultPlaybackRate(rate: number): Player; + + defaultPlaybackRate(): boolean; + + /** + * A getter/setter for the `Player`'s width & height. + * + * @param dimension + * This string can be: + * - 'width' + * - 'height' + * + * @param [value] + * Value for dimension specified in the first argument. + * + * @return The dimension arguments value when getting (width/height). + */ + dimension(dimension: 'width' | 'height', value: number): void; + + dimension(dimension: 'width' | 'height'): number; + + /** + * An instance of the `Player` class is created when any of the Video.js setup methods + * are used to initialize a video. + * + * After an instance has been created it can be accessed globally in two ways: + * 1. By calling `videojs('example_video_1');` + * 2. By using it directly via `videojs.players.example_video_1;` + */ + dispose(): void; + + /** + * Normally gets the length in time of the video in seconds; + * in all but the rarest use cases an argument will NOT be passed to the method + * + * > **NOTE**: The video must have started loading before the duration can be + * known, and in the case of Flash, may not be known until the video starts + * playing. + * + * + * @fires Player#durationchange + * + * @param [seconds] + * The duration of the video to set in seconds + * + * @return - The duration of the video in seconds when getting + */ + duration(seconds: number): void; + + duration(): number; + + /** + * A getter/setter/toggler for the vjs-fluid `className` on the `Player`. + * + * @param [bool] + * - A value of true adds the class. + * - A value of false removes the class. + * - No value will toggle the fluid class. + * + * @return - The value of fluid when getting. + * - `undefined` when setting. + */ + fluid(bool: boolean): void; + + fluid(): boolean; + + /** + * Get object for cached values. + * + * @return get the current object cache + */ + getCache(): any; + + /** + * Gets available media playback quality metrics as specified by the W3C's Media + * Playback Quality API. + * + * @see [Spec]{@link https://wicg.github.io/media-playback-quality} + * + * @return An object with supported media playback quality metrics or undefined if there + * is no tech or the tech does not support it. + */ + getVideoPlaybackQuality(): any; + + /** + * When fullscreen isn't supported we can stretch the + * video container to as wide as the browser will let us. + * + * @fires Player#enterFullWindow + */ + enterFullWindow(): void; + + /** + * Set or get the current MediaError + * + * @fires Player#error + * + * @param [err] + * A MediaError or a string/number to be turned + * into a MediaError + * + * @return The current MediaError when getting (or null) + */ + error(err: MediaError | string | number): void; + + error(): MediaError | null; + + /** + * Return the video to its normal size after having been in full screen mode + * + * @fires Player#fullscreenchange //noinspection JSUnresolvedVariable + */ + exitFullscreen(): Player; + + /** + * Exit full window + * + * @fires Player#exitFullWindow + */ + exitFullWindow(): void; + + /** + * Reports whether or not a player has a plugin available. + * + * This does not report whether or not the plugin has ever been initialized + * on this player. For that, [usingPlugin]{@link Player#usingPlugin}. + * + * @param name + * The name of a plugin. + * + * @return Whether or not this player has the requested plugin available. + */ + hasPlugin(name: string): boolean; + + /** + * Add/remove the vjs-has-started class + * + * @fires Player#firstplay + * + * @param request + * - true: adds the class + * - false: remove the class + * + * @return the boolean value of hasStarted_ + */ + hasStarted(request: boolean): void; + + hasStarted(): boolean; + + /** + * A getter/setter for the `Player`'s height. Returns the player's configured value. + * To get the current height use `currentheight()`. + * + * @param [value] + * The value to set the `Player`'s heigth to. + * + * @return The current height of the `Player` when getting. + */ + height(value: number): void; + + height(): number; + + /** + * Gets or sets the audio flag + * + * @param bool + * - true signals that this is an audio player + * - false signals that this is not an audio player + * + * @return The current value of isAudio when getting + */ + isAudio(bool: boolean): void; + + isAudio(): boolean; + + /** + * Check if the player is in fullscreen mode or tell the player that it + * is or is not in fullscreen mode. + * + * > NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official + * property and instead document.fullscreenElement is used. But isFullscreen is + * still a valuable property for internal player workings. + * + * @param [isFS] + * Set the players current fullscreen state + * + * @return - true if fullscreen is on and getting + * - false if fullscreen is off and getting + */ + isFullscreen(isFS: boolean): void; + + isFullscreen(): boolean; + + /** + * The player's language code + * NOTE: The language should be set in the player options if you want the + * the controls to be built with a specific language. Changing the language + * later will not update controls text. + * + * @param [code] + * the language code to set the player to + * + * @return The current language code when getting + */ + language(code: string): void; + + language(): string; + + /** + * Get the player's language dictionary + * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time + * Languages specified directly in the player options have precedence + * + * @return An array of of supported languages + */ + languages(): string[]; + + languageSwitch(options: any): void; + + /** + * Begin loading the src data. + */ + load(): void; + + /** + * Get or set the loop attribute on the video element. + * + * @param [value] + * - true means that we should loop the video + * - false means that we should not loop the video + * + * @return The current value of loop when getting + */ + loop(value?: boolean): void; + + loop(): string; + + /** + * Get the current muted state, or turn mute on or off + * + * @param [muted] + * - true to mute + * - false to unmute + * + * @return - true if mute is on and getting + * - false if mute is off and getting + */ + muted(muted: boolean): void; + + muted(): boolean; + + /** + * Pause the video playback + * @check + * @return A reference to the player object this function was called on + */ + pause(): Player; + + /** + * Check if the player is paused or has yet to play + * + * @return - false: if the media is currently playing + * - true: if media is not currently playing + */ + paused(): boolean; + + /** + * Attempt to begin playback at the first opportunity. + * @check + * @return Returns a `Promise` only if the browser returns one and the player + * is ready to begin playback. For some browsers and all non-ready + * situations, this will return `undefined`. + */ + play(): Player; + + /** + * Gets or sets the current playback rate. A playback rate of + * 1.0 represents normal speed and 0.5 would indicate half-speed + * playback, for instance. + * + * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate + * + * @param [rate] + * New playback rate to set. + * + * @return The current playback rate when getting or 1.0 + */ + playbackRate(rate?: number): void; + + playbackRate(): number; + + /** + * Get a TimeRange object representing the current ranges of time that the user + * has played. + * @check + * @return A time range object that represents all the increments of time that have + * been played. + */ + played(): any; + + /** + * Set or unset the playsinline attribute. + * Playsinline tells the browser that non-fullscreen playback is preferred. + * + * @param [value] + * - true means that we should try to play inline by default + * - false means that we should use the browser's default playback mode, + * which in most cases is inline. iOS Safari is a notable exception + * and plays fullscreen by default. + * + * @return - the current value of playsinline + * - the player when setting + * + * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline} + */ + playsinline(value: boolean): Player; + + playsinline(): string; + + /** + * Get or set the poster image source url + * + * @fires Player#posterchange + * + * @param [src] + * Poster image source URL + * + * @return The current value of poster when getting + */ + poster(src: string): void; + + poster(): string; + + /** + * Get or set the preload attribute + * + * @param [value] + * - true means that we should preload + * - false means that we should not preload + * + * @return The preload attribute value when getting + */ + preload(value?: boolean): string; + + /** + * Calculates how much time is left in the video. Not part + * of the native video API. + * + * @return The time remaining in seconds + */ + remainingTime(): number; + + /** + * A remaining time function that is intented to be used when + * the time is to be displayed directly to the user. + * + * @return The rounded time remaining in seconds + */ + remainingTimeDisplay(): number; + + /** + * Remove a remote {@link TextTrack} from the respective + * {@link TextTrackList} and {@link HtmlTrackElementList}. + * + * @param track + * Remote {@link TextTrack} to remove + * + * @return does not return anything + */ + removeRemoteTextTrack(track: HTMLTrackElement): void; + + /** + * Increase the size of the video to full screen + * In some browsers, full screen is not supported natively, so it enters + * "full window mode", where the video fills the browser window. + * In browsers and devices that support native full screen, sometimes the + * browser's default controls will be shown, and not the Video.js custom skin. + * This includes most mobile devices (iOS, Android) and older versions of + * Safari. + * + * @fires Player#fullscreenchange + */ + requestFullScreen(): Player; + + /** + * Report user activity + * + * @param event + * Event object + */ + reportUserActivity(event: any): void; + + /** + * Reset the player. Loads the first tech in the techOrder, + * and calls `reset` on the tech`. + */ + reset(): void; + + /** + * Select source based on tech-order or source-order + * Uses source-order selection if `options.sourceOrder` is truthy. Otherwise, + * defaults to tech-order selection + * + * @param sources + * The sources for a media asset + * + * @return Object of source and tech order or false + */ + selectSource(sources: any[]): any; + + /** + * Returns whether or not the user is "scrubbing". Scrubbing is + * when the user has clicked the progress bar handle and is + * dragging it along the progress bar. + * + * @param [isScrubbing] + * whether the user is or is not scrubbing + * + * @return The value of scrubbing when getting + */ + scrubbing(isScrubbing: boolean): void; + + scrubbing(): boolean; + + /** + * Get or set the video source. + * + * @param [source] + * A SourceObject, an array of SourceObjects, or a string referencing + * a URL to a media source. It is _highly recommended_ that an object + * or array of objects is used here, so that source selection + * algorithms can take the `type` into account. + * + * If not provided, this method acts as a getter. + * + * @return If the `source` argument is missing, returns the current source + * URL. Otherwise, returns nothing/undefined. + */ + src(source: string | Tech.SourceObject | Tech.SourceObject[]): void; + + src(): string; + + /** + * Check if current tech can support native fullscreen + * (e.g. with built in controls like iOS, so not our flash swf) + * + * @return if native fullscreen is supported + */ + supportsFullScreen(): boolean; + + /** + * Return a reference to the current {@link Tech}. + * It will print a warning by default about the danger of using the tech directly + * but any argument that is passed in will silence the warning. + * + * @param [safety] + * Anything passed in to silence the warning + * + * @return The Tech + */ + tech(safety?: any): Tech; + + /** + * returns a JavaScript object reperesenting the current track + * information. **DOES not return it as JSON** + * + * @return Object representing the current of track info + */ + toJSON(): any; + + /** + * Get/set if user is active + * + * @fires Player#useractive + * @fires Player#userinactive + * + * @param [bool] + * - true if the user is active + * - false if the user is inactive + * + * @return The current value of userActive when getting + */ + userActive(bool: boolean): void; + + userActive(): boolean; + + /** + * Toggle native controls on/off. Native controls are the controls built into + * devices (e.g. default iPhone controls), Flash, or other techs + * (e.g. Vimeo Controls) + * **This should only be set by the current tech, because only the tech knows + * if it can support native controls** + * + * @fires Player#usingnativecontrols + * @fires Player#usingcustomcontrols + * + * @param [bool] + * - true to turn native controls on + * - false to turn native controls off + * + * @return The current value of native controls when getting + */ + usingNativeControls(bool: boolean): void; + + usingNativeControls(): boolean; + + /** + * Reports whether or not a player is using a plugin by name. + * + * For basic plugins, this only reports whether the plugin has _ever_ been + * initialized on this player. + * + * @param name + * The name of a plugin. + * + * @return Whether or not this player is using the requested plugin. + */ + usingPlugin(name: string): boolean; + + /** + * Get video height + * + * @return current video height + */ + videoHeight(): number; + + /** + * Get video width + * + * @return current video width + */ + videoWidth(): number; + + /** + * Get or set the current volume of the media + * + * @param [percentAsDecimal] + * The new volume as a decimal percent: + * - 0 is muted/0%/off + * - 1.0 is 100%/full + * - 0.5 is half volume or 50% + * + * @return The current volume as a percent when getting + */ + volume(percentAsDecimal: number): TimeRange; + + volume(): number; + + /** + * A getter/setter for the `Player`'s width. Returns the player's configured value. + * To get the current width use `currentWidth()`. + * + * @param [value] + * The value to set the `Player`'s width to. + * + * @return The current width of the `Player` when getting. + */ + width(value: number): void; + + width(): number; + } + + const Player: { + prototype: Player; + + /** + * An instance of the `Player` class is created when any of the Video.js setup methods + * are used to initialize a video. + * + * After an instance has been created it can be accessed globally in two ways: + * 1. By calling `videojs('example_video_1');` + * 2. By using it directly via `videojs.players.example_video_1;` + */ + new(player: Player, options?: PlayerOptions): Player; + + /** + * Gets tag settings + * + * @param tag + * The player tag + * @check + * @return An object containing all of the settings + * for a player tag + */ + getTagSettings(tag: Element): any; + }; + + interface PlayerOptions extends ComponentOptions { + aspectRatio?: string; + autoplay?: boolean; + controlBar?: ControlBarOptions | false; + textTrackSettings?: TextTrackSettingsOptions; + controls?: boolean; + defaultVolume?: number; + fluid?: boolean; + height?: number; + html5?: any; + language?: string; + languages?: { [code: string]: LanguageTranslations }; + loop?: boolean; + muted?: boolean; + notSupportedMessage?: string; + playbackRates?: number[]; + plugins?: any; + poster?: string; + preload?: string; + sourceOrder?: boolean; + sources?: Tech.SourceObject[]; + src?: string; + techOrder?: string[]; + tracks?: TextTrackOptions[]; + width?: number; + } + + /** + * Parent class for all advanced plugins. + * + * @fires Player#beforepluginsetup + * @fires Player#beforepluginsetup:$name + * @fires Player#pluginsetup + * @fires Player#pluginsetup:$name + * @listens Player#dispose + * @throws {Error} + * If attempting to instantiate the base {@link Plugin} class + * directly instead of via a sub-class. + */ + interface Plugin extends EventedMixin { + player: Player; + + /** + * Disposes a plugin. + * + * Subclasses can override this if they want, but for the sake of safety, + * it's probably best to subscribe the "dispose" event. + * + * @fires Plugin#dispose + */ + dispose(): void; + + /** + * Each event triggered by plugins includes a hash of additional data with + * conventional properties. + * + * This returns that object or mutates an existing hash. + * + * @param [hash={}] + * An object to be used as event an event hash. + * + * @return An event hash object with provided properties mixed-in. + */ + getEventHash(hash?: any): Plugin.PluginEventHash; + + /** + * Handles "statechanged" events on the plugin. No-op by default, override by + * subclassing. + * + * @param e + * An event object provided by a "statechanged" event. + * + * @param e.changes + * An object describing changes that occurred with the "statechanged" + * event. + */ + handleStateChanged(e: Event): void; + + /** + * Get the version of the plugin that was set on .VERSION + */ + version(): string; + + /** + * Triggers an event on the plugin object and overrides + * {@link module:evented~EventedMixin.trigger|EventedMixin.trigger}. + * + * @param event + * An event type or an object with a type property. + * + * @param [hash={}] + * Additional data hash to merge with a + * {@link Plugin~PluginEventHash|PluginEventHash}. + * + * @return Whether or not default was prevented. + */ + trigger(event: any, hash?: any): boolean; + } + + const Plugin: { + prototype: Plugin; + + /** + * The name of the base plugin class as it is registered. + * + */ + BASE_PLUGIN_NAME: string; + + /** + * Creates an instance of this class. + * + * Sub-classes should call `super` to ensure plugins are properly initialized. + * + * @param player + * A Video.js player instance. + */ + new (player: Player): Plugin; + + /** + * De-register a Video.js plugin. + * + * @param name + * The name of the plugin to be deregistered. + */ + deregisterPlugin(name: string): void; + + /** + * Gets a plugin by name if it exists. + * + * @param name + * The name of a plugin. + * + * @return The plugin (or `undefined`). + */ + getPlugin(name: string): typeof Plugin; + + /** + * Gets a plugin's version, if available + * + * @param name + * The name of a plugin. + * + * @return The plugin's version or an empty string. + */ + getPluginVersion(name: string): string; + + /** + * Gets an object containing multiple Video.js plugins. + * + * @param [names] + * If provided, should be an array of plugin names. Defaults to _all_ + * plugin names. + * + * @return An object containing plugin(s) associated with their name(s) or + * `undefined` if no matching plugins exist). + * + * @check returning type + */ + getPlugins(names?: string[]): { [name: string]: Plugin } + + /** + * Determines if a plugin is a basic plugin (i.e. not a sub-class of `Plugin`). + * + * @param plugin + * If a string, matches the name of a plugin. If a function, will be + * tested directly. + * + * @return Whether or not a plugin is a basic plugin. + */ + isBasic(plugin: string | (() => any)): boolean + /** + * Register a Video.js plugin. + * + * @param name + * The name of the plugin to be registered. Must be a string and + * must not match an existing plugin or a method on the `Player` + * prototype. + * + * @param plugin + * A sub-class of `Plugin` or a function for basic plugins. + * + * @return For advanced plugins, a factory function for that plugin. For + * basic plugins, a wrapper function that initializes the plugin. + */ + registerPlugin(name: string, plugin: (this: Player, options: any) => T): () => T; + registerPlugin(name: string, plugin: T): () => T; + }; + + namespace Plugin { + interface PluginEventHash { + /** + * For basic plugins, the return value of the plugin function. For + * advanced plugins, the plugin instance on which the event is fired. + */ + instance: Plugin; + /** + * The name of the plugin. + */ + name: string; + /** + * For basic plugins, the plugin function. For advanced plugins, the + * plugin class/constructor. + */ + plugin: string; + } + } + + interface ProgressControl extends Component { + /** + * Create the `Component`'s DOM element + * + * @return The element that was created. + */ + createEl(): HTMLDivElement; + + /** + * Disable all controls on the progress control and its children + */ + disable(): void; + + /** + * Enable all controls on the progress control and its children + */ + enable(): void; + + /** + * Are controls are currently enabled for this progress control. + * + * @return true if controls are enabled, false otherwise + */ + enabled(): boolean; + + /** + * Handle `mousedown` or `touchstart` events on the `ProgressControl`. + * + * @param event + * `mousedown` or `touchstart` event that triggered this function + * + * @listens mousedown + * @listens touchstart + */ + handleMouseDown(event: EventTarget.Event): void; + + /** + * When the mouse moves over the `ProgressControl`, the pointer position + * gets passed down to the `MouseTimeDisplay` component. + * + * @param event + * The `mousemove` event that caused this function to run. + * + * @listen mousemove + */ + handleMouseMove(event: EventTarget.Event): void; + + /** + * Handle `mousemove` or `touchmove` events on the `ProgressControl`. + * + * @param event + * `mousedown` or `touchstart` event that triggered this function + * + * @listens mousemove + * @listens touchmove + */ + handleMouseSeek(event: EventTarget.Event): void; + + /** + * Handle `mouseup` or `touchend` events on the `ProgressControl`. + * + * @param event + * `mouseup` or `touchend` event that triggered this function. + * + * @listens touchend + * @listens mouseup + */ + handleMouseUp(event: EventTarget.Event): void; + } + + const ProgressControl: { + prototype: ProgressControl; + + /** + * Creates an instance of this class. + * + * @param player + * The `Player` that this class should be attached to. + * + * @param [options] + * The key/value store of player options. + */ + new (player: Player, options?: ComponentOptions): ProgressControl; + }; + + interface Representation { + id: string; + width: number; + height: number; + bitrate: number; + + enabled(): boolean; + + enabled(enabled: boolean): void; + } + + /** + * Seek bar and container for the progress bars. Uses {@link PlayProgressBar} + * as its `bar`. + */ + interface SeekBar extends Slider { + /** + * Create the `Component`'s DOM element + * + * @return The element that was created. + */ + createEl(): HTMLDivElement; + + /** + * Disable controls for this slider if they are enabled + */ + disable(): void; + + /** + * Enable controls for this slider if they are disabled + */ + enable(): void; + + /** + * Toggles the playback state of the player + * This gets called when enter or space is used on the seekbar + * + * @param event + * The `keydown` event that caused this function to be called + * + */ + handleAction(event: EventTarget.Event): void; + + /** + * We want the seek bar to be full on ended + * no matter what the actual internal values are. so we force it. + * + * @param [event] + * The `timeupdate` or `ended` event that caused this to run. + * + * @listens Player#ended + */ + handleEnded(event: EventTarget.Event): void; + + /** + * Called when this SeekBar has focus and a key gets pressed down. By + * default it will call `this.handleAction` when the key is space or enter. + * + * @param event + * The `keydown` event that caused this function to be called. + * + * @listens keydown + */ + handleKeyPress(event: EventTarget.Event): void; + + /** + * Handle mouse down on seek bar + * + * @param event + * The `mousedown` event that caused this to run. + * + * @listens mousedown + */ + handleMouseDown(event: EventTarget.Event): void; + + /** + * Handle mouse move on seek bar + * + * @param event + * The `mousemove` event that caused this to run. + * + * @listens mousemove + */ + handleMouseMove(event: EventTarget.Event): void; + + /** + * Handle mouse up on seek bar + * + * @param event + * The `mouseup` event that caused this to run. + * + * @listens mouseup + */ + handleMouseUp(event: EventTarget.Event): void; + + /** + * Get the percentage of media played so far. + * + * @return The percentage of media played so far (0 to 1). + */ + getPercent(): number; + + /** + * Move more quickly fast forward for keyboard-only users + */ + stepForward(): void; + + /** + * Move more quickly rewind for keyboard-only users + */ + stepBack(): void; + + /** + * Update the seek bar's UI. + * + * @listens Player#timeupdate + * + * @return The current percent at a number from 0-1 + */ + update(): number; + } + + const SeekBar: { + prototype: SeekBar; + + /** + * Creates an instance of this class. + * + * @param player + * The `Player` that this class should be attached to. + * + * @param [options] + * The key/value store of player options. + */ + new (player: Player, options?: SliderOptions): SeekBar; + }; + + /** + * The base functionality for a slider. Can be vertical or horizontal. + * For instance the volume bar or the seek bar on a video is a slider. + */ + interface Slider extends Component { + options_: SliderOptions; + + /** + * Enable controls for this slider if they are disabled + */ + enable(): void; + + /** + * Are controls are currently enabled for this slider or not. + * + * @return true if controls are enabled, false otherwise + */ + enabled(): boolean; + + /** + * Disable controls for this slider if they are enabled + */ + disable(): void; + + /** + * Create the `Slider`s DOM element. + * + * @param type + * Type of element to create. + * + * @param [props={}] + * List of properties in Object form. + * + * @param [attributes={}] + * list of attributes in Object form. + * + * @return The element that gets created. + */ + createEl(type: string, props?: any, attributes?: any): Element; + + /** + * Handle `mousedown` or `touchstart` events on the `Slider`. + * + * @param event + * `mousedown` or `touchstart` event that triggered this function + * + * @listens mousedown + * @listens touchstart + * @fires Slider#slideractive + */ + handleMouseDown(event: EventTarget.Event): void; + + /** + * Handle the `mousemove`, `touchmove`, and `mousedown` events on this `Slider`. + * The `mousemove` and `touchmove` events will only only trigger this function during + * `mousedown` and `touchstart`. This is due to {@link Slider#handleMouseDown} and + * {@link Slider#handleMouseUp}. + * + * @param event + * `mousedown`, `mousemove`, `touchstart`, or `touchmove` event that triggered + * this function + * + * @listens mousemove + * @listens touchmove + */ + handleMouseMove(event: EventTarget.Event): void; + + /** + * Handle `mouseup` or `touchend` events on the `Slider`. + * + * @param event + * The `mouseup` event that caused this to run. + * + * @listens touchend + * @listens mouseup + * @fires Slider#sliderinactive + */ + handleMouseUp(event: EventTarget.Event): void; + + /** + * Update the progress bar of the `Slider`. + * + * @return The percentage of progress the progress bar represents as a + * number from 0 to 1. + */ + update(): number; + + /** + * Calculate distance for slider + * + * @param event + * The event that caused this function to run. + * + * @return The current position of the Slider. + * - position.x for vertical `Slider`s + * - position.y for horizontal `Slider`s + */ + calculateDistance(event: EventTarget.Event): number; + + /** + * Handle a `focus` event on this `Slider`. + * + * @listens focus + */ + handleFocus(): void; + + /** + * Handle a `focus` event on this `Slider`. + * + * @listens focus + */ + handleFocus(): void; + + /** + * Handle a `blur` event on this `Slider`. + * + * @listens blur + */ + handleBlur(): void; + + /** + * Listener for click events on slider, used to prevent clicks + * from bubbling up to parent elements like button menus. + * + * @param event + * Event that caused this object to run + */ + handleClick(event: EventTarget.Event): void; + + /** + * Get/set if slider is horizontal for vertical + * + * @param [bool] + * - true if slider is vertical, + * - false is horizontal + * + * @return - true if slider is vertical, and getting + * - false if the slider is horizontal, and getting + */ + vertical(bool: boolean): void; + + vertical(): boolean; + } + + const Slider: { + prototype: Slider; + + /** + * Create an instance of this class + * + * @param player + * The `Player` that this class should be attached to. + * + * @param [options] + * The key/value store of player options. + */ + new (player: Player, options?: SliderOptions): Slider; + }; + + interface SliderOptions extends ComponentOptions { + /** + * Set property names to bar to match with the child Slider class is looking for + */ + barName?: string; + + /** + * Set a horizontal or vertical class on the slider depending on the slider type + */ + vertical?: boolean; + } + + /** + * Just an empty spacer element that can be used as an append point for plugins, etc. + * Also can be used to create space between elements when necessary. + */ + interface Spacer extends Component { + /** + * Builds the default DOM `className`. + * + * @return The DOM `className` for this object. + */ + buildCSSClass(): string; + + /** + * Create the `Component`'s DOM element + * + * @return The element that was created. + */ + createEl(): HTMLDivElement; + } + + const Spacer: { + prototype: Spacer; + + /** + * Creates an instance of this class. + * + * @param player + * The `Player` that this class should be attached to. + * + * @param [options] + * The key/value store of player options. + * + * @param [ready] + * Function that gets called when the `Component` is ready. + */ + new (player: Player, options?: ComponentOptions, ready?: Component.ReadyCallback): Spacer; + }; + + interface Tech extends Component { + /** + * Boolean indicating whether the `Tech` supports fullscreen resize control. + * Resizing plugins using request fullscreen reloads the plugin + * + * @default + */ + featuresFullscreenResize: boolean; + + /** + * Boolean indicating whether the `Tech` supports muting volume. + * + * @default + */ + featuresMuteControl: boolean; + + /** + * Boolean indicating whether the `Tech` supports the native `TextTrack`s. + * This will help us integrate with native `TextTrack`s if the browser supports them. + * + * @default + */ + featuresNativeTextTracks: boolean; + + /** + * Boolean indicating whether the `Tech` supports changing the speed at which the video + * plays. Examples: + * - Set player to play 2x (twice) as fast + * - Set player to play 0.5x (half) as fast + * + * @default + */ + featuresPlaybackRate: boolean; + + /** + * Boolean indicating whether the `Tech` supports the `progress` event. This is currently + * not triggered by video-js-swf. This will be used to determine if + * {@link Tech#manualProgressOn} should be called. + * + * @default + */ + featuresProgressEvents: boolean; + + /** + * Boolean indicating whether the `Tech` supports the `sourceset` event. + * + * A tech should set this to `true` and then use {@link Tech#triggerSourceset} + * to trigger a {@link Tech#event:sourceset} at the earliest time after getting + * a new source. + * + * @default + */ + featuresSourceset: boolean; + + /** + * Boolean indicating whether the `Tech` supports the `timeupdate` event. This is currently + * not triggered by video-js-swf. This will be used to determine if + * {@link Tech#manualTimeUpdates} should be called. + * + * @default + */ + featuresTimeupdateEvents: boolean; + + /** + * Boolean indicating whether the `Tech` supports volume control. + * + * @default + */ + featuresVolumeControl: boolean; + + /** + * Creates a remote text track object and returns an html track element. + * + * > Note: This can be an emulated {@link HTMLTrackElement} or a native one. + * + * @param options + * See {@link Tech#createRemoteTextTrack} for more detailed properties. + * + * @param [manualCleanup=true] + * - When false: the TextTrack will be automatically removed from the video + * element whenever the source changes + * - When True: The TextTrack will have to be cleaned up manually + * + * @return An Html Track Element. + * + * @deprecated The default functionality for this function will be equivalent + * to "manualCleanup=false" in the future. The manualCleanup parameter will + * also be removed. + */ + addRemoteTextTrack(options: TextTrackOptions, manualCleanup: true): HTMLTrackElement; + + /** + * Create and returns a remote {@link TextTrack} object. + * + * @param kind + * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata) + * + * @param [label] + * Label to identify the text track + * + * @param [language] + * Two letter language abbreviation + * + * @return The TextTrack that gets created. + */ + addTextTrack(kind: string, label: string, language: string): TextTrack; + + /** + * Emulate TextTracks using vtt.js if necessary + * + * @fires Tech#vttjsloaded + * @fires Tech#vttjserror + */ + addWebVttScript_(): void; + + /** + * Get the {@link AudioTrackList} + * + * @return Tech.prototype.audioTracks + */ + audioTracks(): TrackList; + + /** + * Get and create a `TimeRange` object for buffering. + * + * @return The time range object that was created. + */ + buffered(): any; + + /** + * Get the percentage of the current video that is currently buffered. + * + * @return A number from 0 to 1 that represents the decimal percentage of the + * video that is buffered. + * + */ + bufferedPercent(): number; + + /** + * Check if the tech can support the given mime-type. + * + * The base tech does not support any type, but source handlers might + * overwrite this. + * + * @param type + * The mimetype to check for support + * + * @return 'probably', 'maybe', or empty string + * + * @see [Spec]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType} + */ + canPlayType(type: string): string; + + /** + * Remove any TextTracks added via addRemoteTextTrack that are + * flagged for automatic garbage collection + */ + cleanupAutoTextTracks(): void; + + /** + * Clear out a single `TrackList` or an array of `TrackLists` given their names. + * + * > Note: Techs without source handlers should call this between sources for `video` + * & `audio` tracks. You don't want to use them between tracks! + * + * @param types + * TrackList names to clear, valid names are `video`, `audio`, and + * `text`. + */ + clearTracks(types: string | string[]): void; + + /** + * Create an emulated TextTrack for use by addRemoteTextTrack + * + * This is intended to be overridden by classes that inherit from + * Tech in order to create native or custom TextTracks. + * + * @param options + * The object should contain the options to initialize the TextTrack with. + * + * @param [options.kind] + * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata). + * + * @param [options.label]. + * Label to identify the text track + * + * @param [options.language] + * Two letter language abbreviation. + * + * @return The track element that gets created. + */ + createRemoteTextTrack(options: TextTrackOptions): HTMLTextAreaElement; + + /** + * Turn off all event polyfills, clear the `Tech`s {@link AudioTrackList}, + * {@link VideoTrackList}, and {@link TextTrackList}, and dispose of this Tech. + * + * @fires Component#dispose + */ + dispose(): void; + + /** + * Emulate texttracks + * + */ + emulateTextTracks(): void; + + /** + * Get or set an error on the Tech. + * + * @param [err] + * Error to set on the Tech + * + * @return The current error object on the tech, or null if there isn't one. + */ + error(err: MediaError): MediaError | null; + + /** + * Gets available media playback quality metrics as specified by the W3C's Media + * Playback Quality API. + * + * @see [Spec]{@link https://wicg.github.io/media-playback-quality} + * + * @return An object with supported media playback quality metrics + */ + getVideoPlaybackQuality(): any; + + /** + * Turn on listeners for {@link VideoTrackList}, {@link {AudioTrackList}, and + * {@link TextTrackList} events. + * + * This adds {@link EventTarget~EventListeners} for `addtrack`, and `removetrack`. + * + * @fires Tech#audiotrackchange + * @fires Tech#videotrackchange + * @fires Tech#texttrackchange + */ + initTrackListeners(): void; + + manualProgressOff(): void; + + /** + * Polyfill the `progress` event for browsers that don't support it natively. + * + * @see {@link Tech#trackProgress} + */ + manualProgressOn(): void; + + /** + * Turn off the polyfill for `progress` events that was created in + * {@link Tech#manualProgressOn} + */ + manualTimeUpdatesOff(): void; + + /** + * Polyfill the `timeupdate` event for browsers that don't support it. + * + * @see {@link Tech#trackCurrentTime} + */ + manualTimeUpdatesOn(): void; + + /** + * Update our internal duration on a `durationchange` event by calling + * {@link Tech#duration}. + * + * @param event + * The `durationchange` event that caused this to run. + * + * @listens Tech#durationchange + */ + onDurationChange(event: Event): void; + + /** + * Attempt to force override of native audio tracks. + * + * @param override - If set to true native audio will be overridden, + * otherwise native audio will potentially be used. + */ + overrideNativeAudioTracks(override: boolean): void; + + /** + * Attempt to force override of native video tracks. + * + * @param override - If set to true native video will be overridden, + * otherwise native video will potentially be used. + */ + overrideNativeVideoTracks(override: boolean): void; + + /** + * Returns the `TimeRange`s that have been played through for the current source. + * + * > NOTE: This implementation is incomplete. It does not track the played `TimeRange`. + * It only checks whether the source has played at all or not. + * + * @return - A single time range if this video has played + * - An empty set of ranges if not. + */ + played(): any; + + /** + * A method to check for the presence of the 'playsinline'
  • {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}Restricted