Merge branch 'master' into react-navigation/update-from-flow

This commit is contained in:
abrahambotros
2017-06-15 09:35:03 -07:00
57 changed files with 2116 additions and 813 deletions
@@ -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,
});
+3
View File
@@ -1,6 +1,7 @@
// Type definitions for connect-redis
// Project: https://npmjs.com/package/connect-redis
// Definitions by: Xavier Stouder <https://github.com/xstoudi>
// Albert Kurniawan <https://github.com/morcerf>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="express" />
@@ -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;
+130 -20
View File
@@ -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<SNodeExtra, SLinkExtra>;
type SNodeCustomId = d3Sankey.SankeyNode<SNodeExtraCustomId, SLinkExtra>;
type SLink = d3Sankey.SankeyLink<SNodeExtra, SLinkExtra>;
type SLinkCustomId = d3Sankey.SankeyLink<SNodeExtraCustomId, SLinkExtra>;
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<SNodeExtra, SLinkExtra>;
let slgDefault: d3Sankey.SankeyLayout<d3Sankey.SankeyGraph<{}, {}>, {}, {}> = d3Sankey.sankey();
let slgDAG: d3Sankey.SankeyLayout<DAG, SNodeExtra, SLinkExtra> = d3Sankey.sankey<DAG, SNodeExtra, SLinkExtra>();
let slgDAGCustomId: d3Sankey.SankeyLayout<DAGCustomId, SNodeExtraCustomId, SLinkExtra> = d3Sankey.sankey<DAGCustomId, SNodeExtraCustomId, SLinkExtra>();
// ---------------------------------------------------------------------------
// 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):
+80 -8
View File
@@ -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 <https://github.com/tomwanzek>, Alex Ford <https://github.com/gustavderdrache>
// 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<N extends SankeyExtraProperties, L extends Sa
* Nodes zero-based graph depth, derived from the graph topology calculated by Sankey layout generator.
*/
depth?: number;
/**
* Nodes zero-based graph height, derived from the graph topology calculated by Sankey layout generator.
*/
height?: number;
/**
* Node's minimum horizontal position (derived from the node.depth) calculated by Sankey layout generator.
*/
@@ -96,23 +100,25 @@ export type SankeyNode<N extends SankeyExtraProperties, L extends SankeyExtraPro
*/
export interface SankeyLinkMinimal<N extends SankeyExtraProperties, L extends SankeyExtraProperties> {
/**
* 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<N, L>;
source: number | string | SankeyNode<N, L>;
/**
* 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<N, L>;
target: number | string | SankeyNode<N, L>;
/**
* Link's numeric value
*/
@@ -244,6 +250,34 @@ export interface SankeyLayout<Data, N extends SankeyExtraProperties, L extends S
*/
links(links: (data: Data, ...args: any[]) => Array<SankeyLink<N, L>>): 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<N, L>) => 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 links 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<N, L>) => string | number): this;
/**
* Return the current node alignment method, which defaults to d3.sankeyLeft.
*/
nodeAlign(): (node: SankeyNode<N, L>, 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, L>, n: number) => number): this;
/**
* Return the current node width, which defaults to 24.
*/
@@ -346,6 +380,44 @@ export function sankey<N extends SankeyExtraProperties, L extends SankeyExtraPro
*/
export function sankey<Data, N extends SankeyExtraProperties, L extends SankeyExtraProperties>(): SankeyLayout<Data, N, L>;
/**
* 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
+14
View File
@@ -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
+49
View File
@@ -0,0 +1,49 @@
// Type definitions for hubot 2.19
// Project: https://github.com/github/hubot
// Definitions by: Dirk Gadsden <https://github.com/dirk>
// 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<T>(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;
+22
View File
@@ -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"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+10
View File
@@ -0,0 +1,10 @@
// Type definitions for jasmine-given 2.6
// Project: https://github.com/searls/jasmine-given
// Definitions by: Shai Reznik <https://github.com/shairez>
// 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;
@@ -0,0 +1,9 @@
Given(() => { });
When(() => { });
Then(() => { });
And(() => { });
Invariant(() => {});
+22
View File
@@ -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"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+9 -1
View File
@@ -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.
+3
View File
@@ -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");
});
+42 -4
View File
@@ -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 <https://github.com/swissspidy>
// Clarence Ho <https://github.com/clarenceh>
@@ -10,7 +10,7 @@
export = massive;
declare function massive(
connection: object | string,
connection: massive.ConnectionInfo | string,
loaderConfig?: object,
driverConfig?: object): Promise<massive.Database>;
@@ -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<T> {
find(criteria: object | {}, queryOptions?: QueryOptions): Promise<T[]>;
findOne(criteria: number | object, queryOptions?: QueryOptions): Promise<T>;
count(criteria: object): Promise<string>;
where(query: string, params: any[] | object): Promise<T[]>;
search(criteria: SearchCriteria, queryOptions?: QueryOptions): Promise<any>;
save(data: object): Promise<T[]>;
insert(data: object): Promise<T[]>;
update(dataOrCriteria: object, changesMap?: object): Promise<T[]>;
destroy(criteria: object): Promise<T[]>;
}
interface Document {
countDoc(criteria: object): Promise<number>;
findDoc(criteria: number | string| object): Promise<object>;
searchDoc(criteria: SearchCriteria): Promise<object[]>;
saveDoc(doc: object): Promise<object>;
modify(docId: number | string, doc: object, fieldName?: string): Promise<object>;
}
interface Database {
attach(ctor: any, ...sources: any[]): Promise<any>;
detach(entity: string, collection: string): void;
reload(): void;
query(query: any, params: any, options: any): Promise<any>;
saveDoc(collection: any, doc: any): any;
saveDoc(collectionName: string, doc: object): Promise<any>;
createDocumentTable(path: any): Promise<any>;
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<object[]>;
}
}
+1
View File
@@ -832,6 +832,7 @@ declare namespace __MaterialUI {
className?: string;
openIcon?: React.ReactNode;
closeIcon?: React.ReactNode;
iconStyle?: React.CSSProperties;
}
export class CardHeader extends React.Component<CardHeaderProps, {}> {
}
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://www.npmjs.com/package/promisify-supertest
// Definitions by: Leo Liang <https://github.com/aleung/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
// Mostly copy-pasted from supertest.d.ts
+5 -5
View File
@@ -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" {
}
}
}
+4 -4
View File
@@ -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<T>(fn: (a: T) => boolean, list: T[]): T;
find<T>(fn: (a: T) => boolean): (list: T[]) => T;
find<T>(fn: (a: T) => boolean, list: T[]): T | undefined;
find<T>(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<T>(fn: (a: T) => boolean, list: T[]): T;
findLast<T>(fn: (a: T) => boolean): (list: T[]) => T;
findLast<T>(fn: (a: T) => boolean, list: T[]): T | undefined;
findLast<T>(fn: (a: T) => boolean): (list: T[]) => T | undefined;
/**
* Returns the index of the last element of the list which matches the predicate, or
+1
View File
@@ -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 {
+1
View File
@@ -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() {
+31 -33
View File
@@ -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 <https://github.com/bgrieder>,
// Christian Droulers <https://github.com/cdroulers>,
// Fedor Nezhivoi <https://github.com/gyzerok>,
// Till Wolff <https://github.com/tillwolff>,
// Karol Janyst <https://github.com/LKay>,
// Brian Houser <https://github.com/bhouser>
// Brian Houser <https://github.com/bhouser>,
// Krister Kari <https://github.com/kristerkari>
// 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<P> = React.ComponentClass<P> | React.StatelessComponent<P>
type ComponentConstructor<P> = React.ComponentClass<P> | React.StatelessComponent<P>;
function injectIntl<P>(component: ComponentConstructor<P & InjectedIntlProps>, options?: InjectIntlConfig):
React.ComponentClass<P> & { WrappedComponent: ComponentConstructor<P & InjectedIntlProps> };
@@ -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<T extends Messages>(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<FormattedDate.Props, any> { }
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<FormattedTime.Props, any> { }
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<FormattedRelative.Props, any> { }
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<FormattedMessage.Props, any> { }
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<FormattedNumber.Props, any> { }
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<FormattedPlural.Props, any> { }
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<IntlProvider.Props, any> {
getChildContext(): {
intl: InjectedIntl;
}
};
}
}
declare module "react-intl" {
export = ReactIntl
export = ReactIntl;
}
declare module "react-intl/locale-data/af" {
+23 -11
View File
@@ -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<SomeComponentProps> = injectIntl<SomeComponentProps>(({
@@ -51,7 +51,10 @@ const SomeFunctionalComponentWithIntl: React.ComponentClass<SomeComponentProps>
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 <strong>{name}</strong>!" }, { name: "Roger" });
return (
<div className={className}>
@@ -71,8 +74,17 @@ class SomeComponent extends React.Component<SomeComponentProps & InjectedIntlPro
const formattedNumber = intl.formatNumber(123, { format: "short" });
const formattedPlural = intl.formatPlural(1, { style: "ordinal" });
const formattedMessage = intl.formatMessage({ id: "hello", defaultMessage: "Hello {name}!" }, { name: "Roger" });
const formattedMessagePlurals = intl.formatMessage({ id: "hello", defaultMessage: "Hello {name} you have {unreadCount, number} {unreadCount, plural, one {message} other {messages}}!" }, { name: "Roger", unreadCount: 123 });
const formattedMessageNumber = intl.formatMessage({ id: "hello", defaultMessage: "Hello {num}!" }, { num: 1 });
const formattedMessageDate = intl.formatMessage({ id: "hello", defaultMessage: "Hello {date}!" }, { date: new Date() });
const formattedMessageBool = intl.formatMessage({ id: "hello", defaultMessage: "Hello {bool}!" }, { bool: true });
const formattedMessagePlurals = intl.formatMessage({
id: "hello",
defaultMessage: "Hello {name} you have {unreadCount, number} {unreadCount, plural, one {message} other {messages}}!" },
{ name: "Roger", unreadCount: 123 });
const formattedHTMLMessage = intl.formatHTMLMessage({ id: "hello", defaultMessage: "Hello <strong>{name}</strong>!" }, { name: "Roger" });
const formattedHTMLMessageNumber = intl.formatHTMLMessage({ id: "hello", defaultMessage: "Hello <strong>{num}</strong>!" }, { num: 1 });
const formattedHTMLMessageDate = intl.formatHTMLMessage({ id: "hello", defaultMessage: "Hello <strong>{date}</strong>!" }, { date: new Date() });
const formattedHTMLMessageBool = intl.formatHTMLMessage({ id: "hello", defaultMessage: "Hello <strong>{bool}</strong>!" }, { bool: true });
return <div className={this.props.className}>
<FormattedRelative
value={new Date().getTime()}
@@ -221,7 +233,7 @@ class SomeComponent extends React.Component<SomeComponentProps & InjectedIntlPro
<span className="number">{formattedNum}</span>
)}
</FormattedNumber>
</div>
</div>;
}
}
@@ -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 (
<IntlProvider locale="en" formats={{}} messages={messages} defaultLocale="en" defaultFormats={messages}>
@@ -250,9 +262,9 @@ class TestApp extends React.Component<{}, {}> {
const intlProvider = new IntlProvider({ locale: 'en' }, {});
const { intl } = intlProvider.getChildContext();
const wrappedComponent = <SomeComponentWithIntl.WrappedComponent className="test" intl={intl}/>
const wrappedComponent = <SomeComponentWithIntl.WrappedComponent className="test" intl={intl}/>;
export default {
TestApp,
SomeComponent: SomeComponentWithIntl
}
};
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+8
View File
@@ -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> = T & {
navigationOptions?: NavigationScreenConfig<any>,
path?: string,
+52
View File
@@ -0,0 +1,52 @@
// Type definitions for sharp-timer 0.3
// Project: https://github.com/afractal/SharpTimer
// Definitions by: Hermes Gjini - afractal <https://github.com/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);
}
+10
View File
@@ -0,0 +1,10 @@
import { Timer, Stopwatch } from 'sharp-timer';
let timer = new Timer(10);
timer.onIntervalElapsing(i => { });
timer.onIntervalElapsed(() => {
timer.stop();
});
timer.start();
+22
View File
@@ -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"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://github.com/astronaughts/simple-cw-node
// Definitions by: vvakame <https://github.com/vvakame>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
import superagent = require("superagent");
// TODO 1. update superagent with generics
+305 -311
View File
@@ -3,331 +3,325 @@
// Definitions by: Kir Dergachev <https://github.com/decyrus>
// 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;
}
+12 -12
View File
@@ -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) => { });
+1 -1
View File
@@ -3,7 +3,7 @@
// Definitions by: Chris Wrench <https://github.com/cgwrench>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="stripe"/>
/// <reference types="stripe/v2"/>
interface StripeCheckoutStatic {
configure(options: StripeCheckoutOptions): StripeCheckoutHandler;
+177 -157
View File
@@ -1,4 +1,4 @@
// Type definitions for stripe 2.x
// Type definitions for stripe 3.0
// Project: https://stripe.com/
// Definitions by: Andy Hawkins <https://github.com/a904guy/,http://a904guy.com>
// Eric J. Smith <https://github.com/ejsmith/>
@@ -7,164 +7,184 @@
// Justin Leider <https://github.com/jleider>
// 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<TokenResponse>;
}
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.
+37 -23
View File
@@ -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);
});
+1 -1
View File
@@ -20,4 +20,4 @@
"index.d.ts",
"stripe-tests.ts"
]
}
}
+170
View File
@@ -0,0 +1,170 @@
// Type definitions for stripe 2.x
// Project: https://stripe.com/
// Definitions by: Andy Hawkins <https://github.com/a904guy/,http://a904guy.com>
// Eric J. Smith <https://github.com/ejsmith/>
// Amrit Kahlon <https://github.com/amritk/>
// Adam Cmiel <https://github.com/adamcmiel>
// Justin Leider <https://github.com/jleider>
// 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.
+25
View File
@@ -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);
}
});
}
+26
View File
@@ -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"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+11
View File
@@ -0,0 +1,11 @@
// Type definitions for superagent-no-cache 0.1
// Project: https://github.com/johntron/superagent-no-cache
// Definitions by: Michael Ledin <https://github.com/mxl/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
import * as request from 'superagent';
declare const plugin: request.Plugin;
export = plugin;
@@ -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
});
+23
View File
@@ -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"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+14
View File
@@ -0,0 +1,14 @@
// Type definitions for superagent-prefix 0.0
// Project: https://github.com/johntron/superagent-prefix
// Definitions by: Michael Ledin <https://github.com/mxl/>
// 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;
@@ -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
});
+23
View File
@@ -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"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+48 -41
View File
@@ -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 <https://github.com/varju/>
// Nico Zelaya <https://github.com/NicoZelaya/>
// Definitions by: Nico Zelaya <https://github.com/NicoZelaya/>
// Michael Ledin <https://github.com/mxl/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
/// <reference types="node" />
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<SuperAgentRequest> {
(url: string): SuperAgentRequest;
// tslint:disable-next-line:unified-signatures
(method: string, url: string): SuperAgentRequest;
agent(): SuperAgent<SuperAgentRequest>;
@@ -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<Response> /* 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;
+186 -178
View File
@@ -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);
});
+1 -1
View File
@@ -20,4 +20,4 @@
"index.d.ts",
"superagent-tests.ts"
]
}
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+126
View File
@@ -0,0 +1,126 @@
// Type definitions for SuperAgent 2.3
// Project: https://github.com/visionmedia/superagent
// Definitions by: Alex Varju <https://github.com/varju/>
// Nico Zelaya <https://github.com/NicoZelaya/>
// Michael Ledin <https://github.com/mxl/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
/// <reference types="node" />
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<SuperAgentRequest> {
(url: string): SuperAgentRequest;
// tslint:disable-next-line:unified-signatures
(method: string, url: string): SuperAgentRequest;
agent(): SuperAgent<SuperAgentRequest>;
}
interface SuperAgent<Req> 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<Response> /* 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;
+314
View File
@@ -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);
});
+27
View File
@@ -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"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1
View File
@@ -2,6 +2,7 @@
// Project: https://github.com/visionmedia/supertest
// Definitions by: Alex Varju <https://github.com/varju/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
import * as superagent from "superagent"