diff --git a/types/connect-redis/connect-redis-tests.ts b/types/connect-redis/connect-redis-tests.ts index 3c50074117..11cd583a74 100644 --- a/types/connect-redis/connect-redis-tests.ts +++ b/types/connect-redis/connect-redis-tests.ts @@ -2,3 +2,9 @@ import * as connectRedis from "connect-redis"; import * as session from "express-session"; let RedisStore = connectRedis(session); +const store = new RedisStore({ + host: 'localhost', + port: 6379, + logErrors: error => console.warn(error), + scanCount: 80, +}); diff --git a/types/connect-redis/index.d.ts b/types/connect-redis/index.d.ts index f66314a083..b5084609a2 100644 --- a/types/connect-redis/index.d.ts +++ b/types/connect-redis/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for connect-redis // Project: https://npmjs.com/package/connect-redis // Definitions by: Xavier Stouder +// Albert Kurniawan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -32,6 +33,8 @@ declare module "connect-redis" { prefix?: string; unref?: boolean; serializer?: Serializer | JSON; + logErrors?: boolean | ((error: string) => void); + scanCount?: number; } interface Serializer { stringify: Function; diff --git a/types/d3-sankey/d3-sankey-tests.ts b/types/d3-sankey/d3-sankey-tests.ts index c270011528..abf61775b8 100644 --- a/types/d3-sankey/d3-sankey-tests.ts +++ b/types/d3-sankey/d3-sankey-tests.ts @@ -7,7 +7,7 @@ */ import * as d3Sankey from 'd3-sankey'; -import {select, Selection} from 'd3-selection'; +import { select, Selection } from 'd3-selection'; import { Link } from 'd3-shape'; // --------------------------------------------------------------------------- @@ -18,38 +18,44 @@ import { Link } from 'd3-shape'; // the Sankey layout generator. The latter are reflected in the SankeyNode and SankeyLink interfaces provided // by the definitions file interface SNodeExtra { - nodeId: number; - name: string; + name: string; +} + +interface SNodeExtraCustomId { + nodeId: string; + name: string; } interface SLinkExtra { - uom: string; + uom: string; } // For convenience type SNode = d3Sankey.SankeyNode; +type SNodeCustomId = d3Sankey.SankeyNode; type SLink = d3Sankey.SankeyLink; +type SLinkCustomId = d3Sankey.SankeyLink; interface DAG { - customNodes: SNode[]; - customLinks: SLink[]; + customNodes: SNode[]; + customLinks: SLink[]; } -const graph: DAG = { +interface DAGCustomId { + customNodes: SNodeCustomId[]; + customLinks: SLinkCustomId[]; +} + +const graphDefault: DAG = { customNodes: [{ - nodeId: 0, name: "node0" }, { - nodeId: 1, name: "node1" }, { - nodeId: 2, name: "node2" }, { - nodeId: 3, name: "node3" }, { - nodeId: 4, name: "node4" }], customLinks: [{ @@ -90,6 +96,61 @@ const graph: DAG = { }] }; +const graphCustomId: DAGCustomId = { + customNodes: [{ + nodeId: "n0", + name: "node0" + }, { + nodeId: "n1", + name: "node1" + }, { + nodeId: "n2", + name: "node2" + }, { + nodeId: "n3", + name: "node3" + }, { + nodeId: "n4", + name: "node4" + }], + customLinks: [{ + source: "n0", + target: "n2", + value: 2, + uom: 'Widget(s)' + }, { + source: "n1", + target: "n2", + value: 2, + uom: 'Widget(s)' + }, { + source: "n1", + target: "n3", + value: 2, + uom: 'Widget(s)' + }, { + source: "n0", + target: "n4", + value: 2, + uom: 'Widget(s)' + }, { + source: "n2", + target: "n3", + value: 2, + uom: 'Widget(s)' + }, { + source: "n2", + target: "n4", + value: 2, + uom: 'Widget(s)' + }, { + source: "n3", + target: "n4", + value: 4, + uom: 'Widget(s)' + }] +}; + let sNodes: SNode[]; let sLinks: SLink[]; @@ -109,6 +170,7 @@ let sGraph: d3Sankey.SankeyGraph; let slgDefault: d3Sankey.SankeyLayout, {}, {}> = d3Sankey.sankey(); let slgDAG: d3Sankey.SankeyLayout = d3Sankey.sankey(); +let slgDAGCustomId: d3Sankey.SankeyLayout = d3Sankey.sankey(); // --------------------------------------------------------------------------- // NodeWidth @@ -175,6 +237,54 @@ slgDAG = slgDAG.iterations(40); num = slgDAG.iterations(); +// --------------------------------------------------------------------------- +// Node Id +// --------------------------------------------------------------------------- + +// Set ----------------------------------------------------------------------- + +slgDAGCustomId = slgDAGCustomId.nodeId((d) => { + const node: SNodeCustomId = d; + return d.nodeId; +}); + +// Get ----------------------------------------------------------------------- + +let nodeIdAccessor: (d: SNodeCustomId) => string | number; + +nodeIdAccessor = slgDAGCustomId.nodeId(); + +// --------------------------------------------------------------------------- +// Node Alignment +// --------------------------------------------------------------------------- + +// Set ----------------------------------------------------------------------- + +declare const testNode: SNode; + +// Test pre-defined alignment functions +slgDAG = slgDAG.nodeAlign(d3Sankey.sankeyLeft); +num = d3Sankey.sankeyLeft(testNode, 10); +slgDAG = slgDAG.nodeAlign(d3Sankey.sankeyRight); +num = d3Sankey.sankeyRight(testNode, 10); +slgDAG = slgDAG.nodeAlign(d3Sankey.sankeyCenter); +num = d3Sankey.sankeyCenter(testNode, 10); +slgDAG = slgDAG.nodeAlign(d3Sankey.sankeyJustify); +num = d3Sankey.sankeyJustify(testNode, 10); + +// Test custom +slgDAG = slgDAG.nodeAlign((node, maxN) => { + const n: SNode = node; + const mN: number = maxN; + return node.depth || 0; +}); + +// Get ----------------------------------------------------------------------- + +let nodeAlignmentFn: (d: SNode, n: number) => number; + +nodeAlignmentFn = slgDAG.nodeAlign(); + // --------------------------------------------------------------------------- // Nodes // --------------------------------------------------------------------------- @@ -182,7 +292,7 @@ num = slgDAG.iterations(); // Set ----------------------------------------------------------------------- // Use array and test return type for chainability -slgDAG = slgDAG.nodes(graph.customNodes); +slgDAG = slgDAG.nodes(graphDefault.customNodes); // Use accessor function and test return type for chainability slgDAG = slgDAG.nodes(d => d.customNodes); @@ -198,7 +308,7 @@ let nodesAccessor: (d: DAG) => SNode[] = slgDAG.nodes(); // Set ----------------------------------------------------------------------- // test return type for chainability -slgDAG = slgDAG.links(graph.customLinks); +slgDAG = slgDAG.links(graphDefault.customLinks); // Use accessor function and test return type for chainability slgDAG = slgDAG.links(d => d.customLinks); @@ -211,9 +321,9 @@ let linksAccessor: (d: DAG) => SLink[] = slgDAG.links(); // Compute Initial Layout // --------------------------------------------------------------------------- -sGraph = slgDAG(graph); +sGraph = slgDAG(graphDefault); // With additional arguments, although here unused. -sGraph = slgDAG(graph, "foo", 50); +sGraph = slgDAG(graphDefault, "foo", 50); // --------------------------------------------------------------------------- // Update Layout @@ -255,7 +365,6 @@ let sNode = sNodes[0]; // User-specified extra properties: -num = sNode.nodeId; str = sNode.name; // Sankey Layout calculated (if layout has been run, otherwise undefined): @@ -267,6 +376,7 @@ numMaybe = sNode.y1; numMaybe = sNode.value; numMaybe = sNode.index; numMaybe = sNode.depth; +numMaybe = sNode.height; let linksArrMaybe: SLink[] | undefined; @@ -290,10 +400,10 @@ num = sLink.value; // layout(...) was invoked, the source and target nodes may be numbers // objects without the Sankey layout coordinates, or objects with calculated // information -let numOrSankeyNode: number | SNode; +let numStringOrSankeyNode: number | string | SNode; -numOrSankeyNode = sLink.source; -numOrSankeyNode = sLink.target; +numStringOrSankeyNode = sLink.source; +numStringOrSankeyNode = sLink.target; // Sankey Layout calculated (if layout has been run, otherwise undefined): diff --git a/types/d3-sankey/index.d.ts b/types/d3-sankey/index.d.ts index 55c2934c13..46a80b2671 100644 --- a/types/d3-sankey/index.d.ts +++ b/types/d3-sankey/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for D3JS d3-sankey module 0.6 +// Type definitions for D3JS d3-sankey module 0.7 // Project: https://github.com/d3/d3-sankey/ // Definitions by: Tom Wanzek , Alex Ford // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 0.6 +// Last module patch version validated against: 0.7 import { Link } from 'd3-shape'; @@ -50,6 +50,10 @@ export interface SankeyNodeMinimal { /** - * Link's source node. For convenience, when initializing a Sankey layout, + * Link's source node. For convenience, when initializing a Sankey layout using the default node id accessor, * source may be the zero-based index of the corresponding node in the nodes array - * returned by the nodes accessor of the Sankey layout generator rather than object references. + * returned by the nodes accessor of the Sankey layout generator rather than object references. Alternatively, + * the Sankey layout can be configured with a custom node ID accessor to resolve the source node of the link upon initialization. * * Once the Sankey generator is invoked to return the Sankey graph object, * the numeric index will be replaced with the corresponding source node object. */ - source: number | SankeyNode; + source: number | string | SankeyNode; /** - * Link's target node. For convenience, when initializing a Sankey layout, + * Link's target node. For convenience, when initializing a Sankey layout using the default node id accessor, * target may be the zero-based index of the corresponding node in the nodes array - * returned by the nodes accessor of the Sankey layout generator rather than object references. + * returned by the nodes accessor of the Sankey layout generator rather than object references. Alternatively, + * the Sankey layout can be configured with a custom node ID accessor to resolve the target node of the link upon initialization. * * Once the Sankey generator is invoked to return the Sankey graph object, * the numeric index will be replaced with the corresponding target node object. */ - target: number | SankeyNode; + target: number | string | SankeyNode; /** * Link's numeric value */ @@ -244,6 +250,34 @@ export interface SankeyLayout Array>): this; + /** + * Return the current node id accessor. + * The default accessor is a function being passed in a Sankey layout node and returning its numeric node.index. + */ + nodeId(): (node: SankeyNode) => string | number; + /** + * Set the node id accessor to the specified function and return this Sankey layout generator. + * + * The default accessor is a function being passed in a Sankey layout node and returning its numeric node.index. + * The default id accessor allows each link’s source and target to be specified as a zero-based index into the nodes array. + * + * @param nodeId A node id accessor function being passed a node in the Sankey graph and returning its id. + */ + nodeId(nodeId: (node: SankeyNode) => string | number): this; + + /** + * Return the current node alignment method, which defaults to d3.sankeyLeft. + */ + nodeAlign(): (node: SankeyNode, n: number) => number; + /** + * Set the node alignment method the specified function and return this Sankey layout generator. + * + * @param nodeAlign A node alignment function which is evaluated for each input node in order, + * being passed the current node and the total depth n of the graph (one plus the maximum node.depth), + * and must return an integer between 0 and n - 1 that indicates the desired horizontal position of the node in the generated Sankey diagram. + */ + nodeAlign(nodeAlign: (node: SankeyNode, n: number) => number): this; + /** * Return the current node width, which defaults to 24. */ @@ -346,6 +380,44 @@ export function sankey(): SankeyLayout; +/** + * Compute the horizontal node position of a node in a Sankey layout with left alignment. + * Returns (node.depth) to indicate the desired horizontal position of the node in the generated Sankey diagram. + * + * @param node Sankey node for which to calculate the horizontal node position. + * @param n Total depth n of the graph (one plus the maximum node.depth) + */ +export function sankeyLeft(node: SankeyNode<{}, {}>, n: number): number; + +/** + * Compute the horizontal node position of a node in a Sankey layout with right alignment. + * Returns (n - 1 - node.height) to indicate the desired horizontal position of the node in the generated Sankey diagram. + * + * @param node Sankey node for which to calculate the horizontal node position. + * @param n Total depth n of the graph (one plus the maximum node.depth) + */ +export function sankeyRight(node: SankeyNode<{}, {}>, n: number): number; + +/** + * Compute the horizontal node position of a node in a Sankey layout with center alignment. + * Like d3.sankeyLeft, except that nodes without any incoming links are moved as right as possible. + * Returns an integer between 0 and n - 1 that indicates the desired horizontal position of the node in the generated Sankey diagram. + * + * @param node Sankey node for which to calculate the horizontal node position. + * @param n Total depth n of the graph (one plus the maximum node.depth) + */ +export function sankeyCenter(node: SankeyNode<{}, {}>, n: number): number; + +/** + * Compute the horizontal node position of a node in a Sankey layout with justified alignment. + * Like d3.sankeyLeft, except that nodes without any outgoing links are moved to the far right. + * Returns an integer between 0 and n - 1 that indicates the desired horizontal position of the node in the generated Sankey diagram. + * + * @param node Sankey node for which to calculate the horizontal node position. + * @param n Total depth n of the graph (one plus the maximum node.depth) + */ +export function sankeyJustify(node: SankeyNode<{}, {}>, n: number): number; + /** * Get a horizontal link shape suitable for a Sankey diagram. * Source and target accessors are pre-configured and work with the diff --git a/types/hubot/hubot-tests.ts b/types/hubot/hubot-tests.ts new file mode 100644 index 0000000000..9c5e832bc2 --- /dev/null +++ b/types/hubot/hubot-tests.ts @@ -0,0 +1,14 @@ +import * as Hubot from "hubot"; + +const brain = new Hubot.Brain(); +brain; // $ExpectType Brain +brain.userForName('someone'); // $ExpectType any + +const robot = new Hubot.Robot( + 'src/adapters', + 'slack', + false, + 'hubot', +); +robot; // $ExpectType Robot +robot.hear(/hello/, () => null); // $ExpectType void diff --git a/types/hubot/index.d.ts b/types/hubot/index.d.ts new file mode 100644 index 0000000000..e0a809f69a --- /dev/null +++ b/types/hubot/index.d.ts @@ -0,0 +1,49 @@ +// Type definitions for hubot 2.19 +// Project: https://github.com/github/hubot +// Definitions by: Dirk Gadsden +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Hubot { + class Brain { + userForId(id: any): any; + userForName(name: string): any; + } + + class User { + id: any; + name: string; + } + + class Message { + user: User; + text: string; + id: string; + } + + class Response { + match: RegExpMatchArray; + message: Message; + + constructor(robot: Robot, message: Message, match: RegExpMatchArray); + send(...strings: string[]): void; + reply(...strings: string[]): void; + random(items: T[]): T; + } + + type ListenerCallback = (response: Response) => void; + + class Robot { + brain: Brain; + + constructor(adapterPath: string, adapter: string, httpd: boolean, name: string, alias?: string); + hear(regex: RegExp, callback: ListenerCallback): void; + hear(regex: RegExp, options: any, callback: ListenerCallback): void; + respond(regex: RegExp, callback: ListenerCallback): void; + respond(regex: RegExp, options: any, callback: ListenerCallback): void; + } +} + +// Compatibility with CommonJS syntax exported by Hubot's CoffeeScript. +// tslint:disable-next-line export-just-namespace +export = Hubot; +export as namespace Hubot; diff --git a/types/hubot/tsconfig.json b/types/hubot/tsconfig.json new file mode 100644 index 0000000000..0e3faa4c35 --- /dev/null +++ b/types/hubot/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "hubot-tests.ts" + ] +} diff --git a/types/hubot/tslint.json b/types/hubot/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hubot/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jasmine-given/index.d.ts b/types/jasmine-given/index.d.ts new file mode 100644 index 0000000000..70a23d7e07 --- /dev/null +++ b/types/jasmine-given/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for jasmine-given 2.6 +// Project: https://github.com/searls/jasmine-given +// Definitions by: Shai Reznik +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function Given(func: () => void): void; +declare function When(func: () => void): void; +declare function Then(func: () => void): void; +declare function And(func: () => void): void; +declare function Invariant(func: () => void): void; diff --git a/types/jasmine-given/jasmine-given-tests.ts b/types/jasmine-given/jasmine-given-tests.ts new file mode 100644 index 0000000000..8a994ecbbe --- /dev/null +++ b/types/jasmine-given/jasmine-given-tests.ts @@ -0,0 +1,9 @@ +Given(() => { }); + +When(() => { }); + +Then(() => { }); + +And(() => { }); + +Invariant(() => {}); diff --git a/types/jasmine-given/tsconfig.json b/types/jasmine-given/tsconfig.json new file mode 100644 index 0000000000..cb1571590b --- /dev/null +++ b/types/jasmine-given/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jasmine-given-tests.ts" + ] +} \ No newline at end of file diff --git a/types/jasmine-given/tslint.json b/types/jasmine-given/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/jasmine-given/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/jquery/index.d.ts b/types/jquery/index.d.ts index a8b2895d6b..cedea8354e 100644 --- a/types/jquery/index.d.ts +++ b/types/jquery/index.d.ts @@ -699,6 +699,14 @@ interface JQueryCoordinates { top: number; } +/** + * The interface used to specify the properties parameter in css() + */ +type cssPropertySetter = (index: number, value?: string) => string | number; +interface JQueryCssProperties { + [propertyName: string]: string | number | cssPropertySetter; +} + /** * Elements in the array returned by serializeArray() */ @@ -1707,7 +1715,7 @@ interface JQuery { * @param properties An object of property-value pairs to set. * @see {@link https://api.jquery.com/css/#css-properties} */ - css(properties: Object): JQuery; + css(properties: JQueryCssProperties): JQuery; /** * Get the current computed height for the first element in the set of matched elements. diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index d2d58aa2a2..4b6fc4e0db 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -1065,6 +1065,9 @@ function test_css() { $('div.example').css('width', function (index) { return index * 50; }); + $('div.example').css('width', function (index, style) { + return style.length > 0 ? style : index * 50; + }); $("p").mouseover(function () { $(this).css("color", "red"); }); diff --git a/types/massive/index.d.ts b/types/massive/index.d.ts index 1ed6b62ac6..67be093bb0 100644 --- a/types/massive/index.d.ts +++ b/types/massive/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for massive 3.x +// Type definitions for massive 3.0 // Project: https://github.com/dmfay/massive-js.git // Definitions by: Pascal Birchler // Clarence Ho @@ -10,7 +10,7 @@ export = massive; declare function massive( - connection: object | string, + connection: massive.ConnectionInfo | string, loaderConfig?: object, driverConfig?: object): Promise; @@ -26,17 +26,55 @@ declare namespace massive { fallback_application_name?: boolean; } + interface QueryOptions { + columns?: string[]; + limit?: number; + offset?: number; + only?: boolean; + order?: string[]; + orderBody?: boolean; + build?: boolean; + document?: boolean; + single?: boolean; + stream?: boolean; + } + + interface SearchCriteria { + fields: string[]; + term: string; + } + + interface Table { + find(criteria: object | {}, queryOptions?: QueryOptions): Promise; + findOne(criteria: number | object, queryOptions?: QueryOptions): Promise; + count(criteria: object): Promise; + where(query: string, params: any[] | object): Promise; + search(criteria: SearchCriteria, queryOptions?: QueryOptions): Promise; + save(data: object): Promise; + insert(data: object): Promise; + update(dataOrCriteria: object, changesMap?: object): Promise; + destroy(criteria: object): Promise; + } + + interface Document { + countDoc(criteria: object): Promise; + findDoc(criteria: number | string| object): Promise; + searchDoc(criteria: SearchCriteria): Promise; + saveDoc(doc: object): Promise; + modify(docId: number | string, doc: object, fieldName?: string): Promise; + } + interface Database { attach(ctor: any, ...sources: any[]): Promise; detach(entity: string, collection: string): void; reload(): void; query(query: any, params: any, options: any): Promise; - saveDoc(collection: any, doc: any): any; + saveDoc(collectionName: string, doc: object): Promise; createDocumentTable(path: any): Promise; getObject(path: any, collection: any): object; dropTable(table: string, options: any): void; createSchema(schemaName: string): void; dropSchema(schemaName: string, options: any): void; - [name: string]: any; + run(query: string, params: any[] | object): Promise; } } diff --git a/types/material-ui/index.d.ts b/types/material-ui/index.d.ts index 7308c0f089..560b21f2ca 100644 --- a/types/material-ui/index.d.ts +++ b/types/material-ui/index.d.ts @@ -832,6 +832,7 @@ declare namespace __MaterialUI { className?: string; openIcon?: React.ReactNode; closeIcon?: React.ReactNode; + iconStyle?: React.CSSProperties; } export class CardHeader extends React.Component { } diff --git a/types/promisify-supertest/index.d.ts b/types/promisify-supertest/index.d.ts index 5c0ea6251a..9f59afdb89 100644 --- a/types/promisify-supertest/index.d.ts +++ b/types/promisify-supertest/index.d.ts @@ -2,7 +2,7 @@ // Project: https://www.npmjs.com/package/promisify-supertest // Definitions by: Leo Liang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.2 // Mostly copy-pasted from supertest.d.ts diff --git a/types/prosemirror-model/index.d.ts b/types/prosemirror-model/index.d.ts index ff281cb2f9..3ede724248 100644 --- a/types/prosemirror-model/index.d.ts +++ b/types/prosemirror-model/index.d.ts @@ -236,8 +236,8 @@ declare module "prosemirror-model" { export class Schema { constructor(spec: SchemaSpec) spec: SchemaSpec; - nodes: Object; - marks: Object; + nodes: {[key: string]: NodeType}; + marks: {[key: string]: MarkType}; cached: Object; topNodeType: NodeType; node(type: string | NodeType, attrs?: Object, content?: Fragment | ProsemirrorNode | ProsemirrorNode[], marks?: Mark[]): ProsemirrorNode @@ -252,8 +252,8 @@ declare module "prosemirror-model" { } export class DOMSerializer { constructor(nodes: Object, marks: Object) - nodes: Object; - marks: Object; + nodes: {[key: string]: NodeType}; + marks: {[key: string]: MarkType}; serializeFragment(fragment: Fragment, options?: Object): DocumentFragment serializeNode(node: ProsemirrorNode, options?: Object): Node static renderSpec(doc: Document, structure: DOMOutputSpec): { dom: Node, contentDOM?: Node } @@ -263,4 +263,4 @@ declare module "prosemirror-model" { } -} \ No newline at end of file +} diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index 79d1b1f6cf..4d6be6138f 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -587,8 +587,8 @@ declare namespace R { * Returns the first element of the list which matches the predicate, or `undefined` if no * element matches. */ - find(fn: (a: T) => boolean, list: T[]): T; - find(fn: (a: T) => boolean): (list: T[]) => T; + find(fn: (a: T) => boolean, list: T[]): T | undefined; + find(fn: (a: T) => boolean): (list: T[]) => T | undefined; /** @@ -602,8 +602,8 @@ declare namespace R { * Returns the last element of the list which matches the predicate, or `undefined` if no * element matches. */ - findLast(fn: (a: T) => boolean, list: T[]): T; - findLast(fn: (a: T) => boolean): (list: T[]) => T; + findLast(fn: (a: T) => boolean, list: T[]): T | undefined; + findLast(fn: (a: T) => boolean): (list: T[]) => T | undefined; /** * Returns the index of the last element of the list which matches the predicate, or diff --git a/types/rangy/index.d.ts b/types/rangy/index.d.ts index b6615b9aad..4a3afc08a1 100644 --- a/types/rangy/index.d.ts +++ b/types/rangy/index.d.ts @@ -31,6 +31,7 @@ interface RangyRange extends Range { equals(range:RangyRange):boolean; refresh():any; select():any; + toCharacterRange(containerNode:Node):{start:number, end:number}; } interface RangySelection extends Selection { diff --git a/types/rangy/rangy-tests.ts b/types/rangy/rangy-tests.ts index de2ec468f0..3b177a46b3 100644 --- a/types/rangy/rangy-tests.ts +++ b/types/rangy/rangy-tests.ts @@ -74,6 +74,7 @@ function testRangyRange() { rangyRange.splitBoundaries(); assertString(rangyRange.toHtml()); assertRangyRange(rangyRange.union(rangyRange)); + let characterRange:{start:number, end:number} = rangyRange.toCharacterRange(new Node); } function testSelection() { diff --git a/types/react-intl/index.d.ts b/types/react-intl/index.d.ts index 9777987c8d..f52fbc1cbc 100644 --- a/types/react-intl/index.d.ts +++ b/types/react-intl/index.d.ts @@ -1,22 +1,22 @@ -// Type definitions for react-intl 2.2 +// Type definitions for react-intl 2.3 // Project: http://formatjs.io/react/ // Definitions by: Bruno Grieder , // Christian Droulers , // Fedor Nezhivoi , // Till Wolff , // Karol Janyst , -// Brian Houser +// Brian Houser , +// Krister Kari // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 declare namespace ReactIntl { - type DateSource = Date | string | number; interface Locale { locale: string; - fields?: { [key: string]: string }, - pluralRuleFunction?: (n: number, ord: boolean) => string; + fields?: { [key: string]: string }; + pluralRuleFunction?(n: number, ord: boolean): string; } type LocaleData = Locale[]; @@ -26,7 +26,7 @@ declare namespace ReactIntl { withRef?: boolean; } - type ComponentConstructor

= React.ComponentClass

| React.StatelessComponent

+ type ComponentConstructor

= React.ComponentClass

| React.StatelessComponent

; function injectIntl

(component: ComponentConstructor

, options?: InjectIntlConfig): React.ComponentClass

& { WrappedComponent: ComponentConstructor

}; @@ -34,7 +34,7 @@ declare namespace ReactIntl { function addLocaleData(data: Locale[] | Locale): void; interface Messages { - [key: string]: FormattedMessage.MessageDescriptor + [key: string]: FormattedMessage.MessageDescriptor; } function defineMessages(messages: T): T; @@ -64,19 +64,19 @@ declare namespace ReactIntl { const intlShape: IntlShape; interface InjectedIntl { - formatDate: (value: DateSource, options?: FormattedDate.PropsBase) => string; - formatTime: (value: DateSource, options?: FormattedTime.PropsBase) => string; - formatRelative: (value: DateSource, options?: FormattedRelative.PropsBase & { now?: any }) => string; - formatNumber: (value: number, options?: FormattedNumber.PropsBase) => string; - formatPlural: (value: number, options?: FormattedPlural.Base) => keyof FormattedPlural.PropsBase; - formatMessage: (messageDescriptor: FormattedMessage.MessageDescriptor, values?: {[key: string]: string | number}) => string; - formatHTMLMessage: (messageDescriptor: FormattedMessage.MessageDescriptor, values?: {[key: string]: string}) => string; + formatDate(value: DateSource, options?: FormattedDate.PropsBase): string; + formatTime(value: DateSource, options?: FormattedTime.PropsBase): string; + formatRelative(value: DateSource, options?: FormattedRelative.PropsBase & { now?: any }): string; + formatNumber(value: number, options?: FormattedNumber.PropsBase): string; + formatPlural(value: number, options?: FormattedPlural.Base): keyof FormattedPlural.PropsBase; + formatMessage(messageDescriptor: FormattedMessage.MessageDescriptor, values?: {[key: string]: string | number | boolean | Date}): string; + formatHTMLMessage(messageDescriptor: FormattedMessage.MessageDescriptor, values?: {[key: string]: string | number | boolean | Date}): string; locale: string; formats: any; messages: { [id: string]: string }; defaultLocale: string; defaultFormats: any; - now : () => number; + now(): number; } interface InjectedIntlProps { @@ -90,9 +90,9 @@ declare namespace ReactIntl { } namespace FormattedDate { - export interface PropsBase extends IntlComponent.DateTimeFormatProps {} + type PropsBase = IntlComponent.DateTimeFormatProps; - export interface Props extends PropsBase { + interface Props extends PropsBase { value: DateSource; } } @@ -100,16 +100,16 @@ declare namespace ReactIntl { class FormattedDate extends React.Component { } namespace FormattedTime { - export interface PropsBase extends IntlComponent.DateTimeFormatProps {} + type PropsBase = IntlComponent.DateTimeFormatProps; - export interface Props extends PropsBase { + interface Props extends PropsBase { value: DateSource; } } class FormattedTime extends React.Component { } namespace FormattedRelative { - export interface PropsBase { + interface PropsBase { /* * one of "second", "minute", "hour", "day", "month" or "year" */ @@ -123,7 +123,7 @@ declare namespace ReactIntl { initialNow?: any; } - export interface Props extends PropsBase { + interface Props extends PropsBase { value: DateSource; } } @@ -131,13 +131,13 @@ declare namespace ReactIntl { class FormattedRelative extends React.Component { } namespace FormattedMessage { - export interface MessageDescriptor { + interface MessageDescriptor { id: string; description?: string; defaultMessage?: string; } - export interface Props extends MessageDescriptor { + interface Props extends MessageDescriptor { values?: {[key: string]: string | number | JSX.Element}; tagName?: string; } @@ -147,26 +147,25 @@ declare namespace ReactIntl { class FormattedHTMLMessage extends React.Component { } namespace FormattedNumber { - export interface PropsBase extends Intl.NumberFormatOptions { + interface PropsBase extends Intl.NumberFormatOptions { format?: string; } - export interface Props extends PropsBase { + interface Props extends PropsBase { value: number; } } class FormattedNumber extends React.Component { } - namespace FormattedPlural { - export interface Base { + interface Base { /* * one of "cardinal" (default) | "ordinal" */ style?: "cardinal" | "ordinal"; } - export interface PropsBase extends Base { + interface PropsBase extends Base { other?: any; zero?: any; one?: any; @@ -175,15 +174,14 @@ declare namespace ReactIntl { many?: any; } - export interface Props extends PropsBase { + interface Props extends PropsBase { value: number; } } class FormattedPlural extends React.Component { } - namespace IntlProvider { - export interface Props { + interface Props { locale?: string; formats?: any; messages?: any; @@ -196,12 +194,12 @@ declare namespace ReactIntl { class IntlProvider extends React.Component { getChildContext(): { intl: InjectedIntl; - } + }; } } declare module "react-intl" { - export = ReactIntl + export = ReactIntl; } declare module "react-intl/locale-data/af" { diff --git a/types/react-intl/react-intl-tests.tsx b/types/react-intl/react-intl-tests.tsx index 8b21ef8651..1550aafcbe 100644 --- a/types/react-intl/react-intl-tests.tsx +++ b/types/react-intl/react-intl-tests.tsx @@ -3,8 +3,8 @@ * Updated by Fedor Nezhivoi */ -import * as React from "react" -import * as reactMixin from "react-mixin" +import * as React from "react"; +import * as reactMixin from "react-mixin"; import { IntlProvider, @@ -21,14 +21,14 @@ import { FormattedPlural, FormattedDate, FormattedTime -} from "react-intl" +} from "react-intl"; import reactIntlEn = require("react-intl/locale-data/en"); addLocaleData(reactIntlEn); interface SomeComponentProps { - className: string + className: string; } const SomeFunctionalComponentWithIntl: React.ComponentClass = injectIntl(({ @@ -51,7 +51,10 @@ const SomeFunctionalComponentWithIntl: React.ComponentClass const formattedNumber = formatNumber(123, { format: "short" }); const formattedPlural = formatPlural(1, { style: "ordinal" }); const formattedMessage = formatMessage({ id: "hello", defaultMessage: "Hello {name}!" }, { name: "Roger" }); - const formattedMessagePlurals = formatMessage({ id: "hello", defaultMessage: "Hello {name} you have {unreadCount, number} {unreadCount, plural, one {message} other {messages}}!" }, { name: "Roger", unreadCount: 123 }); + const formattedMessagePlurals = formatMessage({ + id: "hello", + defaultMessage: "Hello {name} you have {unreadCount, number} {unreadCount, plural, one {message} other {messages}}!" }, + { name: "Roger", unreadCount: 123 }); const formattedHTMLMessage = formatHTMLMessage({ id: "hello", defaultMessage: "Hello {name}!" }, { name: "Roger" }); return (

@@ -71,8 +74,17 @@ class SomeComponent extends React.Component{name}!" }, { name: "Roger" }); + const formattedHTMLMessageNumber = intl.formatHTMLMessage({ id: "hello", defaultMessage: "Hello {num}!" }, { num: 1 }); + const formattedHTMLMessageDate = intl.formatHTMLMessage({ id: "hello", defaultMessage: "Hello {date}!" }, { date: new Date() }); + const formattedHTMLMessageBool = intl.formatHTMLMessage({ id: "hello", defaultMessage: "Hello {bool}!" }, { bool: true }); return
{formattedNum} )} -
+
; } } @@ -230,14 +242,14 @@ const SomeComponentWithIntl = injectIntl(SomeComponent); class TestApp extends React.Component<{}, {}> { render(): React.ReactElement<{}> { const definedMessages = defineMessages({ - "sup": { + sup: { id: "sup", defaultMessage: "Hai mom" } }); const messages = { - "hello": "Hello, {name}!" + hello: "Hello, {name}!" }; return ( @@ -250,9 +262,9 @@ class TestApp extends React.Component<{}, {}> { const intlProvider = new IntlProvider({ locale: 'en' }, {}); const { intl } = intlProvider.getChildContext(); -const wrappedComponent = +const wrappedComponent = ; export default { TestApp, SomeComponent: SomeComponentWithIntl -} +}; diff --git a/types/react-intl/tslint.json b/types/react-intl/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-intl/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index d2bf9882de..5f86c8ed58 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -274,6 +274,14 @@ export type NavigationAction = | NavigationStackAction | NavigationTabAction; +export namespace NavigationActions { + function init(options?: NavigationInitAction): NavigationInitAction; + function navigate(options: NavigationNavigateAction): NavigationNavigateAction; + function reset(options: NavigationResetAction): NavigationResetAction; + function back(options?: NavigationBackAction): NavigationBackAction; + function setParams(options: NavigationSetParamsAction): NavigationSetParamsAction; +} + export type NavigationRouteConfig = T & { navigationOptions?: NavigationScreenConfig, path?: string, diff --git a/types/sharp-timer/index.d.ts b/types/sharp-timer/index.d.ts new file mode 100644 index 0000000000..928a47eed7 --- /dev/null +++ b/types/sharp-timer/index.d.ts @@ -0,0 +1,52 @@ +// Type definitions for sharp-timer 0.3 +// Project: https://github.com/afractal/SharpTimer +// Definitions by: Hermes Gjini - afractal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type ElapsedEvent = () => void; +export type ElapsingEvent = (intervalValue: number) => void; + +export class Timer { + private _enabled; + private _stopped; + private _interval; + private _intervalElapsedEvents; + private _intervalElapsingEvents; + constructor(interval: number); + readonly enabled: boolean; + readonly stopped: boolean; + interval: number; + start(): void; + pause(): void; + resume(): void; + stop(): void; + onIntervalElapsed(intervalElapsedHandler: ElapsedEvent): void; + onIntervalElapsing(intervalElapsingHandler: ElapsingEvent): void; + toString(): string; + private getDoubleDigit(number); + private checkForValidInterval(interval); +} + +export class Stopwatch { + private _isRunning; + private _elapsedMilliseconds; + private _startedTimeInMillis; + private _intervalIds; + private static readonly millisPerSecond; + private static readonly millisPerMinute; + private static readonly millisPerHour; + constructor(); + readonly elapsed: string; + readonly elapsedMilliseconds: number; + readonly elapsedSeconds: number; + readonly elapsedMinutes: number; + readonly elapsedHours: number; + readonly isRunning: boolean; + static startNew(): Stopwatch; + start(): void; + stop(): void; + reset(): void; + restart(): void; + dispose(): void; + private getDoubleDigit(num); +} diff --git a/types/sharp-timer/sharp-timer-tests.ts b/types/sharp-timer/sharp-timer-tests.ts new file mode 100644 index 0000000000..5d8976e474 --- /dev/null +++ b/types/sharp-timer/sharp-timer-tests.ts @@ -0,0 +1,10 @@ +import { Timer, Stopwatch } from 'sharp-timer'; + +let timer = new Timer(10); + +timer.onIntervalElapsing(i => { }); +timer.onIntervalElapsed(() => { + timer.stop(); +}); + +timer.start(); diff --git a/types/sharp-timer/tsconfig.json b/types/sharp-timer/tsconfig.json new file mode 100644 index 0000000000..ffaeaf9685 --- /dev/null +++ b/types/sharp-timer/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sharp-timer-tests.ts" + ] +} diff --git a/types/sharp-timer/tslint.json b/types/sharp-timer/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/sharp-timer/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/simple-cw-node/index.d.ts b/types/simple-cw-node/index.d.ts index c73394e4b0..66aace5ddb 100644 --- a/types/simple-cw-node/index.d.ts +++ b/types/simple-cw-node/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/astronaughts/simple-cw-node // Definitions by: vvakame // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.2 import superagent = require("superagent"); // TODO 1. update superagent with generics diff --git a/types/sip.js/index.d.ts b/types/sip.js/index.d.ts index 4cb973ad10..2e3394386f 100644 --- a/types/sip.js/index.d.ts +++ b/types/sip.js/index.d.ts @@ -3,331 +3,325 @@ // Definitions by: Kir Dergachev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface SIP { - UA: { - new (configuration?: sipjs.ConfigurationParameters): sipjs.UA; - }; - URI: { - new (scheme?: string, user?: string, host?: string, port?: number, parameters?: string[], headers?: string[]): sipjs.URI; - parse(uri: string): sipjs.URI; - }; - NameAddrHeader: { - new (uri: string | sipjs.URI, displayName: string, parameters: Array<{ key: string, value: string }>): sipjs.NameAddrHeader; - parse(name_addr_header: string): sipjs.NameAddrHeader; - }; +export as namespace sipjs; + +export class URI { + scheme?: string; + user?: string; + host?: string; + port?: number; + + constructor(scheme?: string, user?: string, host?: string, port?: number, parameters?: string[], headers?: string[]); + static parse(uri: string): sipjs.URI; + + setParam(key: string, value?: string): void; + getParam(key: string): string; + hasParam(key: string): string; + deleteParam(key: string): string; + clearParams(): void; + setHeader(name: string, value: string): void; + getHeader(name: string): string[]; + hasHeader(name: string): boolean; + deleteHeader(name: string): string[]; + clearHeaders(): void; + clone(): URI; + toString(): string; } -declare namespace sipjs { - interface URI { - scheme?: string; - user?: string; - host?: string; - port?: number; +export namespace UA.EventArgs { + interface ConnectedArgs { attempts: number; } + interface UnregisteredArgs { response: string; cause: string; } + interface RegistrationFailedArgs extends UnregisteredArgs { } +} - setParam(key: string, value?: string): void; - getParam(key: string): string; - hasParam(key: string): string; - deleteParam(key: string): string; - clearParams(): void; - setHeader(name: string, value: string): void; - getHeader(name: string): string[]; - hasHeader(name: string): boolean; - deleteHeader(name: string): string[]; - clearHeaders(): void; - clone(): URI; - toString(): string; +export class UA { + constructor(configuration?: sipjs.ConfigurationParameters); + + start(): void; + stop(): void; + register(options?: ExtraHeadersOptions): UA; + unregister(options?: UnregisterOptions): void; + isRegistered(): boolean; + isConnected(): boolean; + message(target: string | URI, body: string, options?: MessageOptions): Message; + subscribe(target: string | URI, event: string, options?: SubscribeOptions): Subscription; + invite(target: string | URI, element?: InviteOptions | HTMLAudioElement | HTMLVideoElement): Session; + request(method: string, target: string | URI, options?: RequestOptions): ClientContext; + + on(name: 'connected', callback: (args: UA.EventArgs.ConnectedArgs) => void): void; + on(name: 'disconnected' | 'registered' | string, callback: () => void): void; + on(name: 'unregistered', callback: (args: UA.EventArgs.UnregisteredArgs) => void): void; + on(name: 'registrationFailed', callback: (args: UA.EventArgs.RegistrationFailedArgs) => void): void; + on(name: 'invite', callback: (session: Session) => void): void; + on(name: 'message', callback: (message: Message) => void): void; +} + +export namespace C { + namespace supported { + const REQUIRED: string; + const SUPPORTED: string; + const UNSUPPORTED: string; } - namespace UA.EventArgs { - interface ConnectedArgs { attempts: number; } - interface UnregisteredArgs { response: string; cause: string; } - interface RegistrationFailedArgs extends UnregisteredArgs { } + namespace causes { + const INVALID_TARGET: string; + const CONNECTION_ERROR: string; + const REQUEST_TIMEOUT: string; + const SIP_FAILURE_CODE: string; + } +} + +export interface Session { + startTime?: Date; + endTime?: Date; + ua?: UA; + method?: string; + mediaHandler?: WebRTC.MediaHandler; + request?: IncomingRequest | OutgoingRequest; + localIdentity?: NameAddrHeader; + remoteIdentity?: NameAddrHeader; + data: ClientContext | ServerContext; + + dtmf(tone: string | number, options?: Session.DtmfOptions): Session; + terminate(options?: Session.CommonOptions): Session; + bye(options?: Session.CommonOptions): Session; + getLocalStreams(): any[]; + getRemoteStreams(): any[]; + refer(target: string | Session, options?: ExtraHeadersOptions): Session; + mute(options?: ExtraHeadersOptions): void; + unmute(options?: ExtraHeadersOptions): void; + cancel(options?: Session.CommonOptions): void; + progress(options?: Session.ProgressOptions): void; + accept(options?: Session.AcceptOptions): void; + reject(options?: Session.CommonOptions): void; + reply(options?: Session.CommonOptions): void; + followRefer(callback: () => void): void; + + on(name: 'progress', callback: (response: IncomingResponse) => void): void; + on(name: 'accepted', callback: (data: { code: number, response: IncomingResponse }) => void): void; + on(name: 'failed' | 'rejected', callback: (response: IncomingResponse, cause: string) => void): void; + on(name: 'terminated', callback: (message: IncomingResponse, cause: string) => void): void; + on(name: 'cancel' | string, callback: () => void): void; + on(name: 'replaced', callback: (newSession: Session) => void): void; + on(name: 'dtmf', callback: (request: IncomingRequest, dtmf: Session.DTMF) => void): void; + on(name: 'muted' | 'unmuted', callback: (data: Session.Muted) => void): void; + on(name: 'refer' | 'bye', callback: (request: IncomingRequest) => void): void; +} + +export namespace Session { + interface DtmfOptions extends ExtraHeadersOptions { + duration?: number; + interToneGap?: number; } - interface UA { - start(): void; - stop(): void; - register(options?: ExtraHeadersOptions): UA; - unregister(options?: UnregisterOptions): void; - isRegistered(): boolean; - isConnected(): boolean; - message(target: string | URI, body: string, options?: MessageOptions): Message; - subscribe(target: string | URI, event: string, options?: SubscribeOptions): Subscription; - invite(target: string | URI, element?: InviteOptions | HTMLAudioElement | HTMLVideoElement): Session; - request(method: string, target: string | URI, options?: RequestOptions): ClientContext; - - on(name: 'connected', callback: (args: UA.EventArgs.ConnectedArgs) => void): void; - on(name: 'disconnected' | 'registered' | string, callback: () => void): void; - on(name: 'unregistered', callback: (args: UA.EventArgs.UnregisteredArgs) => void): void; - on(name: 'registrationFailed', callback: (args: UA.EventArgs.RegistrationFailedArgs) => void): void; - on(name: 'invite', callback: (session: Session) => void): void; - on(name: 'message', callback: (message: Message) => void): void; - } - - namespace UA.C { - class supported { - REQUIRED: string; - SUPPORTED: string; - UNSUPPORTED: string; - } - - class causes { - INVALID_TARGET: string; - CONNECTION_ERROR: string; - REQUEST_TIMEOUT: string; - SIP_FAILURE_CODE: string; - } - } - - interface Session { - startTime?: Date; - endTime?: Date; - ua?: UA; - method?: string; - mediaHandler?: WebRTC.MediaHandler; - request?: IncomingRequest | OutgoingRequest; - localIdentity?: NameAddrHeader; - remoteIdentity?: NameAddrHeader; - data: ClientContext | ServerContext; - - dtmf(tone: string | number, options?: Session.DtmfOptions): Session; - terminate(options?: Session.CommonOptions): Session; - bye(options?: Session.CommonOptions): Session; - getLocalStreams(): any[]; - getRemoteStreams(): any[]; - refer(target: string | Session, options?: ExtraHeadersOptions): Session; - mute(options?: ExtraHeadersOptions): void; - unmute(options?: ExtraHeadersOptions): void; - cancel(options?: Session.CommonOptions): void; - progress(options?: Session.ProgressOptions): void; - accept(options?: Session.AcceptOptions): void; - reject(options?: Session.CommonOptions): void; - reply(options?: Session.CommonOptions): void; - followRefer(callback: () => void): void; - - on(name: 'progress', callback: (response: IncomingResponse) => void): void; - on(name: 'accepted', callback: (data: { code: number, response: IncomingResponse }) => void): void; - on(name: 'failed' | 'rejected', callback: (response: IncomingResponse, cause: string) => void): void; - on(name: 'terminated', callback: (message: IncomingResponse, cause: string) => void): void; - on(name: 'cancel' | string, callback: () => void): void; - on(name: 'replaced', callback: (newSession: Session) => void): void; - on(name: 'dtmf', callback: (request: IncomingRequest, dtmf: Session.DTMF) => void): void; - on(name: 'muted' | 'unmuted', callback: (data: Session.Muted) => void): void; - on(name: 'refer' | 'bye', callback: (request: IncomingRequest) => void): void; - } - - namespace Session { - interface DtmfOptions extends ExtraHeadersOptions { - duration?: number; - interToneGap?: number; - } - - interface CommonOptions extends ExtraHeadersOptions { - status_code?: number; - reason_phrase?: string; - body?: string; - } - - interface ProgressOptions extends ExtraHeadersOptions { - rel100?: boolean; - media?: MediaConstraints; - } - - interface AcceptOptions { - RTCConstraints?: any; - media?: MediaOptions; - } - - interface DTMF extends Object {} - - interface Muted { - audio?: boolean; - video?: boolean; - } - } - - interface RenderHint { - remote?: Element; - local?: Element; - } - - interface MediaConstraints { - audio: boolean; - video: boolean; - } - - interface TurnServer { - urls?: string | string[]; - username?: string; - password?: string; - } - - namespace WebRTC { - interface Options { - stunServers?: string | string[]; - turnServers?: TurnServer | TurnServer[]; - RTCConstraints?: any; - } - - type MediaHandlerFactory = (session: Session, options: Options) => MediaHandler; - - class MediaHandler { - getLocalStreams(): any[]; - getRemoteStreams(): any[]; - render(renderHint: RenderHint): void; - - on(name: 'userMediaRequest', callback: (constraints: MediaConstraints) => void): void; - on(name: 'addStream' | 'userMedia', callback: (stream: any) => void): void; - on(name: 'userMediaFailed', callback: (error: string) => void): void; - on(name: 'iceCandidate', callback: (candidate: any) => void): void; - on( - name: 'iceGathering' | 'iceGatheringComplete' | 'iceConnection' | 'iceConnectionChecking' | 'iceConnectionConnected' | 'iceConnectionCompleted' | 'iceConnectionFailed' | - 'iceConnectionDisconnected' | 'iceConnectionClosed' | string, - callback: () => void): void; - on(name: 'dataChannel' | 'getDescription' | 'setDescription', callback: (sdpWrapper: { type: string, sdp: string }) => void): void; - } - } - - /* Parameters */ - interface ConfigurationParameters { - uri?: string; - wsServers?: string | string[] | Array<{ ws_uri: string; weigth: number }>; - allowLegacyNotifications?: boolean; - authenticationFactory?: WebRTC.MediaHandlerFactory; - authorizationUser?: string; - autostart?: boolean; - connectionRecoveryMaxInterval?: number; - connectionRecoveryMinInterval?: number; - displayName?: string; - hackCleanJitsiSdpImageattr?: boolean; - hackStripTcp?: boolean; - hackIpInContact?: boolean; - hackViaTcp?: boolean; - hackWssInTransport?: boolean; - iceCheckingTimeout?: number; - instanceId?: string; - log?: { - builtinEnabled?: boolean; - level?: number | string; - connector?(level: string, category: string, label: string, content: string): void; - }; - mediaHandlerFactory?: WebRTC.MediaHandlerFactory; - noAnswerTimeout?: number; - password?: string; - register?: boolean; - registerExpires?: number; - registrarServer?: string; - rel100?: string; - replaces?: string; - stunServers?: string | string[]; - traceSip?: boolean; - turnServers?: TurnServer | TurnServer[]; - usePreloadedRoute?: boolean; - userAgentString?: string; - wsServerMaxReconnection?: number; - wsServerReconnectionTimeout?: number; - } - - /* Options */ - interface ExtraHeadersOptions { - extraHeaders?: string[]; - } - - interface UnregisterOptions extends ExtraHeadersOptions { - all?: boolean; - } - - interface MessageOptions extends ExtraHeadersOptions { - contentType?: string; - } - - interface SubscribeOptions extends ExtraHeadersOptions { - expires?: number; - } - - interface MediaOptions { - constraints?: MediaConstraints; - stream?: any; - render?: RenderHint; - } - - interface InviteOptions extends ExtraHeadersOptions { - media?: MediaOptions; - anonymous?: boolean; - rel100?: string; - inviteWithoutSdp?: boolean; - RTCConstraints?: any; - } - - interface RequestOptions extends ExtraHeadersOptions { + interface CommonOptions extends ExtraHeadersOptions { + status_code?: number; + reason_phrase?: string; body?: string; } - /* Contexts */ - interface Message extends ClientContext { - body: string; + interface ProgressOptions extends ExtraHeadersOptions { + rel100?: boolean; + media?: MediaConstraints; } - interface Subscription extends ClientContext { - id: string; - state: string; - event: string; - dialog: string; - timers: {}; - errorCodes: number[]; - subscribe(): Subscription; - unsubscribe(): void; - close(): void; + interface AcceptOptions { + RTCConstraints?: any; + media?: MediaOptions; } - /* Context */ - interface Context { - ua: UA; - method: string; - request: OutgoingRequest; - localIdentity: NameAddrHeader; - remoteIdentity: NameAddrHeader; - data: {}; - on(name: 'progress' | 'accepted' | 'rejected' | 'failed', callback: (response: IncomingMessage, cause: string) => void): void; - on(name: 'notify', callback: (request: IncomingRequest) => void): void; - on(name: string, callback: () => void): void; - } + interface DTMF extends Object {} - interface ClientContext extends Context { - cancel(options?: { status_code?: number, reason_phrase?: string }): ClientContext; - } - - interface ServerContext extends Context { - progress(options?: Session.ProgressOptions): void; - accept(options?: Session.AcceptOptions): void; - reject(options?: Session.CommonOptions): void; - reply(options?: Session.CommonOptions): void; - } - - /* Request */ - interface Request extends Context { - } - - interface IncomingRequest extends Request { - } - - interface OutgoingRequest extends Request { - } - - interface IncomingResponse extends Request { - } - - interface IncomingMessage extends Request { - } - - /* Header */ - interface NameAddrHeader { - uri: string | URI; - displayName: string; - - setParam(key: string, value?: string): void; - getParam(key: string): string; - deleteParam(key: string): string; - clearParams(): void; + interface Muted { + audio?: boolean; + video?: boolean; } } + +export interface RenderHint { + remote?: Element; + local?: Element; +} + +export interface MediaConstraints { + audio: boolean; + video: boolean; +} + +export interface TurnServer { + urls?: string | string[]; + username?: string; + password?: string; +} + +export namespace WebRTC { + interface Options { + stunServers?: string | string[]; + turnServers?: TurnServer | TurnServer[]; + RTCConstraints?: any; + } + + type MediaHandlerFactory = (session: Session, options: Options) => MediaHandler; + + class MediaHandler { + getLocalStreams(): any[]; + getRemoteStreams(): any[]; + render(renderHint: RenderHint): void; + + on(name: 'userMediaRequest', callback: (constraints: MediaConstraints) => void): void; + on(name: 'addStream' | 'userMedia', callback: (stream: any) => void): void; + on(name: 'userMediaFailed', callback: (error: string) => void): void; + on(name: 'iceCandidate', callback: (candidate: any) => void): void; + on( + name: 'iceGathering' | 'iceGatheringComplete' | 'iceConnection' | 'iceConnectionChecking' | 'iceConnectionConnected' | 'iceConnectionCompleted' | 'iceConnectionFailed' | + 'iceConnectionDisconnected' | 'iceConnectionClosed' | string, + callback: () => void): void; + on(name: 'dataChannel' | 'getDescription' | 'setDescription', callback: (sdpWrapper: { type: string, sdp: string }) => void): void; + } +} + +/* Parameters */ +export interface ConfigurationParameters { + uri?: string; + wsServers?: string | string[] | Array<{ ws_uri: string; weigth: number }>; + allowLegacyNotifications?: boolean; + authenticationFactory?: WebRTC.MediaHandlerFactory; + authorizationUser?: string; + autostart?: boolean; + connectionRecoveryMaxInterval?: number; + connectionRecoveryMinInterval?: number; + displayName?: string; + hackCleanJitsiSdpImageattr?: boolean; + hackStripTcp?: boolean; + hackIpInContact?: boolean; + hackViaTcp?: boolean; + hackWssInTransport?: boolean; + iceCheckingTimeout?: number; + instanceId?: string; + log?: { + builtinEnabled?: boolean; + level?: number | string; + connector?(level: string, category: string, label: string, content: string): void; + }; + mediaHandlerFactory?: WebRTC.MediaHandlerFactory; + noAnswerTimeout?: number; + password?: string; + register?: boolean; + registerExpires?: number; + registrarServer?: string; + rel100?: string; + replaces?: string; + stunServers?: string | string[]; + traceSip?: boolean; + turnServers?: TurnServer | TurnServer[]; + usePreloadedRoute?: boolean; + userAgentString?: string; + wsServerMaxReconnection?: number; + wsServerReconnectionTimeout?: number; +} + +/* Options */ +export interface ExtraHeadersOptions { + extraHeaders?: string[]; +} + +export interface UnregisterOptions extends ExtraHeadersOptions { + all?: boolean; +} + +export interface MessageOptions extends ExtraHeadersOptions { + contentType?: string; +} + +export interface SubscribeOptions extends ExtraHeadersOptions { + expires?: number; +} + +export interface MediaOptions { + constraints?: MediaConstraints; + stream?: any; + render?: RenderHint; +} + +export interface InviteOptions extends ExtraHeadersOptions { + media?: MediaOptions; + anonymous?: boolean; + rel100?: string; + inviteWithoutSdp?: boolean; + RTCConstraints?: any; +} + +export interface RequestOptions extends ExtraHeadersOptions { + body?: string; +} + +/* Contexts */ +export interface Message extends ClientContext { + body: string; +} + +export interface Subscription extends ClientContext { + id: string; + state: string; + event: string; + dialog: string; + timers: {}; + errorCodes: number[]; + subscribe(): Subscription; + unsubscribe(): void; + close(): void; +} + +/* Context */ +export interface Context { + ua: UA; + method: string; + request: OutgoingRequest; + localIdentity: NameAddrHeader; + remoteIdentity: NameAddrHeader; + data: {}; + on(name: 'progress' | 'accepted' | 'rejected' | 'failed', callback: (response: IncomingMessage, cause: string) => void): void; + on(name: 'notify', callback: (request: IncomingRequest) => void): void; + on(name: string, callback: () => void): void; +} + +export interface ClientContext extends Context { + cancel(options?: { status_code?: number, reason_phrase?: string }): ClientContext; +} + +export interface ServerContext extends Context { + progress(options?: Session.ProgressOptions): void; + accept(options?: Session.AcceptOptions): void; + reject(options?: Session.CommonOptions): void; + reply(options?: Session.CommonOptions): void; +} + +/* Request */ +export interface Request extends Context { +} + +export interface IncomingRequest extends Request { +} + +export interface OutgoingRequest extends Request { +} + +export interface IncomingResponse extends Request { +} + +export interface IncomingMessage extends Request { +} + +/* Header */ +export class NameAddrHeader { + uri: string | URI; + displayName: string; + + constructor(uri: string | sipjs.URI, displayName: string, parameters: Array<{ key: string, value: string }>); + static parse(name_addr_header: string): sipjs.NameAddrHeader; + + setParam(key: string, value?: string): void; + getParam(key: string): string; + deleteParam(key: string): string; + clearParams(): void; +} diff --git a/types/sip.js/sip.js-tests.ts b/types/sip.js/sip.js-tests.ts index 23b2578194..44f61fea25 100644 --- a/types/sip.js/sip.js-tests.ts +++ b/types/sip.js/sip.js-tests.ts @@ -1,11 +1,11 @@ -declare var sip: SIP; +import * as SIP from 'sip.js'; -let ua: sipjs.UA = new sip.UA(); +let ua: SIP.UA = new SIP.UA(); -const mediaHandler = (session: sipjs.Session, options: sipjs.WebRTC.Options) => new sipjs.WebRTC.MediaHandler(); +const mediaHandler = (session: SIP.Session, options: SIP.WebRTC.Options) => new SIP.WebRTC.MediaHandler(); const logConnector = (level: string, category: string, label: string, content: string) => null; -const uaWithConfig: sipjs.UA = new sip.UA({ +const uaWithConfig: SIP.UA = new SIP.UA({ uri: "wss://uri", wsServers: ["s1", "s2"], allowLegacyNotifications: true, @@ -61,14 +61,14 @@ ua.unregister({ extraHeaders: [""], all: true }); const isConnected: boolean = ua.isConnected(); const isRegistered: boolean = ua.isRegistered(); -const message: sipjs.Message = ua.message("", "", { contentType: "" }); +const message: SIP.Message = ua.message("", "", { contentType: "" }); ua.subscribe("", "", { expires: 1, extraHeaders: [""] }); -const subscription: sipjs.Subscription = ua.subscribe(new sip.URI(), "", { expires: 1, extraHeaders: [""] }); +const subscription: SIP.Subscription = ua.subscribe(new SIP.URI(), "", { expires: 1, extraHeaders: [""] }); let session = ua.invite("", new HTMLVideoElement()); -const inviteOptions: sipjs.InviteOptions = { +const inviteOptions: SIP.InviteOptions = { media: { constraints: { audio: true, video: false }, stream: new MediaStream(), @@ -82,14 +82,14 @@ const inviteOptions: sipjs.InviteOptions = { session = ua.invite("", inviteOptions); -ua.on('connected', (args: sipjs.UA.EventArgs.ConnectedArgs) => { }); +ua.on('connected', (args: SIP.UA.EventArgs.ConnectedArgs) => { }); ua.on('disconnected', () => { }); ua.on('registered', () => { }); -ua.on('unregistered', (args: sipjs.UA.EventArgs.UnregisteredArgs) => { }); -ua.on('registrationFailed', (args: sipjs.UA.EventArgs.RegistrationFailedArgs) => { }); -ua.on('invite', (session: sipjs.Session) => { +ua.on('unregistered', (args: SIP.UA.EventArgs.UnregisteredArgs) => { }); +ua.on('registrationFailed', (args: SIP.UA.EventArgs.RegistrationFailedArgs) => { }); +ua.on('invite', (session: SIP.Session) => { session.on('progress', (response) => {}); session.on('accepted', (response) => {}); session.on('rejected', (response) => {}); }); -ua.on('message', (message: sipjs.Message) => { }); +ua.on('message', (message: SIP.Message) => { }); diff --git a/types/stripe-checkout/index.d.ts b/types/stripe-checkout/index.d.ts index 41f94f3a2c..b546ef1851 100644 --- a/types/stripe-checkout/index.d.ts +++ b/types/stripe-checkout/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Chris Wrench // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface StripeCheckoutStatic { configure(options: StripeCheckoutOptions): StripeCheckoutHandler; diff --git a/types/stripe/index.d.ts b/types/stripe/index.d.ts index cc486b5d5b..f58d5e602f 100644 --- a/types/stripe/index.d.ts +++ b/types/stripe/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for stripe 2.x +// Type definitions for stripe 3.0 // Project: https://stripe.com/ // Definitions by: Andy Hawkins // Eric J. Smith @@ -7,164 +7,184 @@ // Justin Leider // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare const Stripe: StripeStatic; +export function Stripe(stripePublicKey: string): stripe.StripeStatic; -interface StripeStatic { - applePay: StripeApplePay; - setPublishableKey(key: string): void; - validateCardNumber(cardNumber: string): boolean; - validateExpiry(month: string, year: string): boolean; - validateCVC(cardCVC: string): boolean; - cardType(cardNumber: string): StripeCardDataBrand; - getToken(token: string, responseHandler: (status: number, response: StripeCardTokenResponse) => void): void; - card: StripeCard; - createToken(data: StripeCardTokenData, responseHandler: (status: number, response: StripeCardTokenResponse) => void): void; - bankAccount: StripeBankAccount; -} +export namespace stripe { + interface StripeStatic { + elements(options?: elements.ElementsCreateOptions): elements.Elements; + createToken(element: elements.Element, options?: TokenOptions): Promise; + } -interface StripeCardTokenData { - number: string; - exp_month?: number; - exp_year?: number; - exp?: string; - cvc?: string; - name?: string; - address_line1?: string; - address_line2?: string; - address_city?: string; - address_state?: string; - address_zip?: string; - address_country?: string; -} + interface TokenOptions { + name?: string; + address_line1?: string; + address_line2?: string; + address_city?: string; + address_state?: string; + address_zip?: string; + address_country?: string; + currency?: string; + } -interface StripeTokenResponse { - id: string; - client_ip: string; - created: number; - livemode: boolean; - object: string; - type: string; - used: boolean; - error?: StripeError; -} - -interface StripeCardTokenResponse extends StripeTokenResponse { - card: StripeCard; -} - -interface StripeError { - type: string; - code: string; - message: string; - param?: string; -} - -type StripeCardDataBrand = 'Visa' | 'American Express' | 'MasterCard' | 'Discover' | 'JCB' | 'Diners Club' | 'Unknown'; - -type StripeCardDataFunding = 'credit' | 'debit' | 'prepaid' | 'unknown'; - -interface StripeCard { - object: string; - last4: string; - exp_month: number; - exp_year: number; - country?: string; - name?: string; - address_line1?: string; - address_line2?: string; - address_city?: string; - address_state?: string; - address_zip?: string; - address_country?: string; - brand?: StripeCardDataBrand; - funding?: StripeCardDataFunding; - createToken(data: StripeCardTokenData, responseHandler: (status: number, response: StripeCardTokenResponse) => void): void; - validateCardNumber(cardNumber: string): boolean; - validateExpiry(month: string, year: string): boolean; - validateCVC(cardCVC: string): boolean; -} - -interface StripeBankAccount { - createToken(params: StripeBankTokenParams, stripeResponseHandler: (status: number, response: StripeBankTokenResponse) => void): void; - validateRoutingNumber(routingNumber: number | string, countryCode: string): boolean; - validateAccountNumber(accountNumber: number | string, countryCode: string): boolean; -} - -interface StripeBankTokenParams { - country: string; - currency: string; - account_number: number | string; - routing_number?: number | string; - account_holder_name: string; - account_holder_type: string; -} - -interface StripeBankTokenResponse extends StripeTokenResponse { - bank_account: { - country: string; - bank_name: string; - last4: number; - validated: boolean; + interface Token { + id: string; object: string; - }; + bank_account?: BankAccount; + card?: Card; + client_ip: string; + created: number; + livemode: boolean; + type: string; + used: boolean; + } + + interface TokenResponse { + token?: Token; + error?: Error; + } + + interface Error { + type: string; + charge: string; + message?: string; + code?: string; + declined_code?: string; + param?: string; + } + + type statusType = 'new' | 'validated' | 'verified' | 'verification_failed' | 'errored'; + interface BankAccount { + id: string; + object: string; + account_holder_name: string; + account_holder_type: string; + bank_name: string; + country: string; + currency: string; + fingerprint: string; + last4: string; + routing_number: string; + status: statusType; + } + + type brandType = 'Visa' | 'American Express' | 'MasterCard' | 'Discover' | 'JCB' | 'Diners Club' | 'Unknown'; + type checkType = 'pass' | 'fail' | 'unavailable' | 'unchecked'; + type fundingType = 'credit' | 'debit' | 'prepaid' | 'unknown'; + type tokenizationType = 'apple_pay' | 'android_pay'; + interface Card { + id: string; + object: string; + address_city?: string; + address_country?: string; + address_line1?: string; + address_line1_check?: checkType; + address_line2?: string; + address_state?: string; + address_zip?: string; + address_zip_check?: checkType; + brand: brandType; + country: string; + currency?: string; + cvc_check?: checkType; + dynamic_last4: string; + exp_month: number; + exp_year: number; + fingerprint: string; + funding: fundingType; + last4: string; + metadata: any; + name?: string; + tokenization_method?: tokenizationType; + } + + // Container for all elements related types + namespace elements { + interface ElementsCreateOptions { + fonts?: elements.Font[]; + locale?: string; + } + + type handler = (response?: ElementChangeResponse) => void; + type eventTypes = 'blur' | 'change' | 'focus' | 'ready'; + interface Element { + // HTMLElement keeps giving this error for some reason: + // Cannot find name 'HTMLElement' + mount(domElement: string | any): void; + on(event: eventTypes, handler: handler): void; + blur(): void; + clear(): void; + unmount(): void; + update(options: ElementsOptions): void; + } + + interface ElementChangeResponse { + brand: string; + complete: boolean; + empty: boolean; + value?: { postalCode: string | number }; + error?: Error; + } + + interface ElementOptions { + fonts?: elements.Font[]; + locale?: string; + } + + type elementsType = 'card' | 'cardNumber' | 'cardExpiry' | 'cardCvc' | 'postalCode'; + interface Elements { + create(type: elementsType, options: ElementsOptions): Element; + } + + interface ElementsOptions { + classes?: { + base?: string; + complete?: string; + empty?: string; + focus?: string; + invalid?: string; + webkitAutofill?: string; + }; + hidePostalCode?: boolean; + hideIcon?: boolean; + iconStyle?: 'solid' | 'default'; + style?: { + base?: Style; + complete?: Style; + empty?: Style; + invalid?: Style; + }; + value?: string | {[objectKey: string]: string; }; + } + + interface Style extends StyleOptions { + ':hover'?: StyleOptions; + ':focus'?: StyleOptions; + '::placeholder'?: StyleOptions; + '::selection'?: StyleOptions; + ':-webkit-autofill'?: StyleOptions; + } + + interface Font { + family?: string; + src?: string; + style?: string; + unicodeRange?: string; + weight?: string; + } + + interface StyleOptions { + color?: string; + fontFamily?: string; + fontSize?: string; + fontSmoothing?: string; + fontStyle?: string; + fontVariant?: string; + iconColor?: string; + lineHeight?: string; + letterSpacing?: string; + textDecoration?: string; + textShadow?: string; + textTransform?: string; + } + } } - -interface StripeApplePay { - checkAvailability(resopnseHandler: (result: boolean) => void): void; - buildSession(data: StripeApplePayPaymentRequest, - onSuccessHandler: (result: StripeApplePaySessionResult, completion: ((value: any) => void)) => void, - onErrorHanlder: (error: { message: string }) => void): any; -} - -type StripeApplePayBillingContactField = 'postalAddress' | 'name'; -type StripeApplePayShippingContactField = StripeApplePayBillingContactField | 'phone' | 'email'; -type StripeApplePayShipping = 'shipping' | 'delivery' | 'storePickup' | 'servicePickup'; - -interface StripeApplePayPaymentRequest { - billingContact: StripeApplePayPaymentContact; - countryCode: string; - currencyCode: string; - total: StripeApplePayLineItem; - lineItems?: StripeApplePayLineItem[]; - requiredBillingContactFields?: StripeApplePayBillingContactField[]; - requiredShippingContactFields?: StripeApplePayShippingContactField[]; - shippingContact?: StripeApplePayPaymentContact; - shippingMethods?: StripeApplePayShippingMethod[]; - shippingType?: StripeApplePayShipping[]; -} - -// https://developer.apple.com/reference/applepayjs/1916082-applepay_js_data_types -interface StripeApplePayLineItem { - type: 'pending' | 'final'; - label: string; - amount: number; -} - -interface StripeApplePaySessionResult { - token: StripeCardTokenResponse; - shippingContact?: StripeApplePayPaymentContact; - shippingMethod?: StripeApplePayShippingMethod; -} - -interface StripeApplePayShippingMethod { - label: string; - detail: string; - amount: number; - identifier: string; -} - -interface StripeApplePayPaymentContact { - emailAddress: string; - phoneNumber: string; - givenName: string; - familyName: string; - addressLines: string[]; - locality: string; - administrativeArea: string; - postalCode: string; - countryCode: string; -} - -// The Stripe client side APIs are not made available to package managers for direct installation. -// As explained compliance reasons. Source: https://github.com/stripe/stripe-node/blob/master/README.md#these-are-serverside-bindings-only -// A release date versioning schema is used to version these APIs. diff --git a/types/stripe/stripe-tests.ts b/types/stripe/stripe-tests.ts index 56e6343f5c..f777c0eb34 100644 --- a/types/stripe/stripe-tests.ts +++ b/types/stripe/stripe-tests.ts @@ -1,25 +1,39 @@ -function success(card: StripeCard) { - console.log(card.brand && card.brand.toString()); -} +import {stripe, Stripe} from 'stripe'; -const cardNumber = '4242424242424242'; - -const isValid = Stripe.validateCardNumber(cardNumber); -if (isValid) { - const tokenData: StripeCardTokenData = { - number: cardNumber, - exp_month: 1, - exp_year: 2100, - cvc: '111' - }; - Stripe.card.createToken(tokenData, (status, response) => { - if (response.error) { - console.error(response.error.message); - if (response.error.param) { - console.error(response.error.param); - } - } else { - success(response.card); +const stripe = Stripe('public-key'); +const elements = stripe.elements(); +const style = { + base: { + color: '#32325d', + lineHeight: '24px', + fontFamily: 'Roboto, "Helvetica Neue", sans-serif', + fontSmoothing: 'antialiased', + fontSize: '16px', + '::placeholder': { + color: '#aab7c4' } - }); -} + }, + invalid: { + color: '#B71C1C', + iconColor: '#B71C1C' + } +}; +const card = elements.create('card', {hidePostalCode: true, style}); +card.mount(document.createElement('div')); +card.on('ready', () => { + console.log('ready'); +}); +card.on('change', (resp: stripe.elements.ElementChangeResponse) => { + console.log(resp.brand); +}); +stripe.createToken(card, { + name: 'Jimmy', + address_city: 'Toronto', + address_country: 'Canada' +}) +.then((result: stripe.TokenResponse) => { + console.log(result.token); +}, +(error: stripe.Error) => { + console.error(error); +}); diff --git a/types/stripe/tsconfig.json b/types/stripe/tsconfig.json index 7ea61e6327..c15aeceae9 100644 --- a/types/stripe/tsconfig.json +++ b/types/stripe/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "stripe-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/stripe/v2/index.d.ts b/types/stripe/v2/index.d.ts new file mode 100644 index 0000000000..cc486b5d5b --- /dev/null +++ b/types/stripe/v2/index.d.ts @@ -0,0 +1,170 @@ +// Type definitions for stripe 2.x +// Project: https://stripe.com/ +// Definitions by: Andy Hawkins +// Eric J. Smith +// Amrit Kahlon +// Adam Cmiel +// Justin Leider +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare const Stripe: StripeStatic; + +interface StripeStatic { + applePay: StripeApplePay; + setPublishableKey(key: string): void; + validateCardNumber(cardNumber: string): boolean; + validateExpiry(month: string, year: string): boolean; + validateCVC(cardCVC: string): boolean; + cardType(cardNumber: string): StripeCardDataBrand; + getToken(token: string, responseHandler: (status: number, response: StripeCardTokenResponse) => void): void; + card: StripeCard; + createToken(data: StripeCardTokenData, responseHandler: (status: number, response: StripeCardTokenResponse) => void): void; + bankAccount: StripeBankAccount; +} + +interface StripeCardTokenData { + number: string; + exp_month?: number; + exp_year?: number; + exp?: string; + cvc?: string; + name?: string; + address_line1?: string; + address_line2?: string; + address_city?: string; + address_state?: string; + address_zip?: string; + address_country?: string; +} + +interface StripeTokenResponse { + id: string; + client_ip: string; + created: number; + livemode: boolean; + object: string; + type: string; + used: boolean; + error?: StripeError; +} + +interface StripeCardTokenResponse extends StripeTokenResponse { + card: StripeCard; +} + +interface StripeError { + type: string; + code: string; + message: string; + param?: string; +} + +type StripeCardDataBrand = 'Visa' | 'American Express' | 'MasterCard' | 'Discover' | 'JCB' | 'Diners Club' | 'Unknown'; + +type StripeCardDataFunding = 'credit' | 'debit' | 'prepaid' | 'unknown'; + +interface StripeCard { + object: string; + last4: string; + exp_month: number; + exp_year: number; + country?: string; + name?: string; + address_line1?: string; + address_line2?: string; + address_city?: string; + address_state?: string; + address_zip?: string; + address_country?: string; + brand?: StripeCardDataBrand; + funding?: StripeCardDataFunding; + createToken(data: StripeCardTokenData, responseHandler: (status: number, response: StripeCardTokenResponse) => void): void; + validateCardNumber(cardNumber: string): boolean; + validateExpiry(month: string, year: string): boolean; + validateCVC(cardCVC: string): boolean; +} + +interface StripeBankAccount { + createToken(params: StripeBankTokenParams, stripeResponseHandler: (status: number, response: StripeBankTokenResponse) => void): void; + validateRoutingNumber(routingNumber: number | string, countryCode: string): boolean; + validateAccountNumber(accountNumber: number | string, countryCode: string): boolean; +} + +interface StripeBankTokenParams { + country: string; + currency: string; + account_number: number | string; + routing_number?: number | string; + account_holder_name: string; + account_holder_type: string; +} + +interface StripeBankTokenResponse extends StripeTokenResponse { + bank_account: { + country: string; + bank_name: string; + last4: number; + validated: boolean; + object: string; + }; +} + +interface StripeApplePay { + checkAvailability(resopnseHandler: (result: boolean) => void): void; + buildSession(data: StripeApplePayPaymentRequest, + onSuccessHandler: (result: StripeApplePaySessionResult, completion: ((value: any) => void)) => void, + onErrorHanlder: (error: { message: string }) => void): any; +} + +type StripeApplePayBillingContactField = 'postalAddress' | 'name'; +type StripeApplePayShippingContactField = StripeApplePayBillingContactField | 'phone' | 'email'; +type StripeApplePayShipping = 'shipping' | 'delivery' | 'storePickup' | 'servicePickup'; + +interface StripeApplePayPaymentRequest { + billingContact: StripeApplePayPaymentContact; + countryCode: string; + currencyCode: string; + total: StripeApplePayLineItem; + lineItems?: StripeApplePayLineItem[]; + requiredBillingContactFields?: StripeApplePayBillingContactField[]; + requiredShippingContactFields?: StripeApplePayShippingContactField[]; + shippingContact?: StripeApplePayPaymentContact; + shippingMethods?: StripeApplePayShippingMethod[]; + shippingType?: StripeApplePayShipping[]; +} + +// https://developer.apple.com/reference/applepayjs/1916082-applepay_js_data_types +interface StripeApplePayLineItem { + type: 'pending' | 'final'; + label: string; + amount: number; +} + +interface StripeApplePaySessionResult { + token: StripeCardTokenResponse; + shippingContact?: StripeApplePayPaymentContact; + shippingMethod?: StripeApplePayShippingMethod; +} + +interface StripeApplePayShippingMethod { + label: string; + detail: string; + amount: number; + identifier: string; +} + +interface StripeApplePayPaymentContact { + emailAddress: string; + phoneNumber: string; + givenName: string; + familyName: string; + addressLines: string[]; + locality: string; + administrativeArea: string; + postalCode: string; + countryCode: string; +} + +// The Stripe client side APIs are not made available to package managers for direct installation. +// As explained compliance reasons. Source: https://github.com/stripe/stripe-node/blob/master/README.md#these-are-serverside-bindings-only +// A release date versioning schema is used to version these APIs. diff --git a/types/stripe/v2/stripe-tests.ts b/types/stripe/v2/stripe-tests.ts new file mode 100644 index 0000000000..56e6343f5c --- /dev/null +++ b/types/stripe/v2/stripe-tests.ts @@ -0,0 +1,25 @@ +function success(card: StripeCard) { + console.log(card.brand && card.brand.toString()); +} + +const cardNumber = '4242424242424242'; + +const isValid = Stripe.validateCardNumber(cardNumber); +if (isValid) { + const tokenData: StripeCardTokenData = { + number: cardNumber, + exp_month: 1, + exp_year: 2100, + cvc: '111' + }; + Stripe.card.createToken(tokenData, (status, response) => { + if (response.error) { + console.error(response.error.message); + if (response.error.param) { + console.error(response.error.param); + } + } else { + success(response.card); + } + }); +} diff --git a/types/stripe/v2/tsconfig.json b/types/stripe/v2/tsconfig.json new file mode 100644 index 0000000000..5917b8206d --- /dev/null +++ b/types/stripe/v2/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "stripe": ["stripe/v2"] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "stripe-tests.ts" + ] +} diff --git a/types/stripe/v2/tslint.json b/types/stripe/v2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/stripe/v2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/superagent-no-cache/index.d.ts b/types/superagent-no-cache/index.d.ts new file mode 100644 index 0000000000..c08b41af15 --- /dev/null +++ b/types/superagent-no-cache/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for superagent-no-cache 0.1 +// Project: https://github.com/johntron/superagent-no-cache +// Definitions by: Michael Ledin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import * as request from 'superagent'; + +declare const plugin: request.Plugin; + +export = plugin; diff --git a/types/superagent-no-cache/superagent-no-cache-tests.ts b/types/superagent-no-cache/superagent-no-cache-tests.ts new file mode 100644 index 0000000000..68e4e961a2 --- /dev/null +++ b/types/superagent-no-cache/superagent-no-cache-tests.ts @@ -0,0 +1,9 @@ +import * as request from 'superagent'; +import * as plugin from 'superagent-no-cache'; + +request + .get('/some-url') + .use(plugin) + .end((err, res) => { + // Do something + }); diff --git a/types/superagent-no-cache/tsconfig.json b/types/superagent-no-cache/tsconfig.json new file mode 100644 index 0000000000..668d406795 --- /dev/null +++ b/types/superagent-no-cache/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "superagent-no-cache-tests.ts" + ] +} diff --git a/types/superagent-no-cache/tslint.json b/types/superagent-no-cache/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/superagent-no-cache/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/superagent-prefix/index.d.ts b/types/superagent-prefix/index.d.ts new file mode 100644 index 0000000000..8b7eb1d508 --- /dev/null +++ b/types/superagent-prefix/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for superagent-prefix 0.0 +// Project: https://github.com/johntron/superagent-prefix +// Definitions by: Michael Ledin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import * as request from 'superagent'; + +declare function plugin(prefix: string): request.Plugin; + +declare namespace plugin { +} + +export = plugin; diff --git a/types/superagent-prefix/superagent-prefix-tests.ts b/types/superagent-prefix/superagent-prefix-tests.ts new file mode 100644 index 0000000000..01e4b52905 --- /dev/null +++ b/types/superagent-prefix/superagent-prefix-tests.ts @@ -0,0 +1,9 @@ +import * as request from 'superagent'; +import * as plugin from 'superagent-prefix'; + +request + .get('/some-url') + .use(plugin('/static')) + .end((err, res) => { + // Do something + }); diff --git a/types/superagent-prefix/tsconfig.json b/types/superagent-prefix/tsconfig.json new file mode 100644 index 0000000000..20c1d2c993 --- /dev/null +++ b/types/superagent-prefix/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "superagent-prefix-tests.ts" + ] +} diff --git a/types/superagent-prefix/tslint.json b/types/superagent-prefix/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/superagent-prefix/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/superagent/index.d.ts b/types/superagent/index.d.ts index fe6a797675..4032a9d543 100644 --- a/types/superagent/index.d.ts +++ b/types/superagent/index.d.ts @@ -1,29 +1,30 @@ -// Type definitions for SuperAgent v2.0.1 +// Type definitions for SuperAgent 3.5 // Project: https://github.com/visionmedia/superagent -// Definitions by: Alex Varju -// Nico Zelaya +// Definitions by: Nico Zelaya +// Michael Ledin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// -import stream = require('stream'); -import https = require('https'); +import * as stream from 'stream'; +import * as https from 'https'; type CallbackHandler = (err: any, res: request.Response) => void; -declare var request: request.SuperAgentStatic; +declare const request: request.SuperAgentStatic; declare namespace request { interface SuperAgentRequest extends Request { - agent(agent: https.Agent): this; - agent(): this; + agent(agent?: https.Agent): this; method: string; url: string; cookies: string; - } + } interface SuperAgentStatic extends SuperAgent { (url: string): SuperAgentRequest; + // tslint:disable-next-line:unified-signatures (method: string, url: string): SuperAgentRequest; agent(): SuperAgent; @@ -58,9 +59,9 @@ declare namespace request { search(url: string, callback?: CallbackHandler): Req; connect(url: string, callback?: CallbackHandler): Req; - parse(fn: (res: Response, callback: (err: Error | null, body: any) => void) => void): this; - saveCookies(res: Response): void; - attachCookies(req: Req): void; + parse(fn: (res: Response, callback: (err: Error | null, body: any) => void) => void): this; + saveCookies(res: Response): void; + attachCookies(req: Req): void; } interface Response extends NodeJS.ReadableStream { @@ -90,37 +91,43 @@ declare namespace request { } interface Request extends Promise /* extends NodeJS.WritableStream */ { - abort(): void; - accept(type: string): this; - attach(field: string, file: string, filename?: string): this; - auth(user: string, name: string): this; - buffer(val?: boolean): this; - clearTimeout(): this; - end(callback?: CallbackHandler): this; - field(name: string, val: string): this; - get(field: string): string; - on(name: string, handler: Function): this; - on(name: 'error', handler: (err: any) => void): this; - part(): this; - pipe(stream: NodeJS.WritableStream, options?: Object): stream.Writable; - query(val: Object): this; - redirects(n: number): this; - responseType(type: string): this; - send(data: string): this; - send(data: Object): this; - send(): this; - set(field: string, val: string): this; - set(field: Object): this; - timeout(ms: number): this; - type(val: string): this; - unset(field: string): this; - use(fn: Function): this; - withCredentials(): this; - write(data: string, encoding?: string): this; - write(data: Buffer, encoding?: string): this; - parse(fn: (res: Response, callback: (err: Error | null, body: any) => void) => void): this; + abort(): void; + accept(type: string): this; + attach(field: string, file: string | Blob, filename?: string): this; + auth(user: string, name: string): this; + buffer(val?: boolean): this; + clearTimeout(): this; + end(callback?: CallbackHandler): this; + field(name: string, val: string): this; + get(field: string): string; + on(name: string, handler: (event: any) => void): this; + on(name: 'error', handler: (err: any) => void): this; + on(name: 'progress', handler: (event: ProgressEvent) => void): this; + part(): this; + pipe(stream: NodeJS.WritableStream, options?: object): stream.Writable; + query(val: object | string): this; + redirects(n: number): this; + responseType(type: string): this; + send(data?: string | object): this; + set(field: string, val: string): this; + set(field: object): this; + timeout(ms: number | { deadline?: number, response?: number }): this; + type(val: string): this; + unset(field: string): this; + use(fn: Plugin): this; + withCredentials(): this; + write(data: string | Buffer, encoding?: string): this; + parse(fn: (res: Response, callback: (err: Error | null, body: any) => void) => void): this; } + type Plugin = (req: Request) => void; + + interface ProgressEvent { + direction: 'download' | 'upload'; + loaded: number; + percent?: number; + total?: number; + } } export = request; diff --git a/types/superagent/superagent-tests.ts b/types/superagent/superagent-tests.ts index da60314b23..a6d07c3eaa 100644 --- a/types/superagent/superagent-tests.ts +++ b/types/superagent/superagent-tests.ts @@ -5,221 +5,209 @@ import * as fs from 'fs'; import * as assert from 'assert'; import { Agent } from 'https'; - // Examples taken from https://github.com/visionmedia/superagent/blob/gh-pages/docs/index.md // and https://github.com/visionmedia/superagent/blob/master/Readme.md const httpsAgent: Agent = new Agent(); request - .post('/api/pet') - .send({ name: 'Manny', species: 'cat' }) - .set('X-API-Key', 'foobar') - .set('Accept', 'application/json') - .agent(httpsAgent) - .end((err, res) => { - if (res.ok) { - console.log('yay got ' + JSON.stringify(res.body)); - } else { - console.log('Oh no! error ' + res.text); - } - }); + .post('/api/pet') + .send({name: 'Manny', species: 'cat'}) + .set('X-API-Key', 'foobar') + .set('Accept', 'application/json') + .agent(httpsAgent) + .end((err, res) => { + if (res.ok) { + console.log('yay got ' + JSON.stringify(res.body)); + } else { + console.log('Oh no! error ' + res.text); + } + }); -var agent = request.agent(); +const agent = request.agent(); agent - .post('/api/pet') - .send({ name: 'Manny', species: 'cat' }) - .set('X-API-Key', 'foobar') - .set('Accept', 'application/json') - .end((err, res) => { - if (res.error) { - console.log('oh no ' + res.error.message); - } else { - console.log('got ' + res.status + ' response'); - } - }); + .post('/api/pet') + .send({name: 'Manny', species: 'cat'}) + .set('X-API-Key', 'foobar') + .set('Accept', 'application/json') + .end((err, res) => { + if (res.error) { + console.log('oh no ' + res.error.message); + } else { + console.log('got ' + res.status + ' response'); + } + }); -// Plugins -var nocache = require('superagent-no-cache'); -var prefix = require('superagent-prefix')('/static'); - -request - .get('/some-url') - .use(prefix) // Prefixes *only* this request - .use(nocache) // Prevents caching of *only* this request - .end(function(err, res){ - // Do something - }); - -var callback = (err: any, res: request.Response) => {}; +const callback = (err: any, res: request.Response) => {}; // Request basics request - .get('/search') - .end(callback); + .get('/search') + .end(callback); request('GET', '/search') - .end(callback); + .end(callback); request - .get('http://example.com/search') - .end(callback); + .get('http://example.com/search') + .end(callback); request - .head('/favicon.ico') - .end(callback); + .head('/favicon.ico') + .end(callback); request - .del('/user/1') - .end(callback); + .del('/user/1') + .end(callback); request - .delete('/user/1') - .end(callback); + .delete('/user/1') + .end(callback); request - .delete('/user/1') - .send() - .end(callback); + .delete('/user/1') + .send() + .end(callback); request('/search') - .end(callback); + .end(callback); // Setting header fields request - .get('/search') - .set('API-Key', 'foobar') - .set('Accept', 'application/json') - .end(callback); + .get('/search') + .set('API-Key', 'foobar') + .set('Accept', 'application/json') + .end(callback); request - .get('/search') - .set({ 'API-Key': 'foobar', Accept: 'application/json' }) - .end(callback); + .get('/search') + .set({'API-Key': 'foobar', Accept: 'application/json'}) + .end(callback); // GET requests request - .get('/search') - .query({ query: 'Manny' }) - .query({ range: '1..5' }) - .query({ order: 'desc' }) - .end(callback); + .get('/search') + .query({query: 'Manny'}) + .query({range: '1..5'}) + .query({order: 'desc'}) + .end(callback); request - .get('/search') - .query({ query: 'Manny', range: '1..5', order: 'desc' }) - .end(callback); + .get('/search') + .query({query: 'Manny', range: '1..5', order: 'desc'}) + .end(callback); request - .get('/querystring') - .query('search=Manny&range=1..5') - .end(callback); + .get('/querystring') + .query('search=Manny&range=1..5') + .end(callback); request - .get('/querystring') - .query('search=Manny') - .query('range=1..5') - .end(callback); + .get('/querystring') + .query('search=Manny') + .query('range=1..5') + .end(callback); // HEAD requests request - .head('/users') - .query({ email: 'joe@smith.com' }) - .end(callback); + .head('/users') + .query({email: 'joe@smith.com'}) + .end(callback); // POST / PUT requests request.post('/user') - .set('Content-Type', 'application/json') - .send('{"name":"tj","pet":"tobi"}') - .end(callback); + .set('Content-Type', 'application/json') + .send('{"name":"tj","pet":"tobi"}') + .end(callback); request.post('/user') - .send({ name: 'tj', pet: 'tobi' }) - .end(callback); + .send({name: 'tj', pet: 'tobi'}) + .end(callback); request.post('/user') - .send({ name: 'tj' }) - .send({ pet: 'tobi' }) - .end(callback); + .send({name: 'tj'}) + .send({pet: 'tobi'}) + .end(callback); request.post('/user') - .send('name=tj') - .send('pet=tobi') - .end(callback); + .send('name=tj') + .send('pet=tobi') + .end(callback); request.post('/user') - .type('form') - .send({ name: 'tj' }) - .send({ pet: 'tobi' }) - .end(callback); + .type('form') + .send({name: 'tj'}) + .send({pet: 'tobi'}) + .end(callback); // Setting the Content-Type request.post('/user') - .set('Content-Type', 'application/json'); + .set('Content-Type', 'application/json'); request.post('/user') - .type('application/json'); + .type('application/json'); request.post('/user') - .type('json'); + .type('json'); request.post('/user') - .type('png'); + .type('png'); // Setting Accept request.get('/user') - .accept('application/json'); + .accept('application/json'); request.get('/user') - .accept('json'); + .accept('json'); request.get('/user') - .accept('png'); + .accept('png'); // Query strings request - .post('/') - .query({ format: 'json' }) - .query({ dest: '/login' }) - .send({ post: 'data', here: 'wahoo' }) - .end(callback); + .post('/') + .query({format: 'json'}) + .query({dest: '/login'}) + .send({post: 'data', here: 'wahoo'}) + .end(callback); // Parsing response bodies request('/search') .end((res: request.Response) => { - var status: number = res.status; - var body = res.body; - var files: Object = res.files; - var text: string = res.text; - var contentLength = res.header['content-length']; - var contentType: string = res.type; - var charset: string = res.charset; + const status: number = res.status; + const body = res.body; + const files: object = res.files; + const text: string = res.text; + const contentLength = res.header['content-length']; + const contentType: string = res.type; + const charset: string = res.charset; }); // Custom parsers request - .post('/search') - .parse((res, callback) => { - res.setEncoding("binary"); - let data = ""; - res.on("data", (chunk: string) => { - data += chunk; + .post('/search') + .parse((res, callback) => { + res.setEncoding("binary"); + let data = ""; + res.on("data", (chunk: string) => { + data += chunk; + }); + + res.on("end", () => { + callback(null, new Buffer(data, "base64")); + }); + }) + .end((res: request.Response) => { + res.body.toString("hex"); }); - res.on("end", () => { - callback(null, new Buffer(data, "base64")); - }); - }) - .end((res: request.Response) => { - res.body.toString("hex"); - }); - -var req = request.get('/hoge'); +const req = request.get('/hoge'); // Aborting requests req.abort(); // Request timeouts req.timeout(100); +req.timeout({ response: 5000, deadline: 60000 }); const reqUrl: string = req.url; const reqMethod: string = req.method; @@ -230,94 +218,114 @@ console.log(reqMethod + ' request to ' + reqUrl + ' cookies ' + reqCookies); // Basic authentication request.get('http://tobi:learnboost@local').end(callback); request - .get('http://local') - .auth('tobo', 'learnboost') - .end(callback); + .get('http://local') + .auth('tobo', 'learnboost') + .end(callback); // Following redirects request - .get('/some.png') - .redirects(2) - .end(callback); + .get('/some.png') + .redirects(2) + .end(callback); // Piping data /* -(function() { -var stream = fs.createReadStream('path/to/my.json'); -var req = request.post('/somewhere'); +(() => { +const stream = fs.createReadStream('path/to/my.json'); +const req = request.post('/somewhere'); req.type('json'); stream.pipe(req); })(); */ -(function() { -var stream = fs.createWriteStream('path/to/my.json'); -var req = request.get('/some.json'); -req.pipe(stream); +(() => { + const stream = fs.createWriteStream('path/to/my.json'); + const req = request.get('/some.json'); + req.pipe(stream); })(); // Multipart requests -(function() { -var req = request.post('/upload'); +(() => { + const req = request.post('/upload'); -req.part() - .set('Content-Type', 'image/png') - .set('Content-Disposition', 'attachment; filename="myimage.png"') - .write('some image data') - .write('some more image data'); + req.part() + .set('Content-Type', 'image/png') + .set('Content-Disposition', 'attachment; filename="myimage.png"') + .write('some image data') + .write('some more image data'); -req.part() - .set('Content-Disposition', 'form-data; name="name"') - .set('Content-Type', 'text/plain') - .write('tobi'); + req.part() + .set('Content-Disposition', 'form-data; name="name"') + .set('Content-Type', 'text/plain') + .write('tobi'); -req.end(callback); + req.end(callback); })(); // Attaching files +const blob: Blob = new File([], 'thor.png'); request - .post('/upload') - .attach('avatar', 'path/to/tobi.png', 'user.png') - .attach('image', 'path/to/loki.png') - .attach('file', 'path/to/jane.png') - .end(callback); + .post('/upload') + .attach('avatar', 'path/to/tobi.png', 'user.png') + .attach('image', 'path/to/loki.png') + .attach('file', 'path/to/jane.png') + .attach('blob', blob) + .end(callback); // Field values request - .post('/upload') - .field('user[name]', 'Tobi') - .field('user[email]', 'tobi@learnboost.com') - .attach('image', 'path/to/tobi.png') - .end(callback); + .post('/upload') + .field('user[name]', 'Tobi') + .field('user[email]', 'tobi@learnboost.com') + .attach('image', 'path/to/tobi.png') + .end(callback); // CORS request - .get('http://localhost:4001/') - .withCredentials() - .end(callback); + .get('http://localhost:4001/') + .withCredentials() + .end(callback); // Error handling request - .post('/upload') - .attach('image', 'path/to/tobi.png') - .end((err: any, res: request.Response): void => {}); + .post('/upload') + .attach('image', 'path/to/tobi.png') + .end((err: any, res: request.Response): void => { + }); request - .post('/upload') - .attach('image', 'path/to/tobi.png') - .on('error', (err: any) => {}) - .end(callback); + .post('/upload') + .attach('image', 'path/to/tobi.png') + .on('error', (err: any) => { + }) + .end(callback); -//Promise +// Progress request - .get('/search') - .then((response) => {}) - .catch((error) => {}); + .post('/upload') + .attach('image', 'path/to/tobi.png') + .on('progress', (progress: request.ProgressEvent) => { + if (progress.direction === 'download') { + } else if (progress.direction === 'upload') { + } + const loaded: number = progress.loaded; + const percent: number | undefined = progress.percent; + const total: number | undefined = progress.total; + }) + .end(callback); + +// Promise +request + .get('/search') + .then((response) => { + }) + .catch((error) => { + }); // Requesting binary data. // adapted from: https://github.com/visionmedia/superagent/blob/v2.0.0/test/client/request.js#L110 request .get('/blob') .responseType('blob') - .end(function (err, res) { - assert(res.xhr instanceof XMLHttpRequest) + .end((err, res) => { + assert(res.xhr instanceof XMLHttpRequest); assert(res.xhr.response instanceof Blob); }); diff --git a/types/superagent/tsconfig.json b/types/superagent/tsconfig.json index 1a20530571..b1f13095f7 100644 --- a/types/superagent/tsconfig.json +++ b/types/superagent/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "superagent-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/superagent/tslint.json b/types/superagent/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/superagent/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/superagent/v2/index.d.ts b/types/superagent/v2/index.d.ts new file mode 100644 index 0000000000..f598bbd4fe --- /dev/null +++ b/types/superagent/v2/index.d.ts @@ -0,0 +1,126 @@ +// Type definitions for SuperAgent 2.3 +// Project: https://github.com/visionmedia/superagent +// Definitions by: Alex Varju +// Nico Zelaya +// Michael Ledin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +import * as stream from 'stream'; +import * as https from 'https'; + +type CallbackHandler = (err: any, res: request.Response) => void; + +declare const request: request.SuperAgentStatic; + +declare namespace request { + interface SuperAgentRequest extends Request { + agent(agent?: https.Agent): this; + + method: string; + url: string; + cookies: string; + } + interface SuperAgentStatic extends SuperAgent { + (url: string): SuperAgentRequest; + // tslint:disable-next-line:unified-signatures + (method: string, url: string): SuperAgentRequest; + + agent(): SuperAgent; + } + + interface SuperAgent extends stream.Stream { + get(url: string, callback?: CallbackHandler): Req; + post(url: string, callback?: CallbackHandler): Req; + put(url: string, callback?: CallbackHandler): Req; + head(url: string, callback?: CallbackHandler): Req; + del(url: string, callback?: CallbackHandler): Req; + delete(url: string, callback?: CallbackHandler): Req; + options(url: string, callback?: CallbackHandler): Req; + trace(url: string, callback?: CallbackHandler): Req; + copy(url: string, callback?: CallbackHandler): Req; + lock(url: string, callback?: CallbackHandler): Req; + mkcol(url: string, callback?: CallbackHandler): Req; + move(url: string, callback?: CallbackHandler): Req; + purge(url: string, callback?: CallbackHandler): Req; + propfind(url: string, callback?: CallbackHandler): Req; + proppatch(url: string, callback?: CallbackHandler): Req; + unlock(url: string, callback?: CallbackHandler): Req; + report(url: string, callback?: CallbackHandler): Req; + mkactivity(url: string, callback?: CallbackHandler): Req; + checkout(url: string, callback?: CallbackHandler): Req; + merge(url: string, callback?: CallbackHandler): Req; + // m-search(url: string, callback?: CallbackHandler): Req; + notify(url: string, callback?: CallbackHandler): Req; + subscribe(url: string, callback?: CallbackHandler): Req; + unsubscribe(url: string, callback?: CallbackHandler): Req; + patch(url: string, callback?: CallbackHandler): Req; + search(url: string, callback?: CallbackHandler): Req; + connect(url: string, callback?: CallbackHandler): Req; + + parse(fn: (res: Response, callback: (err: Error | null, body: any) => void) => void): this; + saveCookies(res: Response): void; + attachCookies(req: Req): void; + } + + interface Response extends NodeJS.ReadableStream { + text: string; + body: any; + files: any; + header: any; + type: string; + charset: string; + status: number; + statusType: number; + info: boolean; + ok: boolean; + redirect: boolean; + clientError: boolean; + serverError: boolean; + error: Error; + accepted: boolean; + noContent: boolean; + badRequest: boolean; + unauthorized: boolean; + notAcceptable: boolean; + notFound: boolean; + forbidden: boolean; + xhr: XMLHttpRequest; + get(header: string): string; + } + + interface Request extends Promise /* extends NodeJS.WritableStream */ { + abort(): void; + accept(type: string): this; + attach(field: string, file: string, filename?: string): this; + auth(user: string, name: string): this; + buffer(val?: boolean): this; + clearTimeout(): this; + end(callback?: CallbackHandler): this; + field(name: string, val: string): this; + get(field: string): string; + on(name: string, handler: (event: any) => void): this; + on(name: 'error', handler: (err: any) => void): this; + part(): this; + pipe(stream: NodeJS.WritableStream, options?: object): stream.Writable; + query(val: object | string): this; + redirects(n: number): this; + responseType(type: string): this; + send(data?: string | object): this; + set(field: string, val: string): this; + set(field: object): this; + timeout(ms: number): this; + type(val: string): this; + unset(field: string): this; + use(fn: Plugin): this; + withCredentials(): this; + write(data: string | Buffer, encoding?: string): this; + parse(fn: (res: Response, callback: (err: Error | null, body: any) => void) => void): this; + } + + type Plugin = (req: Request) => void; +} + +export = request; diff --git a/types/superagent/v2/superagent-tests.ts b/types/superagent/v2/superagent-tests.ts new file mode 100644 index 0000000000..0ad9c302fc --- /dev/null +++ b/types/superagent/v2/superagent-tests.ts @@ -0,0 +1,314 @@ +// via: http://visionmedia.github.io/superagent/ + +import * as request from 'superagent'; +import * as fs from 'fs'; +import * as assert from 'assert'; +import { Agent } from 'https'; + +// Examples taken from https://github.com/visionmedia/superagent/blob/gh-pages/docs/index.md +// and https://github.com/visionmedia/superagent/blob/master/Readme.md + +const httpsAgent: Agent = new Agent(); + +request + .post('/api/pet') + .send({name: 'Manny', species: 'cat'}) + .set('X-API-Key', 'foobar') + .set('Accept', 'application/json') + .agent(httpsAgent) + .end((err, res) => { + if (res.ok) { + console.log('yay got ' + JSON.stringify(res.body)); + } else { + console.log('Oh no! error ' + res.text); + } + }); + +const agent = request.agent(); +agent + .post('/api/pet') + .send({name: 'Manny', species: 'cat'}) + .set('X-API-Key', 'foobar') + .set('Accept', 'application/json') + .end((err, res) => { + if (res.error) { + console.log('oh no ' + res.error.message); + } else { + console.log('got ' + res.status + ' response'); + } + }); + +const callback = (err: any, res: request.Response) => {}; + +// Request basics +request + .get('/search') + .end(callback); + +request('GET', '/search') + .end(callback); + +request + .get('http://example.com/search') + .end(callback); + +request + .head('/favicon.ico') + .end(callback); + +request + .del('/user/1') + .end(callback); + +request + .delete('/user/1') + .end(callback); + +request + .delete('/user/1') + .send() + .end(callback); + +request('/search') + .end(callback); + +// Setting header fields +request + .get('/search') + .set('API-Key', 'foobar') + .set('Accept', 'application/json') + .end(callback); + +request + .get('/search') + .set({'API-Key': 'foobar', Accept: 'application/json'}) + .end(callback); + +// GET requests +request + .get('/search') + .query({query: 'Manny'}) + .query({range: '1..5'}) + .query({order: 'desc'}) + .end(callback); + +request + .get('/search') + .query({query: 'Manny', range: '1..5', order: 'desc'}) + .end(callback); + +request + .get('/querystring') + .query('search=Manny&range=1..5') + .end(callback); + +request + .get('/querystring') + .query('search=Manny') + .query('range=1..5') + .end(callback); + +// HEAD requests +request + .head('/users') + .query({email: 'joe@smith.com'}) + .end(callback); + +// POST / PUT requests +request.post('/user') + .set('Content-Type', 'application/json') + .send('{"name":"tj","pet":"tobi"}') + .end(callback); + +request.post('/user') + .send({name: 'tj', pet: 'tobi'}) + .end(callback); + +request.post('/user') + .send({name: 'tj'}) + .send({pet: 'tobi'}) + .end(callback); + +request.post('/user') + .send('name=tj') + .send('pet=tobi') + .end(callback); + +request.post('/user') + .type('form') + .send({name: 'tj'}) + .send({pet: 'tobi'}) + .end(callback); + +// Setting the Content-Type +request.post('/user') + .set('Content-Type', 'application/json'); + +request.post('/user') + .type('application/json'); + +request.post('/user') + .type('json'); + +request.post('/user') + .type('png'); + +// Setting Accept +request.get('/user') + .accept('application/json'); + +request.get('/user') + .accept('json'); + +request.get('/user') + .accept('png'); + +// Query strings +request + .post('/') + .query({format: 'json'}) + .query({dest: '/login'}) + .send({post: 'data', here: 'wahoo'}) + .end(callback); + +// Parsing response bodies +request('/search') + .end((res: request.Response) => { + const status: number = res.status; + const body = res.body; + const files: object = res.files; + const text: string = res.text; + const contentLength = res.header['content-length']; + const contentType: string = res.type; + const charset: string = res.charset; + }); + +// Custom parsers +request + .post('/search') + .parse((res, callback) => { + res.setEncoding("binary"); + let data = ""; + res.on("data", (chunk: string) => { + data += chunk; + }); + + res.on("end", () => { + callback(null, new Buffer(data, "base64")); + }); + }) + .end((res: request.Response) => { + res.body.toString("hex"); + }); + +const req = request.get('/hoge'); +// Aborting requests +req.abort(); + +// Request timeouts +req.timeout(100); + +const reqUrl: string = req.url; +const reqMethod: string = req.method; +const reqCookies: string = req.cookies; + +console.log(reqMethod + ' request to ' + reqUrl + ' cookies ' + reqCookies); + +// Basic authentication +request.get('http://tobi:learnboost@local').end(callback); +request + .get('http://local') + .auth('tobo', 'learnboost') + .end(callback); + +// Following redirects +request + .get('/some.png') + .redirects(2) + .end(callback); + +// Piping data +/* +(() => { +const stream = fs.createReadStream('path/to/my.json'); +const req = request.post('/somewhere'); +req.type('json'); +stream.pipe(req); +})(); +*/ + +(() => { + const stream = fs.createWriteStream('path/to/my.json'); + const req = request.get('/some.json'); + req.pipe(stream); +})(); + +// Multipart requests +(() => { + const req = request.post('/upload'); + + req.part() + .set('Content-Type', 'image/png') + .set('Content-Disposition', 'attachment; filename="myimage.png"') + .write('some image data') + .write('some more image data'); + + req.part() + .set('Content-Disposition', 'form-data; name="name"') + .set('Content-Type', 'text/plain') + .write('tobi'); + + req.end(callback); +})(); + +// Attaching files +request + .post('/upload') + .attach('avatar', 'path/to/tobi.png', 'user.png') + .attach('image', 'path/to/loki.png') + .attach('file', 'path/to/jane.png') + .end(callback); + +// Field values +request + .post('/upload') + .field('user[name]', 'Tobi') + .field('user[email]', 'tobi@learnboost.com') + .attach('image', 'path/to/tobi.png') + .end(callback); + +// CORS +request + .get('http://localhost:4001/') + .withCredentials() + .end(callback); + +// Error handling +request + .post('/upload') + .attach('image', 'path/to/tobi.png') + .end((err: any, res: request.Response): void => { + }); +request + .post('/upload') + .attach('image', 'path/to/tobi.png') + .on('error', (err: any) => { + }) + .end(callback); + +// Promise +request + .get('/search') + .then((response) => { + }) + .catch((error) => { + }); +// Requesting binary data. +// adapted from: https://github.com/visionmedia/superagent/blob/v2.0.0/test/client/request.js#L110 +request + .get('/blob') + .responseType('blob') + .end((err, res) => { + assert(res.xhr instanceof XMLHttpRequest); + assert(res.xhr.response instanceof Blob); + }); diff --git a/types/superagent/v2/tsconfig.json b/types/superagent/v2/tsconfig.json new file mode 100644 index 0000000000..9061d77842 --- /dev/null +++ b/types/superagent/v2/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "superagent": ["superagent/v2"], + "superagent/*": ["superagent/v2/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "superagent-tests.ts" + ] +} diff --git a/types/superagent/v2/tslint.json b/types/superagent/v2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/superagent/v2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/supertest/index.d.ts b/types/supertest/index.d.ts index f3866469e3..206c70defd 100644 --- a/types/supertest/index.d.ts +++ b/types/supertest/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/visionmedia/supertest // Definitions by: Alex Varju // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 import * as superagent from "superagent"