Merge branch 'master' into NodeJS.EventEmitter.6

This commit is contained in:
Burt Harris
2016-08-30 19:11:19 -07:00
84 changed files with 11130 additions and 3102 deletions

View File

@@ -42,6 +42,7 @@ interface Auth0ClientOptions {
/** Represents a normalized UserProfile. */
interface Auth0UserProfile {
email: string;
email_verified: boolean;
family_name: string;
gender: string;
given_name: string;

View File

@@ -42,6 +42,40 @@ interface Contacts {
*/
pickContact(onSuccess: (contact: Contact) => void,
onError: (error: ContactError) => void): void
/**
* This allows us to use an enumeration when setting the desired fields for the ContactFindOptions.
* The values will correspond to the type of string literals in ContactFieldType.
*/
fieldType: {
addresses: "addresses",
birthday: "birthday",
categories: "categories",
country: "country",
department: "department",
displayName: "displayName",
emails: "emails",
familyName: "familyName",
formatted: "formatted",
givenName: "givenName",
honorificPrefix: "honorificPrefix",
honorificSuffix: "honorificSuffix",
id: "id",
ims: "ims",
locality: "locality",
middleName: "middleName",
name: "name",
nickname: "nickname",
note: "note",
organizations: "organizations",
phoneNumbers: "phoneNumbers",
photos: "photos",
postalCode: "postalCode",
region: "region",
streetAddress: "streetAddress",
title: "title",
urls: "urls"
}
}
interface ContactProperties {
@@ -105,7 +139,7 @@ interface Contact extends ContactProperties {
declare var Contact: {
/** Constructor of Contact object */
new(id?: string,
new (id?: string,
displayName?: string,
name?: ContactName,
nickname?: string,
@@ -130,7 +164,7 @@ interface ContactError {
}
declare var ContactError: {
new(code: number): ContactError;
new (code: number): ContactError;
UNKNOWN_ERROR: number;
INVALID_ARGUMENT_ERROR: number;
TIMEOUT_ERROR: number;
@@ -158,7 +192,7 @@ interface ContactName {
declare var ContactName: {
/** Constructor for ContactName object */
new(formatted?: string,
new (formatted?: string,
familyName?: string,
givenName?: string,
middleName?: string,
@@ -189,7 +223,7 @@ interface ContactField {
declare var ContactField: {
/** Constructor for ContactField object */
new(type?: string,
new (type?: string,
value?: string,
pref?: boolean): ContactField
};
@@ -219,7 +253,7 @@ interface ContactAddress {
declare var ContactAddress: {
/** Constructor of ContactAddress object */
new(pref?: boolean,
new (pref?: boolean,
type?: string,
formatted?: string,
streetAddress?: string,
@@ -248,7 +282,7 @@ interface ContactOrganization {
declare var ContactOrganization: {
/** Constructor for ContactOrganization object */
new(pref?: boolean,
new (pref?: boolean,
type?: string,
name?: string,
department?: string,
@@ -262,12 +296,42 @@ interface ContactFindOptions {
/** Determines if the find operation returns multiple navigator.contacts. */
multiple?: boolean;
/* Contact fields to be returned back. If specified, the resulting Contact object only features values for these fields. */
desiredFields?: string[];
desiredFields?: ContactFieldType[];
}
/** these are the string values that are valid for the desired fields in ContactFindOptions */
declare type ContactFieldType =
"addresses"
| "birthday"
| "categories"
| "country"
| "department"
| "displayName"
| "emails"
| "familyName"
| "formatted"
| "givenName"
| "honorificPrefix"
| "honorificSuffix"
| "id"
| "ims"
| "locality"
| "middleName"
| "name"
| "nickname"
| "note"
| "organizations"
| "phoneNumbers"
| "photos"
| "postalCode"
| "region"
| "streetAddress"
| "title"
| "urls";
declare var ContactFindOptions: {
/** Constructor for ContactFindOptions object */
new(filter?: string,
new (filter?: string,
multiple?: boolean,
desiredFields?: string[]): ContactFindOptions
};
desiredFields?: ContactFieldType[]): ContactFindOptions
};

View File

@@ -0,0 +1,26 @@
/// <reference path="./diff2html.d.ts" />
import Diff2Html = require('diff2html');
let d2h = Diff2Html.Diff2Html;
class Diff2HtmlOptionsImpl implements Diff2Html.Options {
constructor (public inputFormat: string) {
}
}
let strInput =
'diff --git a/sample b/sample\n' +
'index 0000001..0ddf2ba\n' +
'--- a/sample\n' +
'+++ b/sample\n' +
'@@ -1 +1 @@\n' +
'-test\n' +
'+test1r\n';
let strConfiguration = new Diff2HtmlOptionsImpl('diff');
let diffInput = d2h.getJsonFromDiff(strInput, strConfiguration);
let diffConfiguration = new Diff2HtmlOptionsImpl('json');
let htmlString = d2h.getPrettyHtml(diffInput, diffConfiguration);
console.log(htmlString);

66
diff2html/diff2html.d.ts vendored Normal file
View File

@@ -0,0 +1,66 @@
// Type definitions for diff2html
// Project: https://github.com/rtfpessoa/diff2html
// Definitions by: rtfpessoa <https://github.com/rtfpessoa/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace Diff2Html {
export interface Options {
inputFormat?: string;
outputFormat?: string;
showFiles?: boolean;
matching?: string;
synchronisedScroll?: boolean;
matchWordsThreshold?: number;
matchingMaxComparisons?: number;
}
export interface Line {
content: string;
type: string;
oldNumber: number;
newNumber: number;
}
export interface Block {
oldStartLine: number;
oldStartLine2?: number;
newStartLine: number;
header: string;
lines: Line[];
}
export interface Result {
addedLines: number;
deletedLines: number;
isCombined: boolean;
isGitDiff: boolean;
oldName: string;
newName: string;
language: string;
blocks: Block[];
oldMode?: string;
newMode?: string;
deletedFileMode?: string;
newFileMode?: string;
isDeleted?: boolean;
isNew?: boolean;
isCopy?: boolean;
isRename?: boolean;
unchangedPercentage?: number;
changedPercentage?: number;
checksumBefore?: string;
checksumAfter?: string;
mode?: string;
}
export interface Diff2Html {
getJsonFromDiff(input: string, configuration?: Options): Result;
getPrettyHtml(input: any, configuration?: Options): string;
}
}
declare module "diff2html" {
var d2h: { "Diff2Html": Diff2Html.Diff2Html };
export = d2h;
}

View File

@@ -0,0 +1,25 @@
/// <reference path="../estree/estree.d.ts" />
/// <reference path="esprima-walk.d.ts" />
import * as walk from 'esprima-walk'
var program: ESTree.Program
var string: string
var node: ESTree.Node
walk(program, _node => {
string = node.type
node = _node
})
walk.walk(program, _node => {
string = node.type
node = _node
})
walk.walkAddParent(program, _node => {
node = _node
node = _node.parent
string = node.type
})

40
esprima-walk/esprima-walk.d.ts vendored Normal file
View File

@@ -0,0 +1,40 @@
// Type definitions for esprima-walk v0.1.0
// Project: https://github.com/jrajav/esprima-walk
// Definitions by: tswaters <https://github.com/tswaters>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../estree/estree.d.ts" />
declare module "esprima-walk" {
interface NodeWithParent extends ESTree.Node {
parent?: ESTree.Node
}
/**
* Walk the provided AST; fn is called once for each node with a `type`
* @param {ESTree.Program} ast program to walk
* @param {function} fn function invoked for each node with type
*/
function walk (ast: ESTree.Program, fn:(node: ESTree.Node)=>void) :void
namespace walk {
/**
* Walk the provided AST; fn is called once for each node with a `type`
* @param {ESTree.Program} ast program to walk
* @param {function} fn function invoked for each node
*/
export function walk (ast: ESTree.Program, fn:(node: ESTree.Node)=>void) :void
/**
* Walk the provided AST; fn is called once for each node with a `type`.
* Adds a parent property prior to invoking fn when applicable
* @param {ESTree.Program} ast program to walk
* @param {function} fn function invoked for each node
*/
export function walkAddParent (ast: ESTree.Program, fn:(node: NodeWithParent)=>void) :void
}
export = walk
}

View File

@@ -121,7 +121,7 @@ declare module "express-serve-static-core" {
httpOnly?: boolean;
path?: string;
domain?: string;
secure?: boolean;
secure?: boolean | 'auto';
}
interface Errback { (err: Error): void; }
@@ -199,7 +199,7 @@ declare module "express-serve-static-core" {
/**
* Returns the first accepted charset of the specified character sets,
* based on the requests Accept-Charset HTTP header field.
* based on the request's Accept-Charset HTTP header field.
* If none of the specified charsets is accepted, returns false.
*
* For more information, or if you have issues or concerns, see accepts.
@@ -212,7 +212,7 @@ declare module "express-serve-static-core" {
/**
* Returns the first accepted encoding of the specified encodings,
* based on the requests Accept-Encoding HTTP header field.
* based on the request's Accept-Encoding HTTP header field.
* If none of the specified encodings is accepted, returns false.
*
* For more information, or if you have issues or concerns, see accepts.
@@ -225,7 +225,7 @@ declare module "express-serve-static-core" {
/**
* Returns the first accepted language of the specified languages,
* based on the requests Accept-Language HTTP header field.
* based on the request's Accept-Language HTTP header field.
* If none of the specified languages is accepted, returns false.
*
* For more information, or if you have issues or concerns, see accepts.

View File

@@ -6,7 +6,8 @@ import session = require('express-session');
var app = express();
app.use(session({
secret: 'keyboard cat'
secret: 'keyboard cat',
cookie: { secure: 'auto' }
}));
app.use(session({
secret: 'keyboard cat',

View File

@@ -0,0 +1,17 @@
/// <reference path='fill-pdf.d.ts' />
import * as fillPdf from 'fill-pdf';
var formData: fillPdf.FormData = { FieldName: 'Text to put into form field' };
var pdfTemplatePath = 'templates.pdf';
var extendArgs: string[] = [];
fillPdf.generatePdf(formData, pdfTemplatePath, extendArgs, (err: Error, output: Buffer) => {
if ( !err ) {
console.log('Success!');
// output is a buffer
}
});
var result = fillPdf.generateFdf(formData);
// result is a buffer

16
fill-pdf/fill-pdf.d.ts vendored Normal file
View File

@@ -0,0 +1,16 @@
// Type definitions for fill-pdf v0.5.0
// Project: https://github.com/dommmel/fill-pdf
// Definitions by: Seth Westphal <https://github.com/westy92>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module 'fill-pdf' {
export interface FormData {
[name: string]: string;
}
export function generatePdf(data: FormData, templatePath: string, extendArgs: string[], callback?: (err: Error, output: Buffer) => void): void;
export function generateFdf(data: FormData): Buffer;
}

View File

@@ -318,7 +318,7 @@ interface JQuery {
/**
* Moves the calendar to an arbitrary date.
*/
fullCalendar(method: 'gotoDate', date: Date | string): void;
fullCalendar(method: 'gotoDate', date: moment.Moment | Date | string): void;
/**
* Moves the calendar forward/backward an arbitrary amount of time.
@@ -403,4 +403,4 @@ interface JQuery {
interface JQueryStatic {
fullCalendar: FullCalendar.Calendar;
}
}

View File

@@ -427,7 +427,7 @@ declare namespace google.maps {
/**
* Marker position. Required.
*/
position: LatLng;
position: LatLng|LatLngLiteral;
/** Image map region definition used for drag/click. */
shape?: MarkerShape;
/** Rollover text. */

View File

@@ -0,0 +1,24 @@
/// <reference path="graphlib.d.ts" />
import * as graphlib from 'graphlib';
function test_graph() {
var g = new graphlib.Graph();
g.setEdge('a', 'b');
g.setEdge('a', 'b', 1.023);
g.edge('a', 'b');
g.edge({v: 'a', w: 'b'});
graphlib.json.read(graphlib.json.write(g));
graphlib.alg.dijkstra(g, 'a', e => g.edge(e));
graphlib.alg.dijkstraAll(g, e => g.edge(e));
graphlib.alg.dijkstraAll(g);
graphlib.alg.findCycles(g);
graphlib.alg.isAcyclic(g);
graphlib.alg.prim(g, e => g.edge(e));
graphlib.alg.tarjan(g);
graphlib.alg.topsort(g);
}

291
graphlib/graphlib.d.ts vendored Normal file
View File

@@ -0,0 +1,291 @@
// Type definitions for graphlib 2.1.1
// Project: https://github.com/cpettitt/graphlib
// Definitions by: Dan Vanderkam <http://danvk.org/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "graphlib" {
export interface GraphOptions {
directed?: boolean; // default: true.
multigraph?: boolean; // default: false.
compound?: boolean; // default: false.
}
export interface Edge {
v: string;
w: string;
/** The name that uniquely identifies a multi-edge. */
name?: string;
}
// TODO: add template parameters for edge and vertex labels?
export class Graph {
constructor(options?: GraphOptions);
/**
* Creates or updates the value for the node v in the graph. If label is supplied
* it is set as the value for the node. If label is not supplied and the node was
* created by this call then the default node label will be assigned. Returns the
* graph, allowing this to be chained with other functions. Takes O(1) time.
*/
setNode(name: string, label?: any): Graph;
hasNode(name: string): boolean;
/**
* Remove the node with the id v in the graph or do nothing if the node is not in
* the graph. If the node was removed this function also removes any incident
* edges. Returns the graph, allowing this to be chained with other functions.
* Takes O(|E|) time. */
removeNode(name: string): Graph;
nodes(): string[];
/** Returns the label for this node. */
node(name: string): any;
/**
* Creates or updates the label for the edge (v, w) with the optionally supplied
* name. If label is supplied it is set as the value for the edge. If label is not
* supplied and the edge was created by this call then the default edge label will
* be assigned. The name parameter is only useful with multigraphs. Returns the
* graph, allowing this to be chained with other functions. Takes O(1) time.
*/
setEdge(v: string, w: string, label?: any): Graph;
edges(): Edge[];
/** Returns the label for this edge. */
edge(v: string, w: string): any;
edge(e: Edge): any;
/**
* Return all edges that point to the node v. Optionally filters those edges down to just those
* coming from node u. Behavior is undefined for undirected graphs - use nodeEdges instead.
* Returns undefined if node v is not in the graph. Takes O(|E|) time.
*/
inEdges(v: string, u?: string): Edge[];
/**
* Return all edges that are pointed at by node v. Optionally filters those edges down to just
* those point to w. Behavior is undefined for undirected graphs - use nodeEdges instead.
* Returns undefined if node v is not in the graph. Takes O(|E|) time.
*/
outEdges(v: string, w?: string): Edge[];
/**
* Returns all edges to or from node v regardless of direction. Optionally filters those edges
* down to just those between nodes v and w regardless of direction. Returns undefined if node v
* is not in the graph. Takes O(|E|) time.
*/
nodeEdges(v: string, w?: string): Edge[];
/**
* Return all nodes that are predecessors of the specified node or undefined if node v is not in
* the graph. Behavior is undefined for undirected graphs - use neighbors instead. Takes O(|V|)
* time.
*/
predecessors(node: string): string[];
/**
* Return all nodes that are successors of the specified node or undefined if node v is not in
* the graph. Behavior is undefined for undirected graphs - use neighbors instead. Takes O(|V|)
* time.
*/
successors(node: string): string[];
/**
* Return all nodes that are predecessors or successors of the specified node or undefined if
* node v is not in the graph. Takes O(|V|) time.
*/
neighbors(node: string): string[];
isDirected(): boolean;
isMultigraph(): boolean;
isCompound(): boolean;
/** Sets the label for the graph to label. */
setGraph(label: string): void;
/**
* Returns the currently assigned label for the graph. If no label has been assigned,
* returns undefined.
*/
graph(): string;
/**
* Returns the number of nodes in the graph.
*/
nodeCount(): number;
/**
* Returns the number of edges in the graph.
*/
edgeCount(): number;
/** Returns those nodes in the graph that have no in-edges. Takes O(|V|) time. */
sources(): string[];
/** Returns those nodes in the graph that have no out-edges. Takes O(|V|) time. */
sinks(): string[];
}
export namespace json {
/**
* Creates a JSONrepresentation of the graph that can be serialized to a string with
* JSON.stringify. The graph can later be restored using json.read.
*/
function write(g: Graph): Object;
/**
* Takes JSON as input and returns the graph representation. For example, if we have
* serialized the graph in json-write to a string named str, we can restore it to a
* graph as follows:
*
* var g2 = graphlib.json.read(JSON.parse(str));
* g2.nodes();
* // ['a', 'b']
* g2.edges()
* // [ { v: 'a', w: 'b' } ]
*/
function read(json: Object): Graph;
}
export interface Path {
distance: number;
predecessor: string;
}
export namespace alg {
/**
* Finds all connected components in a graph and returns an array of these components.
* Each component is itself an array that contains the ids of nodes in the component.
* This function takes O(|V|) time.
*/
function components(g: Graph): string[][];
/**
* This function is an implementation of Dijkstra's algorithm which finds the shortest
* path from source to all other nodes in g. This function returns a map of
* v -> { distance, predecessor }. The distance property holds the sum of the weights
* from source to v along the shortest path or Number.POSITIVE_INFINITY if there is no path
* from source. The predecessor property can be used to walk the individual elements of the
* path from source to v in reverse order.
*
* It takes an optional weightFn(e) which returns the weight of the edge e. If no weightFn
* is supplied then each edge is assumed to have a weight of 1. This function throws an
* Error if any of the traversed edges have a negative edge weight.
*
* It takes an optional edgeFn(v) which returns the ids of all edges incident to the node v
* for the purposes of shortest path traversal. By default this function uses the g.outEdges.
*
* It takes O((|E| + |V|) * log |V|) time.
*/
function dijkstra(
graph: Graph,
source: string,
weightFn?: (e: Edge) => number,
edgeFn?: (v: string) => Edge[]
): {[node: string]: Path};
/**
* This function finds the shortest path from each node to every other reachable node in
* the graph. It is similar to alg.dijkstra, but instead of returning a single-source
* array, it returns a mapping of of source -> alg.dijksta(g, source, weightFn, edgeFn).
*
* This function takes an optional weightFn(e) which returns the weight of the edge e.
* If no weightFn is supplied then each edge is assumed to have a weight of 1. This
* function throws an Error if any of the traversed edges have a negative edge weight.
*
* This function takes an optional edgeFn(u) which returns the ids of all edges incident
* to the node u for the purposes of shortest path traversal. By default this function
* uses g.outEdges.
*
* This function takes O(|V| * (|E| + |V|) * log |V|) time.
*/
function dijkstraAll(
graph: Graph,
weightFn?: (e: Edge) => number,
edgeFn?: (v: string) => Edge[]
): {[source: string]: {[node: string]: Path}};
/**
* Given a Graph, g, this function returns all nodes that are part of a cycle. As there
* may be more than one cycle in a graph this function return an array of these cycles,
* where each cycle is itself represented by an array of ids for each node involved in
* that cycle.
*
* alg.isAcyclic is more efficient if you only need to determine whether a graph has a
* cycle or not.
*/
function findCycles(graph: Graph): string[][];
/**
* This function is an implementation of the Floyd-Warshall algorithm, which finds the
* shortest path from each node to every other reachable node in the graph. It is similar
* to alg.dijkstraAll, but it handles negative edge weights and is more efficient for some types
* of graphs. This function returns a map of source -> { target -> { distance, predecessor }.
* The distance property holds the sum of the weights from source to target along the shortest
* path of Number.POSITIVE_INFINITY if there is no path from source. The predecessor property
* can be used to walk the individual elements of the path from source to target in reverse
* order.
*
* This function takes an optional weightFn(e) which returns the weight of the edge e. If no
* weightFunc is supplied then each edge is assumed to have a weight of 1.
*
* This function takes an optional edgeFn(v) which returns the ids of all edges incident to the
* node v for the purposes of shortest path traversal. By default this function uses the
* outEdges function on the supplied graph.
*
* This algorithm takes O(|V|^3) time.
*/
function floydWarshall(
graph: Graph,
weightFn?: (e: Edge) => number,
edgeFn?: (v: string) => Edge[]
): {[source: string]: {[node: string]: Path}};
/**
* Given a Graph, g, this function returns true if the graph has no cycles and returns false if it
* does. This algorithm returns as soon as it detects the first cycle. You can use alg.findCycles
* to get the actual list of cycles in the graph.
*/
function isAcyclic(graph: Graph): boolean;
/**
* Prim's algorithm takes a connected undirected graph and generates a minimum spanning tree. This
* function returns the minimum spanning tree as an undirected graph. This algorithm is derived
* from the description in "Introduction to Algorithms", Third Edition, Cormen, et al., Pg 634.
*
* This function takes a weightFn(e) which returns the weight of the edge e. It throws an Error if
* the graph is not connected.
*
* This function takes O(|E| log |V|) time.
*/
function prim(graph: Graph, weightFn: (e: Edge) => number): Graph;
/**
* This function is an implementation of Tarjan's algorithm which finds all strongly connected
* components in the directed graph g. Each strongly connected component is composed of nodes that
* can reach all other nodes in the component via directed edges. A strongly connected component
* can consist of a single node if that node cannot both reach and be reached by any other
* specific node in the graph. Components of more than one node are guaranteed to have at least
* one cycle.
*
* This function returns an array of components. Each component is itself an array that contains
* the ids of all nodes in the component.
*/
function tarjan(graph: Graph): string[][];
/**
* An implementation of topological sorting.
*
* Given a Graph g this function returns an array of nodes such that for each edge u -> v, u
* appears before v in the array. If the graph has a cycle it is impossible to generate such a
* list and CycleException is thrown.
*
* Takes O(|V| + |E|) time.
*/
function topsort(graph: Graph): string[];
}
}

View File

@@ -0,0 +1,36 @@
/// <reference path="../gulp/gulp.d.ts"/>
/// <reference path="../gulp-angular-templatecache/gulp-angular-templatecache.d.ts"/>
import * as gulp from 'gulp';
import * as templateCache from 'gulp-angular-templatecache';
gulp.task('templatecache:no-arguments', function () {
return gulp.src('templates/**/*.html')
.pipe(templateCache())
.pipe(gulp.dest('public'));
});
gulp.task('templatecache:with-filename', function () {
return gulp.src('templates/**/*.html')
.pipe(templateCache('templates.js'))
.pipe(gulp.dest('public'));
});
gulp.task('templatecache:with-options', function () {
return gulp.src('templates/**/*.html')
.pipe(templateCache({
filename: 'templates.js',
standalone: true,
module: 'app.templates'
}))
.pipe(gulp.dest('public'));
});
gulp.task('templatecache:with-filename-and-options', function () {
return gulp.src('templates/**/*.html')
.pipe(templateCache('templates.js', {
standalone: true,
module: 'app.templates'
}))
.pipe(gulp.dest('public'));
});

View File

@@ -0,0 +1,69 @@
// Type definitions for gulp-angular-templatecache v2.0.0
// Project: https://github.com/miickel/gulp-angular-templatecache
// Definitions by: Aman Mahajan <https://github.com/amanmahajan7>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts"/>
declare module "gulp-angular-templatecache" {
function templatecache(): NodeJS.ReadWriteStream;
function templatecache(filename: string): NodeJS.ReadWriteStream;
function templatecache(options: templatecache.Options): NodeJS.ReadWriteStream;
function templatecache(filename: string, options: templatecache.Options): NodeJS.ReadWriteStream;
namespace templatecache {
interface Options {
/**
* Name to use when concatenating.
*/
filename?: string;
/**
* Prefix for template URLs.
*/
root?: string;
/**
* Name of AngularJS module.
*/
module?: string;
/**
* Create a new AngularJS module, instead of using an existing.
*/
standalone?: boolean;
/**
* Override file base path.
*/
base?: string | Function;
/**
* Wrap the templateCache in a module system. Currently supported systems: RequireJS, Browserify, ES6 and IIFE (Immediately-Invoked Function Expression).
*/
moduleSystem?: string;
/**
* Transform the generated URL before it's put into $templateCache.
*/
transformUrl?: Function;
/**
* Override template header.
*/
templateHeader?: string;
/**
* Override template body.
*/
templateBody?: string;
/**
* Override template footer.
*/
templateFooter?: string;
}
}
export = templatecache;
}

View File

@@ -0,0 +1,82 @@
// Test file for HERE Maps API for JavaScript Definition file
/// <reference path="heremaps.d.ts" />
/**
* EXAMPLE from the HERE Maps API
* Takes a snapshot of the map.
*
* @param {Element} resultContainer Reference to DOM Element to show the captured map area
* @param {H.Map} map Reference to initialized map object
* @param {H.ui.UI} ui Reference to UI component
*/
function capture(resultContainer: HTMLElement, map: H.Map, ui: H.ui.UI) {
// Capturing area of the map is asynchronous, callback function receives HTML5 canvas
// element with desired map area rendered on it.
// We also pass an H.ui.UI reference in order to see the ScaleBar in the output.
// If dimensions are omitted, whole veiw port will be captured
map.capture((canvas: HTMLCanvasElement) => {
if (canvas) {
resultContainer.innerHTML = '';
resultContainer.appendChild(canvas);
} else {
// For example when map is in Panorama mode
resultContainer.innerHTML = 'Capturing is not supported';
}
}, [ui], 50, 50, 500, 200);
}
/**
* Boilerplate map initialization code starts below:
*/
// Step 1: initialize communication with the platform
var platform = new H.service.Platform({
app_id: 'DemoAppId01082013GAL',
app_code: 'AJKnXv84fjrb0KIHawS0Tg',
useHTTPS: true,
useCIT: true
});
var defaultLayers = platform.createDefaultLayers();
var mapContainer = document.getElementById('map');
// Step 2: initialize a map
var map = new H.Map(mapContainer, defaultLayers.normal.map, {
// initial center and zoom level of the map
zoom: 16,
// Champs-Elysees
center: {lat: 48.869145, lng: 2.314298}
});
// Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Step 4: Create the default UI
var ui = H.ui.UI.createDefault(map, defaultLayers, 'en-US');
// Step 6: Create "Capture" button and place for showing the captured area
var resultContainer = document.getElementById('panel');
// Create container for the "Capture" button
var containerNode = document.createElement('div');
containerNode.setAttribute('style',
'position:absolute;top:0;left:0;background-color:#fff; padding:10px;');
containerNode.className = 'btn-group';
// Create the "Capture" button
var captureBtn = document.createElement('input');
captureBtn.value = 'Capture';
captureBtn.type = 'button';
captureBtn.className = 'btn btn-sm btn-default';
// Add both button and container to the DOM
containerNode.appendChild(captureBtn);
mapContainer.appendChild(containerNode);
// Step 7: Handle capture button click event
captureBtn.onclick = function() {
capture(resultContainer, map, ui);
};

6045
heremaps/heremaps.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,13 @@
/// <reference path='html-pdf.d.ts' />
/// <reference path='../node/node.d.ts' />
import * as fs from 'fs';
import * as pdf from 'html-pdf';
var html = fs.readFileSync('./test/businesscard.html', 'utf8');
var options: pdf.CreateOptions = { format: 'Letter' };
pdf.create(html, options).toFile('./businesscard.pdf', (err: Error, res: pdf.FileInfo) => {
if (err) return console.log(err);
console.log(res); // { filename: '/app/businesscard.pdf' }
});

80
html-pdf/html-pdf.d.ts vendored Normal file
View File

@@ -0,0 +1,80 @@
// Type definitions for html-pdf v2.1.0
// Project: https://github.com/marcbachmann/node-html-pdf
// Definitions by: Seth Westphal <https://github.com/westy92>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path='../node/node.d.ts' />
declare module 'html-pdf' {
import * as fs from 'fs';
export interface CreateOptions {
// Export options
directory?: string;
// Papersize Options: http://phantomjs.org/api/webpage/property/paper-size.html
height?: string;
width?: string;
format?: 'A3' | 'A4' | 'A5' | 'Legal' | 'Letter' | 'Tabloid';
orientation?: 'portrait' | 'landscape';
// Page options
border?: string | {
top?: string;
right?: string;
bottom?: string;
left?: string;
};
header?: {
height?: string;
contents?: string;
};
footer?: {
height?: string;
contents?: {
first?: string;
[page: number]: string;
default?: string;
last?: string;
};
};
// Rendering options
base?: string;
// Zooming option, can be used to scale images if `options.type` is not pdf
zoomFactor?: string;
// File options
type?: 'png' | 'jpeg' | 'pdf';
quality?: string;
// Script options
phantomPath?: string;
phantomArgs?: string[];
script?: string;
timeout?: number;
// HTTP Headers that are used for requests
httpHeaders?: {
[header: string]: string;
};
}
export interface FileInfo {
filename: string;
}
export interface CreateResult {
toBuffer(callback: (err: Error, buffer: Buffer) => void): void;
toFile(callback: (err: Error, res: FileInfo) => void): void;
toFile(filename?: string, callback?: (err: Error, res: FileInfo) => void): void;
toStream(callback: (err: Error, stream: fs.ReadStream) => void): void;
}
export function create(html: string, options?: CreateOptions): CreateResult;
}

View File

@@ -4,51 +4,52 @@ import { inject, Kernel } from "inversify";
import { autoProvide, makeProvideDecorator, makeFluentProvideDecorator } from "inversify-binding-decorators";
module decorator {
let kernel = new Kernel();
let provide = makeProvideDecorator(kernel);
interface INinja {
interface Warrior {
fight(): string;
sneak(): string;
}
interface IKatana {
interface Weapon {
hit(): string;
}
interface IShuriken {
interface ThrowableWeapon {
throw(): string;
}
let TYPE = {
IKatana: "IKatana",
INinja: "INinja",
IShuriken: "IShuriken"
ThrowableWeapon: "ThrowableWeapon",
Warrior: "Warrior",
Weapon: "Weapon"
};
@provide(TYPE.IKatana)
class Katana implements IKatana {
@provide(TYPE.Weapon)
class Katana implements Weapon {
public hit() {
return "cut!";
}
}
@provide(TYPE.IShuriken)
class Shuriken implements IShuriken {
@provide(TYPE.ThrowableWeapon)
class Shuriken implements ThrowableWeapon {
public throw() {
return "hit!";
}
}
@provide(TYPE.INinja)
class Ninja implements INinja {
@provide(TYPE.Warrior)
class Ninja implements Warrior {
private _katana: IKatana;
private _shuriken: IShuriken;
private _katana: Weapon;
private _shuriken: ThrowableWeapon;
public constructor(
@inject("IKatana") katana: IKatana,
@inject("IShuriken") shuriken: IShuriken
@inject(TYPE.Weapon) katana: Weapon,
@inject(TYPE.ThrowableWeapon) shuriken: ThrowableWeapon
) {
this._katana = katana;
this._shuriken = shuriken;
@@ -59,12 +60,13 @@ module decorator {
}
let ninja = kernel.get<INinja>(TYPE.INinja);
let ninja = kernel.get<Warrior>(TYPE.Warrior);
console.log(ninja);
}
module fluent_decorator {
let kernel = new Kernel();
let provide = makeFluentProvideDecorator(kernel);
@@ -76,27 +78,27 @@ module fluent_decorator {
return provide(identifier).done();
};
interface INinja {
interface Warrior {
fight(): string;
sneak(): string;
}
interface IKatana {
interface Weapon {
hit(): string;
}
interface IShuriken {
interface ThrowableWeapon {
throw(): string;
}
let TYPE = {
IKatana: "IKatana",
INinja: "INinja",
IShuriken: "IShuriken"
ThrowableWeapon: "ThrowableWeapon",
Warrior: "Warrior",
Weapon: "Weapon"
};
@provideSingleton(TYPE.IKatana)
class Katana implements IKatana {
@provideSingleton(TYPE.Weapon)
class Katana implements Weapon {
private _mark: any;
public constructor() {
this._mark = Math.random();
@@ -106,8 +108,8 @@ module fluent_decorator {
}
}
@provideTransient(TYPE.IShuriken)
class Shuriken implements IShuriken {
@provideTransient(TYPE.ThrowableWeapon)
class Shuriken implements ThrowableWeapon {
private _mark: any;
public constructor() {
this._mark = Math.random();
@@ -117,15 +119,15 @@ module fluent_decorator {
}
}
@provideTransient(TYPE.INinja)
class Ninja implements INinja {
@provideTransient(TYPE.Warrior)
class Ninja implements Warrior {
private _katana: IKatana;
private _shuriken: IShuriken;
private _katana: Weapon;
private _shuriken: ThrowableWeapon;
public constructor(
@inject("IKatana") katana: IKatana,
@inject("IShuriken") shuriken: IShuriken
@inject(TYPE.Weapon) katana: Weapon,
@inject(TYPE.ThrowableWeapon) shuriken: ThrowableWeapon
) {
this._katana = katana;
this._shuriken = shuriken;
@@ -136,7 +138,7 @@ module fluent_decorator {
}
let ninja = kernel.get<INinja>(TYPE.INinja);
let ninja = kernel.get<Warrior>(TYPE.Warrior);
console.log(ninja);
}

View File

@@ -1,4 +1,4 @@
// Type definitions for inversify 1.0.0-beta.5
// Type definitions for inversify-binding-decorators 1.0.0
// Project: https://github.com/inversify/inversify-binding-decorators
// Definitions by: inversify <https://github.com/inversify/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -7,46 +7,50 @@
declare namespace inversifyBindingDecorators {
interface IProvideInSyntax<T> extends IProvideDoneSyntax<T> {
inSingletonScope(): IProvideWhenOnSyntax<T>;
}
namespace interfaces {
interface IProvideDoneSyntax<T> {
done(): (target: any) => any;
}
export interface ProvideInSyntax<T> extends ProvideDoneSyntax<T> {
inSingletonScope(): ProvideWhenOnSyntax<T>;
}
interface IProvideOnSyntax<T> extends IProvideDoneSyntax<T> {
onActivation(fn: (context: inversify.interfaces.Context, injectable: T) => T): IProvideWhenSyntax<T>;
}
export interface ProvideDoneSyntax<T> {
done(): (target: any) => any;
}
interface IProvideInWhenOnSyntax<T> extends IProvideInSyntax<T>, IProvideWhenSyntax<T>, IProvideOnSyntax<T> {}
export interface ProvideOnSyntax<T> extends ProvideDoneSyntax<T> {
onActivation(fn: (context: inversify.interfaces.Context, injectable: T) => T): ProvideWhenSyntax<T>;
}
interface IProvideWhenOnSyntax<T> extends IProvideWhenSyntax<T>, IProvideOnSyntax<T> {}
export interface ProvideInWhenOnSyntax<T> extends ProvideInSyntax<T>, ProvideWhenSyntax<T>, ProvideOnSyntax<T> {}
export interface ProvideWhenOnSyntax<T> extends ProvideWhenSyntax<T>, ProvideOnSyntax<T> {}
export interface ProvideWhenSyntax<T> extends ProvideDoneSyntax<T> {
when(constraint: (request: inversify.interfaces.Request) => boolean): ProvideOnSyntax<T>;
whenTargetNamed(name: string): ProvideOnSyntax<T>;
whenTargetTagged(tag: string, value: any): ProvideOnSyntax<T>;
whenInjectedInto(parent: (Function|string)): ProvideOnSyntax<T>;
whenParentNamed(name: string): ProvideOnSyntax<T>;
whenParentTagged(tag: string, value: any): ProvideOnSyntax<T>;
whenAnyAncestorIs(ancestor: (Function|string)): ProvideOnSyntax<T>;
whenNoAncestorIs(ancestor: (Function|string)): ProvideOnSyntax<T>;
whenAnyAncestorNamed(name: string): ProvideOnSyntax<T>;
whenAnyAncestorTagged(tag: string, value: any): ProvideOnSyntax<T>;
whenNoAncestorNamed(name: string): ProvideOnSyntax<T>;
whenNoAncestorTagged(tag: string, value: any): ProvideOnSyntax<T>;
whenAnyAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): ProvideOnSyntax<T>;
whenNoAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): ProvideOnSyntax<T>;
}
interface IProvideWhenSyntax<T> extends IProvideDoneSyntax<T> {
when(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax<T>;
whenTargetNamed(name: string): IProvideOnSyntax<T>;
whenTargetTagged(tag: string, value: any): IProvideOnSyntax<T>;
whenInjectedInto(parent: (Function|string)): IProvideOnSyntax<T>;
whenParentNamed(name: string): IProvideOnSyntax<T>;
whenParentTagged(tag: string, value: any): IProvideOnSyntax<T>;
whenAnyAncestorIs(ancestor: (Function|string)): IProvideOnSyntax<T>;
whenNoAncestorIs(ancestor: (Function|string)): IProvideOnSyntax<T>;
whenAnyAncestorNamed(name: string): IProvideOnSyntax<T>;
whenAnyAncestorTagged(tag: string, value: any): IProvideOnSyntax<T>;
whenNoAncestorNamed(name: string): IProvideOnSyntax<T>;
whenNoAncestorTagged(tag: string, value: any): IProvideOnSyntax<T>;
whenAnyAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax<T>;
whenNoAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax<T>;
}
export function autoProvide(kernel: inversify.interfaces.Kernel, ...modules: any[]): void;
export function makeProvideDecorator(kernel: inversify.interfaces.Kernel):
(serviceIdentifier: (string|Symbol|inversify.interfaces.Newable<any>)) => (target: any) => any;
(serviceIdentifier: inversify.interfaces.ServiceIdentifier<any>) => (target: any) => any;
export function makeFluentProvideDecorator(kernel: inversify.interfaces.Kernel):
(serviceIdentifier: (string|Symbol|inversify.interfaces.Newable<any>)) => IProvideInWhenOnSyntax<any>;
(serviceIdentifier: inversify.interfaces.ServiceIdentifier<any>) => interfaces.ProvideInWhenOnSyntax<any>;
}

View File

@@ -0,0 +1,8 @@
/// <reference path="./inversify-devtools.d.ts" />
import render from "inversify-devtools";
import { Kernel } from "inversify";
let connectKernel = render("root");
let kernel = new Kernel();
connectKernel(kernel);

View File

@@ -0,0 +1,15 @@
// Type definitions for inversify-devtools 1.0.0
// Project: https://github.com/inversify/inversify-devtools
// Definitions by: inversify <https://github.com/inversify/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../inversify/inversify.d.ts" />
interface ConnectKernel extends Function {
(kernel: inversify.interfaces.Kernel): void;
}
declare module "inversify-devtools" {
let render: (container: string) => ConnectKernel;
export default render;
}

View File

@@ -1,21 +1,23 @@
/// <reference path="./inversify-express-utils.d.ts" />
import { InversifyExpressServer, Controller, Get, All, Delete, Head, Put, Patch, Post, Method } from "inversify-express-utils";
import { InversifyExpressServer, Controller, Get, All, Delete, Head, Put, Patch, Post, Method, TYPE } from "inversify-express-utils";
import * as express from "express";
import { Kernel } from "inversify";
let kernel = new Kernel();
module server {
let kernel = new Kernel();
let server = new InversifyExpressServer(kernel);
server
.setConfig((app) => {
.setConfig((app: express.Application) => {
app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
console.log("hello world");
next();
});
})
.setErrorConfig((app) => {
.setErrorConfig((app: express.Application) => {
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
console.error(err.stack);
res.status(500).send("Something broke!");
@@ -55,6 +57,8 @@ module decorators {
public testMethod() { return "METHOD:FOO"; }
}
kernel.bind<Controller>(TYPE.Controller).to(TestController);
function m1(req: express.Request, res: express.Response, next: express.NextFunction) { next(); }
function m2(req: express.Request, res: express.Response, next: express.NextFunction) { next(); }
function m3(req: express.Request, res: express.Response, next: express.NextFunction) { next(); }

View File

@@ -1,4 +1,4 @@
// Type definitions for inversify 1.0.0-alpha.4
// Type definitions for inversify-express-utils 1.0.0
// Project: https://github.com/inversify/inversify-express-utils
// Definitions by: inversify <https://github.com/inversify/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -11,40 +11,50 @@ declare module "inversify-express-utils" {
import * as express from "express";
import * as inversify from "inversify";
interface IInversifyExpressServerConstructor {
new(kernel: inversify.interfaces.Kernel): IInversifyExpressServer;
export namespace interfaces {
export interface InversifyExpressServerConstructor {
new(kernel: inversify.interfaces.Kernel): InversifyExpressServer;
}
export interface InversifyExpressServer {
setConfig(fn: ConfigFunction): InversifyExpressServer;
setErrorConfig(fn: ConfigFunction): InversifyExpressServer;
build(): express.Application;
}
export interface ConfigFunction {
(app: express.Application): void;
}
export interface HandlerDecoratorFactory {
(path: string, ...middleware: express.RequestHandler[]): HandlerDecorator;
}
export interface HandlerDecorator {
(target: any, key: string, value: any): void;
}
}
interface IInversifyExpressServer {
setConfig(fn: IConfigFunction): IInversifyExpressServer;
setErrorConfig(fn: IConfigFunction): IInversifyExpressServer;
build(): express.Application;
export interface Controller {}
interface ServiceIdentifiers {
Controller: Symbol;
}
interface IConfigFunction {
(app: express.Application): void;
}
interface IHandlerDecoratorFactory {
(path: string, ...middleware: express.RequestHandler[]): IHandlerDecorator;
}
interface IHandlerDecorator {
(target: any, key: string, value: any): void;
}
export interface IController {}
export var InversifyExpressServer: IInversifyExpressServerConstructor;
export var InversifyExpressServer: interfaces.InversifyExpressServerConstructor;
export var Controller: (path: string, ...middleware: express.RequestHandler[]) => (target: any) => void;
export var All: IHandlerDecoratorFactory;
export var Get: IHandlerDecoratorFactory;
export var Post: IHandlerDecoratorFactory;
export var Put: IHandlerDecoratorFactory;
export var Patch: IHandlerDecoratorFactory;
export var Head: IHandlerDecoratorFactory;
export var Delete: IHandlerDecoratorFactory;
export var Method: (method: string, path: string, ...middleware: express.RequestHandler[]) => IHandlerDecorator;
export var All: interfaces.HandlerDecoratorFactory;
export var Get: interfaces.HandlerDecoratorFactory;
export var Post: interfaces.HandlerDecoratorFactory;
export var Put: interfaces.HandlerDecoratorFactory;
export var Patch: interfaces.HandlerDecoratorFactory;
export var Head: interfaces.HandlerDecoratorFactory;
export var Delete: interfaces.HandlerDecoratorFactory;
export var Method: (method: string, path: string, ...middleware: express.RequestHandler[]) => interfaces.HandlerDecorator;
export var TYPE: ServiceIdentifiers;
}

View File

@@ -1,4 +1,4 @@
// Type definitions for inversify-inject-decorators 1.0.0-beta.1
// Type definitions for inversify-inject-decorators 1.0.0
// Project: https://github.com/inversify/inversify-inject-decorators
// Definitions by: inversify <https://github.com/inversify/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -7,26 +7,25 @@
declare namespace inversifyInjectDecorators {
interface InjectDecorators {
export interface InjectDecorators {
lazyInject: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable<any>)) =>
lazyInject: (serviceIdentifier: inversify.interfaces.ServiceIdentifier<any>) =>
(proto: any, key: string) => void;
lazyInjectNamed: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable<any>), named: string) =>
lazyInjectNamed: (serviceIdentifier: inversify.interfaces.ServiceIdentifier<any>, named: string) =>
(proto: any, key: string) => void;
lazyInjectTagged: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable<any>), key: string, value: any) =>
lazyInjectTagged: (serviceIdentifier: inversify.interfaces.ServiceIdentifier<any>, key: string, value: any) =>
(proto: any, propertyName: string) => void;
lazyMultiInject: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable<any>)) =>
lazyMultiInject: (serviceIdentifier: inversify.interfaces.ServiceIdentifier<any>) =>
(proto: any, key: string) => void;
}
export function getDecorators(kernel: inversify.interfaces.Kernel): InjectDecorators;
}
declare module "inversify-inject-decorators" {
export default inversifyInjectDecorators.getDecorators;
let getDecorators: (kernel: inversify.interfaces.Kernel) => inversifyInjectDecorators.InjectDecorators;
export default getDecorators;
}

View File

@@ -4,23 +4,23 @@ declare var kernel: inversify.interfaces.Kernel;
import { makeLoggerMiddleware, textSerializer } from "inversify-logger-middleware";
interface ILoggerOutput<T> {
interface LoggerOutput<T> {
entry: T;
}
let makeStringRenderer = function (loggerOutput: ILoggerOutput<string>) {
return function (entry: inversifyLoggerMiddleware.ILogEntry) {
let makeStringRenderer = function (loggerOutput: LoggerOutput<string>) {
return function (entry: inversifyLoggerMiddleware.interfaces.LogEntry) {
loggerOutput.entry = textSerializer(entry);
};
};
let makeObjRenderer = function (loggerOutput: ILoggerOutput<any>) {
return function (entry: inversifyLoggerMiddleware.ILogEntry) {
let makeObjRenderer = function (loggerOutput: LoggerOutput<any>) {
return function (entry: inversifyLoggerMiddleware.interfaces.LogEntry) {
loggerOutput.entry = entry;
};
};
let options: inversifyLoggerMiddleware.ILoggerSettings = {
let options: inversifyLoggerMiddleware.interfaces.LoggerSettings = {
request: {
bindings: {
activated: true,
@@ -48,12 +48,12 @@ let options: inversifyLoggerMiddleware.ILoggerSettings = {
let logger = makeLoggerMiddleware();
kernel.applyMiddleware(logger);
let loggerOutput1: ILoggerOutput<string> = { entry: null };
let loggerOutput1: LoggerOutput<string> = { entry: null };
let stringRenderer1 = makeStringRenderer(loggerOutput1);
let logger1 = makeLoggerMiddleware(options, stringRenderer1);
kernel.applyMiddleware(logger1);
let loggerOutput2: ILoggerOutput<inversifyLoggerMiddleware.ILogEntry> = { entry: null };
let loggerOutput2: LoggerOutput<inversifyLoggerMiddleware.interfaces.LogEntry> = { entry: null };
let objRenderer2 = makeObjRenderer(loggerOutput2);
let logger2 = makeLoggerMiddleware(options, objRenderer2);
kernel.applyMiddleware(logger2);

View File

@@ -1,4 +1,4 @@
// Type definitions for inversify 1.0.0-beta.6
// Type definitions for inversify-logger-middleware 1.0.0
// Project: https://github.com/inversify/inversify-logger-middleware
// Definitions by: inversify <https://github.com/inversify/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -7,50 +7,61 @@
declare namespace inversifyLoggerMiddleware {
export interface ILoggerSettings {
request?: IRequestLoggerSettings;
time?: boolean;
export namespace interfaces {
export interface LoggerSettings {
request?: RequestLoggerSettings;
time?: boolean;
}
export interface RequestLoggerSettings {
serviceIdentifier?: boolean;
bindings?: BindingLoggerSettings;
target?: TargetLoggerSettings;
}
export interface BindingLoggerSettings {
activated?: boolean;
serviceIdentifier?: boolean;
implementationType?: boolean;
factory?: boolean;
provider?: boolean;
constraint?: boolean;
onActivation?: boolean;
cache?: boolean;
dynamicValue?: boolean;
scope?: boolean;
type?: boolean;
}
export interface TargetLoggerSettings {
serviceIdentifier?: boolean;
name?: boolean;
metadata?: boolean;
}
export interface LogEntry {
error: boolean;
exception: any;
guid: string;
multiInject: boolean;
results: any[];
rootRequest: inversify.interfaces.Request;
serviceIdentifier: any;
target: any;
time: string;
}
}
export interface IRequestLoggerSettings {
serviceIdentifier?: boolean;
bindings?: IBindingLoggerSettings;
target?: ITargetLoggerSettings;
}
export function makeLoggerMiddleware(
settings?: interfaces.LoggerSettings,
renderer?: (out: interfaces.LogEntry) => void
): inversify.interfaces.Middleware;
export interface IBindingLoggerSettings {
activated?: boolean;
serviceIdentifier?: boolean;
implementationType?: boolean;
factory?: boolean;
provider?: boolean;
constraint?: boolean;
onActivation?: boolean;
cache?: boolean;
dynamicValue?: boolean;
scope?: boolean;
type?: boolean;
}
export interface ITargetLoggerSettings {
serviceIdentifier?: boolean;
name?: boolean;
metadata?: boolean;
}
export interface ILogEntry {
error: boolean;
exception: any;
multiInject: boolean;
results: any[];
rootRequest: inversify.interfaces.Request;
serviceIdentifier: any;
target: any;
time: string;
}
export function makeLoggerMiddleware(settings?: ILoggerSettings, renderer?: (out: ILogEntry) => void): inversify.interfaces.Middleware;
export function textSerializer(entry: ILogEntry): string;
export function textSerializer(entry: interfaces.LogEntry): string;
export function bindingTypeFormatter(type: number): string;
export function scopeFormatter(scope: number): string;
}

View File

@@ -0,0 +1,91 @@
/// <reference path="./inversify-restify-utils.d.ts" />
import {
InversifyRestifyServer, Controller, Get, Options,
Delete, Head, Put, Patch, Post, Method, TYPE
} from "inversify-restify-utils";
import * as restify from "restify";
import { Kernel } from "inversify";
let kernel = new Kernel();
module server {
let server = new InversifyRestifyServer(kernel);
server
.setConfig((app: restify.Server) => {
app.use((req: restify.Request, res: restify.Response, next: restify.Next) => {
console.log("hello world");
next();
});
})
.build()
.listen(3000, "localhost");
}
module decorators {
@Controller("/")
class TestController {
@Get("/")
public testGet() { return "GET"; }
@Options("/")
public testAll() { return "OPTIONS"; }
@Delete("/")
public testDelete() { return "DELETE"; }
@Head("/")
public testHead() { return "HEAD"; }
@Put("/")
public testPut() { return "PUT"; }
@Patch("/")
public testPatch() { return "PATCH"; }
@Post("/")
public testPost() { return "POST"; }
@Method("opts", "/")
public testMethod() { return "METHOD:OPTS"; }
}
kernel.bind<Controller>(TYPE.Controller).to(TestController);
function m1(req: restify.Request, res: restify.Response, next: restify.Next) { next(); }
function m2(req: restify.Request, res: restify.Response, next: restify.Next) { next(); }
function m3(req: restify.Request, res: restify.Response, next: restify.Next) { next(); }
@Controller("/", m1, m2, m3)
class TestMiddlewareController {
@Get("/", m1, m2, m3)
public testGet() { return "GET"; }
@Options("/", m1, m2, m3)
public testAll() { return "OPTIONS"; }
@Delete("/", m1, m2, m3)
public testDelete() { return "DELETE"; }
@Head("/", m1, m2, m3)
public testHead() { return "HEAD"; }
@Put("/", m1, m2, m3)
public testPut() { return "PUT"; }
@Patch("/", m1, m2, m3)
public testPatch() { return "PATCH"; }
@Post("/", m1, m2, m3)
public testPost() { return "POST"; }
@Method("opts", "/", m1, m2, m3)
public testMethod() { return "METHOD:OPTS"; }
}
}

View File

@@ -0,0 +1,59 @@
// Type definitions for inversify-restify-utils 1.0.0
// Project: https://github.com/inversify/inversify-restify-utils
// Definitions by: inversify <https://github.com/inversify/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../inversify/inversify.d.ts" />
/// <reference path="../restify/restify.d.ts" />
declare module "inversify-restify-utils" {
import * as restify from "restify";
import * as inversify from "inversify";
export namespace interfaces {
export interface InversifyRestifyServerConstructor {
new(kernel: inversify.interfaces.Kernel): InversifyRestifyServer;
}
export interface InversifyRestifyServer {
setConfig(fn: ConfigFunction): InversifyRestifyServer;
build(): restify.Server;
}
export interface ConfigFunction {
(app: restify.Server): void;
}
export interface HandlerDecoratorFactory {
(path: string, ...middleware: restify.RequestHandler[]): HandlerDecorator;
}
export interface HandlerDecorator {
(target: any, key: string, value: any): void;
}
}
export interface Controller {}
interface ServiceIdentifiers {
Controller: Symbol;
}
export var InversifyRestifyServer: interfaces.InversifyRestifyServerConstructor;
export var Controller: (path: string, ...middleware: restify.RequestHandler[]) => (target: any) => void;
export var Options: interfaces.HandlerDecoratorFactory;
export var Get: interfaces.HandlerDecoratorFactory;
export var Post: interfaces.HandlerDecoratorFactory;
export var Put: interfaces.HandlerDecoratorFactory;
export var Patch: interfaces.HandlerDecoratorFactory;
export var Head: interfaces.HandlerDecoratorFactory;
export var Delete: interfaces.HandlerDecoratorFactory;
export var Method: (method: string, path: string, ...middleware: restify.RequestHandler[]) => interfaces.HandlerDecorator;
export var TYPE: ServiceIdentifiers;
}

View File

@@ -1,6 +1,8 @@
/// <reference path="./inversify.d.ts" />
/// <reference path="../harmony-proxy/harmony-proxy.d.ts" />
import * as Proxy from "harmony-proxy";
let injectable = inversify.injectable;
let inject = inversify.inject;
let tagged = inversify.tagged;
@@ -13,10 +15,7 @@ let traverseAncerstors = inversify.traverseAncerstors;
let taggedConstraint = inversify.taggedConstraint;
let namedConstraint = inversify.namedConstraint;
let typeConstraint = inversify.typeConstraint;
let makePropertyMultiInjectDecorator = inversify.makePropertyMultiInjectDecorator;
let makePropertyInjectTaggedDecorator = inversify.makePropertyInjectTaggedDecorator;
let makePropertyInjectNamedDecorator = inversify.makePropertyInjectNamedDecorator;
let makePropertyInjectDecorator = inversify.makePropertyInjectDecorator;
let unmanaged = inversify.unmanaged;
module external_module_test {
@@ -112,7 +111,7 @@ module external_module_test {
// binding types
kernel.bind<Weapon>("Weapon").to(Katana);
kernel.bind<Weapon>("Weapon").toConstantValue(new Katana());
kernel.bind<Weapon>("Weapon").toDynamicValue(() => { return new Katana(); });
kernel.bind<Weapon>("Weapon").toDynamicValue((context: inversify.interfaces.Context) => { return new Katana(); });
kernel.bind<inversify.interfaces.Newable<Weapon>>("Weapon").toConstructor<Weapon>(Katana);
@@ -145,6 +144,7 @@ module external_module_test {
return new Proxy(katanaToBeInjected, handler);
});
@injectable()
class Samurai implements Warrior {
public katana: Weapon;
@@ -161,8 +161,9 @@ module external_module_test {
}
kernel.bind<Samurai>("Samurai").to(Samurai);
kernel.bind<Weapon>("IWeapon").to(Katana).whenTargetTagged("canThrow", false);
kernel.bind<Weapon>("Weapon").to(Katana).whenTargetTagged("canThrow", false);
kernel.bind<ThrowableWeapon>("ThrowableWeapon").to(Shuriken).whenTargetTagged("canThrow", true);
kernel.getAllTagged<Weapon>("Weapon", "canThrow", false);
let throwable = tagged("canThrow", true);
let notThrowable = tagged("canThrow", false);
@@ -200,6 +201,7 @@ module external_module_test {
kernel.bind<Warrior>("Warrior").to(Samurai3);
kernel.bind<Weapon>("Weapon").to(Katana).whenTargetNamed("strong");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenTargetNamed("weak");
kernel.getAllNamed<Weapon>("Weapon", "weak");
@injectable()
class Samurai4 implements Samurai {
@@ -245,18 +247,18 @@ module external_module_test {
// Constraint helpers
kernel.bind<Weapon>("Weapon").to(Shuriken).whenInjectedInto(Ninja);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenInjectedInto("INinja");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenInjectedInto("Ninja");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenParentNamed("chinese");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenParentTagged("canThrow", true);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenTargetNamed("strong");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenTargetTagged("canThrow", true);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorIs(Ninja);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorIs("INinja");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorIs("Ninja");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorNamed("strong");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorTagged("canThrow", true);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorMatches(whenParentNamedCanThrowConstraint);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorIs(Ninja);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorIs("INinja");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorIs("Ninja");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorNamed("strong");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorTagged("canThrow", true);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorMatches(whenParentNamedCanThrowConstraint);
@@ -341,103 +343,42 @@ module external_module_test {
}
module property_injection {
module snapshot {
let kernel = new Kernel();
let TYPES = { Weapon: "Weapon" };
interface Weapon {
durability: number;
use(): void;
}
@injectable()
class Sword implements Weapon {
public durability: number;
public constructor() {
this.durability = 100;
}
public use() {
this.durability = this.durability - 10;
}
}
@injectable()
class WarHammer implements Weapon {
public durability: number;
public constructor() {
this.durability = 100;
}
public use() {
this.durability = this.durability - 10;
}
}
let propertyMultiInject = makePropertyMultiInjectDecorator(kernel);
class Warrior1 {
@propertyMultiInject(TYPES.Weapon)
public weapons: Weapon[];
}
let propertyInject = makePropertyInjectDecorator(kernel);
interface Service {
count: number;
increment(): void;
}
@injectable()
class SomeService implements Service {
public count: number;
public constructor() {
this.count = 0;
}
public increment() {
this.count = this.count + 1;
}
}
class SomeWebComponent {
@propertyInject("Service")
private _service: Service;
public doSomething() {
let count = this._service.count;
this._service.increment();
return count;
}
}
let propertyInjectNammed = makePropertyInjectNamedDecorator(kernel);
class Warrior2 {
@propertyInjectNammed(TYPES.Weapon, "not-throwwable")
@named("not-throwwable")
public primaryWeapon: Weapon;
@propertyInjectNammed(TYPES.Weapon, "throwwable")
@named("throwwable")
public secondaryWeapon: Weapon;
}
let propertyInjectTagged = makePropertyInjectTaggedDecorator(kernel);
class Warrior3 {
@propertyInjectTagged(TYPES.Weapon, "throwwable", false)
@tagged("throwwable", false)
public primaryWeapon: Weapon;
@propertyInjectTagged(TYPES.Weapon, "throwwable", true)
@tagged("throwwable", true)
public secondaryWeapon: Weapon;
}
kernel.snapshot();
kernel.restore();
@injectable()
class Test { }
kernel.bind<Test>(Test).toSelf();
kernel.bind<Test>(Test).toSelf().inSingletonScope();
}
module unmanaged_injection {
let kernel = new Kernel();
const BaseId = "Base";
@injectable()
class Base {
public prop: string;
public constructor(@unmanaged() arg: string) { // injected by user
this.prop = arg;
}
}
@injectable()
class Derived extends Base {
public constructor() {
super("unmanaged-injected-value"); // user injection
}
}
kernel.bind<Base>(BaseId).to(Derived);
console.log(kernel.get(BaseId) instanceof Base); // true
}

View File

@@ -6,11 +6,7 @@ import {
injectable, tagged, named, targetName,
inject, multiInject, traverseAncerstors,
taggedConstraint, namedConstraint, typeConstraint,
makePropertyMultiInjectDecorator,
makePropertyInjectTaggedDecorator,
makePropertyInjectNamedDecorator,
makePropertyInjectDecorator,
KernelModule, interfaces
KernelModule, interfaces, unmanaged
} from "inversify";
import * as Proxy from "harmony-proxy";
@@ -109,7 +105,7 @@ module external_module_test {
// binding types
kernel.bind<Weapon>("Weapon").to(Katana);
kernel.bind<Weapon>("Weapon").toConstantValue(new Katana());
kernel.bind<Weapon>("Weapon").toDynamicValue(() => { return new Katana(); });
kernel.bind<Weapon>("Weapon").toDynamicValue((context: interfaces.Context) => { return new Katana(); });
kernel.bind<interfaces.Newable<Weapon>>("Weapon").toConstructor<Weapon>(Katana);
@@ -159,8 +155,9 @@ module external_module_test {
}
kernel.bind<Samurai>("Samurai").to(Samurai);
kernel.bind<Weapon>("IWeapon").to(Katana).whenTargetTagged("canThrow", false);
kernel.bind<Weapon>("Weapon").to(Katana).whenTargetTagged("canThrow", false);
kernel.bind<ThrowableWeapon>("ThrowableWeapon").to(Shuriken).whenTargetTagged("canThrow", true);
kernel.getAllTagged<Weapon>("Weapon", "canThrow", false);
let throwable = tagged("canThrow", true);
let notThrowable = tagged("canThrow", false);
@@ -198,6 +195,7 @@ module external_module_test {
kernel.bind<Warrior>("Warrior").to(Samurai3);
kernel.bind<Weapon>("Weapon").to(Katana).whenTargetNamed("strong");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenTargetNamed("weak");
kernel.getAllNamed<Weapon>("Weapon", "weak");
@injectable()
class Samurai4 implements Samurai {
@@ -243,18 +241,18 @@ module external_module_test {
// Constraint helpers
kernel.bind<Weapon>("Weapon").to(Shuriken).whenInjectedInto(Ninja);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenInjectedInto("INinja");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenInjectedInto("Ninja");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenParentNamed("chinese");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenParentTagged("canThrow", true);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenTargetNamed("strong");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenTargetTagged("canThrow", true);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorIs(Ninja);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorIs("INinja");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorIs("Ninja");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorNamed("strong");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorTagged("canThrow", true);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenAnyAncestorMatches(whenParentNamedCanThrowConstraint);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorIs(Ninja);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorIs("INinja");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorIs("Ninja");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorNamed("strong");
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorTagged("canThrow", true);
kernel.bind<Weapon>("Weapon").to(Shuriken).whenNoAncestorMatches(whenParentNamedCanThrowConstraint);
@@ -339,103 +337,42 @@ module external_module_test {
}
module property_injection {
module snapshot {
let kernel = new Kernel();
let TYPES = { Weapon: "Weapon" };
interface Weapon {
durability: number;
use(): void;
}
@injectable()
class Sword implements Weapon {
public durability: number;
public constructor() {
this.durability = 100;
}
public use() {
this.durability = this.durability - 10;
}
}
@injectable()
class WarHammer implements Weapon {
public durability: number;
public constructor() {
this.durability = 100;
}
public use() {
this.durability = this.durability - 10;
}
}
let propertyMultiInject = makePropertyMultiInjectDecorator(kernel);
class Warrior1 {
@propertyMultiInject(TYPES.Weapon)
public weapons: Weapon[];
}
let propertyInject = makePropertyInjectDecorator(kernel);
interface Service {
count: number;
increment(): void;
}
@injectable()
class SomeService implements Service {
public count: number;
public constructor() {
this.count = 0;
}
public increment() {
this.count = this.count + 1;
}
}
class SomeWebComponent {
@propertyInject("Service")
private _service: Service;
public doSomething() {
let count = this._service.count;
this._service.increment();
return count;
}
}
let propertyInjectNammed = makePropertyInjectNamedDecorator(kernel);
class Warrior2 {
@propertyInjectNammed(TYPES.Weapon, "not-throwwable")
@named("not-throwwable")
public primaryWeapon: Weapon;
@propertyInjectNammed(TYPES.Weapon, "throwwable")
@named("throwwable")
public secondaryWeapon: Weapon;
}
let propertyInjectTagged = makePropertyInjectTaggedDecorator(kernel);
class Warrior3 {
@propertyInjectTagged(TYPES.Weapon, "throwwable", false)
@tagged("throwwable", false)
public primaryWeapon: Weapon;
@propertyInjectTagged(TYPES.Weapon, "throwwable", true)
@tagged("throwwable", true)
public secondaryWeapon: Weapon;
}
kernel.snapshot();
kernel.restore();
@injectable()
class Test { }
kernel.bind<Test>(Test).toSelf();
kernel.bind<Test>(Test).toSelf().inSingletonScope();
}
module unmanaged_injection {
let kernel = new Kernel();
const BaseId = "Base";
@injectable()
class Base {
public prop: string;
public constructor(@unmanaged() arg: string) { // injected by user
this.prop = arg;
}
}
@injectable()
class Derived extends Base {
public constructor() {
super("unmanaged-injected-value"); // user injection
}
}
kernel.bind<Base>(BaseId).to(Derived);
console.log(kernel.get(BaseId) instanceof Base); // true
}

View File

@@ -1,4 +1,4 @@
// Type definitions for inversify 2.0.0-beta.9
// Type definitions for inversify 2.0.0-rc.12
// Project: https://github.com/inversify/InversifyJS
// Definitions by: inversify <https://github.com/inversify>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -45,7 +45,7 @@ declare namespace inversify {
constraint: (request: Request) => boolean;
onActivation: (context: Context, injectable: T) => T;
cache: T;
dynamicValue: () => T;
dynamicValue: (context: Context) => T;
scope: number; // BindingScope
type: number; // BindingType
}
@@ -135,6 +135,7 @@ declare namespace inversify {
export interface Target {
guid: string;
serviceIdentifier: ServiceIdentifier<any>;
type: number; // TargetType
name: QueryableString;
metadata: Array<Metadata>;
hasTag(key: string): boolean;
@@ -152,6 +153,7 @@ declare namespace inversify {
export interface Kernel {
guid: string;
parent: Kernel;
bind<T>(serviceIdentifier: ServiceIdentifier<T>): BindingToSyntax<T>;
unbind(serviceIdentifier: ServiceIdentifier<any>): void;
unbindAll(): void;
@@ -160,6 +162,8 @@ declare namespace inversify {
getNamed<T>(serviceIdentifier: ServiceIdentifier<T>, named: string): T;
getTagged<T>(serviceIdentifier: ServiceIdentifier<T>, key: string, value: any): T;
getAll<T>(serviceIdentifier: ServiceIdentifier<T>): T[];
getAllNamed<T>(serviceIdentifier: ServiceIdentifier<T>, named: string): T[];
getAllTagged<T>(serviceIdentifier: ServiceIdentifier<T>, key: string, value: any): T[];
load(...modules: KernelModule[]): void;
unload(...modules: KernelModule[]): void;
applyMiddleware(...middleware: Middleware[]): void;
@@ -197,10 +201,12 @@ declare namespace inversify {
export interface KeyValuePair<T> {
serviceIdentifier: ServiceIdentifier<any>;
value: Array<T>;
guid: string;
}
export interface BindingInSyntax<T> {
inSingletonScope(): BindingWhenOnSyntax<T>;
inTransientScope(): BindingWhenOnSyntax<T>;
}
export interface BindingInWhenOnSyntax<T> extends BindingInSyntax<T>, BindingWhenOnSyntax<T> {}
@@ -211,8 +217,9 @@ declare namespace inversify {
export interface BindingToSyntax<T> {
to(constructor: { new(...args: any[]): T; }): BindingInWhenOnSyntax<T>;
toSelf(): BindingInWhenOnSyntax<T>;
toConstantValue(value: T): BindingWhenOnSyntax<T>;
toDynamicValue(func: () => T): BindingWhenOnSyntax<T>;
toDynamicValue(func: (context: Context) => T): BindingWhenOnSyntax<T>;
toConstructor<T2>(constructor: Newable<T2>): BindingWhenOnSyntax<T>;
toFactory<T2>(factory: FactoryCreator<T2>): BindingWhenOnSyntax<T>;
toFunction(func: T): BindingWhenOnSyntax<T>;
@@ -248,30 +255,19 @@ declare namespace inversify {
export function tagged(metadataKey: string, metadataValue: any): (target: any, targetKey: string, index?: number) => any;
export function named(name: string): (target: any, targetKey: string, index?: number) => any;
export function targetName(name: string): (target: any, targetKey: string, index: number) => any;
export function unmanaged(): (target: any, targetKey: string, index: number) => any;
export function inject(serviceIdentifier: interfaces.ServiceIdentifier<any>): (target: any, targetKey: string, index?: number) => any;
export function guid(): string;
export function multiInject(
serviceIdentifier: interfaces.ServiceIdentifier<any>
): (target: any, targetKey: string, index?: number) => any;
export function makePropertyInjectDecorator(kernel: interfaces.Kernel):
(serviceIdentifier: (string|Symbol|interfaces.Newable<any>)) => (proto: any, key: string) => void;
export function makePropertyInjectNamedDecorator(kernel: interfaces.Kernel):
(serviceIdentifier: (string|Symbol|interfaces.Newable<any>), named: string) => (proto: any, key: string) => void;
export function makePropertyInjectTaggedDecorator(kernel: interfaces.Kernel):
(serviceIdentifier: (string|Symbol|interfaces.Newable<any>), key: string, value: any) => (proto: any, propertyName: string) => void;
export function makePropertyMultiInjectDecorator(kernel: interfaces.Kernel):
(serviceIdentifier: (string|Symbol|interfaces.Newable<any>)) => (proto: any, key: string) => void;
// constraint helpers
export var traverseAncerstors: (request: interfaces.Request, constraint: (request: interfaces.Request) => boolean) => boolean;
export var taggedConstraint: (tag: string) => (value: any) => (request: interfaces.Request) => boolean;
export var namedConstraint: (value: any) => (request: interfaces.Request) => boolean;
export var typeConstraint: (type: (Function|string)) => (request: interfaces.Request) => boolean;
}
declare module "inversify" {

View File

@@ -0,0 +1,50 @@
/// <reference path="jsoneditor.d.ts" />
import JSONEditor, {JSONEditorMode, JSONEditorNode, JSONEditorOptions} from 'jsoneditor';
let options: JSONEditorOptions;
options = {
ace: ace,
//ajv: Ajv({allErrors: true, verbose: true})
onChange() {},
onEditable(node: JSONEditorNode) {
return true;
},
onError(error: Error) {},
onModeChange(newMode: JSONEditorMode, oldMode: JSONEditorMode) {},
escapeUnicode: false,
sortObjectKeys: true,
history: true,
mode: 'tree',
modes: ['tree', 'view', 'form', 'code', 'text'],
name: 'foo',
schema: {},
search: false,
indentation: 2,
theme: 'default'
};
options = {
onEditable(node: JSONEditorNode) {
return {field: true, value: false};
}
};
let jsonEditor: JSONEditor;
jsonEditor = new JSONEditor(document.body);
jsonEditor = new JSONEditor(document.body, {});
jsonEditor = new JSONEditor(document.body, options, {foo: 'bar'});
jsonEditor.collapseAll();
jsonEditor.destroy();
jsonEditor.expandAll();
jsonEditor.focus();
jsonEditor.set({foo: 'bar'});
jsonEditor.setMode('text');
jsonEditor.setName('foo');
jsonEditor.setName();
jsonEditor.setSchema({});
jsonEditor.setText('{foo: 1}');
const json: any = jsonEditor.get();
const name: string = jsonEditor.getName();
const jsonString: string = jsonEditor.getText();

52
jsoneditor/jsoneditor.d.ts vendored Normal file
View File

@@ -0,0 +1,52 @@
// Type definitions for jsoneditor v5.5.7
// Project: https://github.com/josdejong/jsoneditor
// Definitions by: Alejandro Sánchez <https://github.com/alejo90>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../ace/ace.d.ts" />
declare module 'jsoneditor' {
export interface JSONEditorNode {
field: string;
value: string;
path: Array<string>;
}
export type JSONEditorMode = 'tree' | 'view' | 'form' | 'code' | 'text';
export interface JSONEditorOptions {
ace?: AceAjax.Ace;
ajv?: any; // Any for now, since ajv typings aren't A-Ok
onChange?: () => void;
onEditable?: (node: JSONEditorNode) => boolean | {field: boolean, value: boolean};
onError?: (error: Error) => void;
onModeChange?: (newMode: JSONEditorMode, oldMode: JSONEditorMode) => void;
escapeUnicode?: boolean;
sortObjectKeys?: boolean;
history?: boolean;
mode?: JSONEditorMode;
modes?: Array<JSONEditorMode>;
name?: string;
schema?: Object;
search?: boolean;
indentation?: number;
theme?: string;
}
export default class JSONEditor {
constructor(container: HTMLElement, options?: JSONEditorOptions, json?: Object);
collapseAll(): void;
destroy(): void;
expandAll(): void;
focus(): void;
set(json: Object): void;
setMode(mode: JSONEditorMode): void;
setName(name?: string): void;
setSchema(schema: Object): void;
setText(jsonString: string): void;
get(): any;
getMode(): JSONEditorMode;
getName(): string;
getText(): string;
}
}

View File

@@ -0,0 +1,6 @@
/// <reference path='jwt-client.d.ts' />
import * as JWT from "jwt-client";
var token = 'eyJpc3MiOiJ0b3B0YWwuY29tIiwiZXhwIjoxNDI2NDIwODAwLCJodHRwOi8vdG9wdGFsLmNvbS9qd3RfY2xhaW1zL2lzX2FkbWluIjp0cnVlLCJjb21wYW55IjoiVG9wdGFsIiwiYXdlc29tZSI6dHJ1ZX0';
var session = JWT.read(token);
console.log('session is', session);

42
jwt-client/jwt-client.d.ts vendored Normal file
View File

@@ -0,0 +1,42 @@
// Type definitions for jwt-client v0.2.1
// Project: https://github.com/pauldijou/jwt-client
// Definitions by: Timoteo Ponce <https://github.com/timoteoponce>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "jwt-client"{
interface JWTHeader{
typ: string;
alg: string;
}
interface JWTObject{
header: JWTHeader;
claim: any;
signature: string;
}
/**
* Read a string value (normally an HTTP header)
* from JSON Web Token to an Object
*/
function read(header:string):JWTObject;
/**
* Given a JWT object, stringify it back to
* its JWT representation.
*/
function write(value:JWTObject):string;
function keep(value:JWTObject, key?:any, storate?: any):void;
function remember():void;
function forget():void;
function get():string;
function validate(value:JWTObject, issuer?:any, audience?: any):boolean;
}

View File

@@ -3,25 +3,25 @@
// Definitions by: Ezekiel Victor <https://github.com/evictor/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module fixture {
var el: HTMLElement;
var json: any[];
declare namespace fixture {
export var el: HTMLElement;
export var json: any[];
function load(...files: string[]): any;
function load(file1: string, append?: boolean): any;
function load(file1: string, file2: string, append?: boolean): any;
function load(file1: string, file2: string, file3: string, append?: boolean): any;
function load(file1: string, file2: string, file3: string, file4: string, append?: boolean): any;
function load(file1: string, file2: string, file3: string, file4: string, file5: string, append?: boolean): any;
export function load(...files: string[]): any;
export function load(file1: string, append?: boolean): any;
export function load(file1: string, file2: string, append?: boolean): any;
export function load(file1: string, file2: string, file3: string, append?: boolean): any;
export function load(file1: string, file2: string, file3: string, file4: string, append?: boolean): any;
export function load(file1: string, file2: string, file3: string, file4: string, file5: string, append?: boolean): any;
function set(...htmlStrs: string[]): HTMLElement|HTMLElement[];
function set(htmlStr1: string, append?: boolean): HTMLElement|HTMLElement[];
function set(htmlStr1: string, htmlStr2: string, append?: boolean): HTMLElement|HTMLElement[];
function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, append?: boolean): HTMLElement|HTMLElement[];
function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, htmlStr4: string, append?: boolean): HTMLElement|HTMLElement[];
function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, htmlStr4: string, htmlStr5: string, append?: boolean): HTMLElement|HTMLElement[];
export function set(...htmlStrs: string[]): HTMLElement|HTMLElement[];
export function set(htmlStr1: string, append?: boolean): HTMLElement|HTMLElement[];
export function set(htmlStr1: string, htmlStr2: string, append?: boolean): HTMLElement|HTMLElement[];
export function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, append?: boolean): HTMLElement|HTMLElement[];
export function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, htmlStr4: string, append?: boolean): HTMLElement|HTMLElement[];
export function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, htmlStr4: string, htmlStr5: string, append?: boolean): HTMLElement|HTMLElement[];
function cleanup(): void;
export function cleanup(): void;
function setBase(fixtureBasePath: string): void;
export function setBase(fixtureBasePath: string): void;
}

View File

@@ -96,6 +96,6 @@ interface LocalForage {
}
declare module "localforage" {
export var localforage: LocalForage;
export default localforage;
var localforage: LocalForage;
export = localforage;
}

View File

@@ -4679,32 +4679,38 @@ result = <{a: number}[][]>_({0: {a: 1}, 1: {a: 2}}).partition<{a: number}>('a',
// result = _(dictionary).chain().map<TResult>(['d', 0, 'b']);
// }
// }
namespace TestReduce {
interface ABC {
[index: string]: number;
a: number;
b: number;
c: number;
}
interface ABC {
[index: string]: number;
a: number;
b: number;
c: number;
result = <number>_.reduce<number, number>([1, 2, 3], function (sum: number, num: number) {
return sum + num;
});
// chained
result = _.chain([1, 2 ,3]).reduce(function (sum: number, num: number) {
return sum + num;
}).value();
result = <ABC>_.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function (r: ABC, num: number, key: string) {
r[key] = num * 3;
return r;
}, {});
result = <number>_([1, 2, 3]).reduce<number>(function (sum: number, num: number) {
return sum + num;
});
result = <ABC>_({ 'a': 1, 'b': 2, 'c': 3 }).reduce<number, ABC>(function (r: ABC, num: number, key: string) {
r[key] = num * 3;
return r;
}, <ABC> {});
result = <number[]>_.reduceRight([[0, 1], [2, 3], [4, 5]], function (a: number[], b: number[]) { return a.concat(b); }, <number[]>[]);
}
result = <number>_.reduce<number, number>([1, 2, 3], function (sum: number, num: number) {
return sum + num;
});
result = <ABC>_.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function (r: ABC, num: number, key: string) {
r[key] = num * 3;
return r;
}, {});
result = <number>_([1, 2, 3]).reduce<number>(function (sum: number, num: number) {
return sum + num;
});
result = <ABC>_({ 'a': 1, 'b': 2, 'c': 3 }).reduce<number, ABC>(function (r: ABC, num: number, key: string) {
r[key] = num * 3;
return r;
}, <ABC> {});
result = <number[]>_.reduceRight([[0, 1], [2, 3], [4, 5]], function (a: number[], b: number[]) { return a.concat(b); }, <number[]>[]);
// _.reject
namespace TestReject {
let array: TResult[];

15
lodash/lodash.d.ts vendored
View File

@@ -8584,6 +8584,21 @@ declare module _ {
callback: MemoIterator<TValue, TResult>): LoDashExplicitObjectWrapper<TResult>;
}
interface LoDashExplicitArrayWrapper<T> {
/**LoDashExplicitWrapper
* @see _.reduce
*/
reduce<TResult>(
callback: MemoIterator<T, TResult>,
accumulator: TResult): LoDashExplicitWrapper<TResult>;
/**
* @see _.reduce
*/
reduce<TResult>(
callback: MemoIterator<T, TResult>): LoDashExplicitWrapper<TResult>;
}
//_.reduceRight
interface LoDashStatic {
/**

View File

@@ -11,14 +11,15 @@ import {
model,
PaginateModel,
PaginateOptions,
PaginateResult
PaginateResult,
Document
} from 'mongoose';
import * as mongoosePaginate from 'mongoose-paginate';
import { Router, Request, Response } from 'express';
//#region Test Models
interface User {
interface User extends Document {
email: string;
username: string;
password: string;
@@ -32,8 +33,7 @@ const UserSchema: Schema = new Schema({
UserSchema.plugin(mongoosePaginate);
type UserModel<T> = _UserModel<T> & PaginateModel<T>;
interface _UserModel<T> {}
interface UserModel<T extends Document> extends PaginateModel<T> {};
let UserModel: UserModel<User> = model<User>('User', UserSchema) as UserModel<User>;
//#endregion

View File

@@ -26,16 +26,21 @@ declare module 'mongoose' {
offset?: number;
}
export type PaginateModel<T> = _PaginateModel<T> & Model<T>;
interface _PaginateModel<T> {
interface PaginateModel<T extends Document> extends Model<T> {
paginate(query?: Object, options?: PaginateOptions, callback?: (err: any, result: PaginateResult<T>) => void): Promise<PaginateResult<T>>;
}
export function model<T extends Document, Statics>(
export function model<T extends Document>(
name: string,
schema?: Schema,
collection?: string,
skipInit?: boolean): Statics & PaginateModel<T>;
skipInit?: boolean): PaginateModel<T>;
export function model<T extends Document, U extends PaginateModel<T>>(
name: string,
schema?: Schema,
collection?: string,
skipInit?: boolean): U;
}
declare module 'mongoose-paginate' {

View File

@@ -1,8 +1,10 @@
/// <reference path="mongoose-promise.d.ts" />
import * as mongoose from 'mongoose';
var cb = function () {};
var mongopromise: MongoosePromise<number>;
var mongopromise: mongoose.Promise<number>;
mongopromise.addBack(function (err, arg) {
err.stack;
arg.toFixed();
@@ -40,7 +42,19 @@ mongopromise.then(function (arg) {
});
mongopromise.complete();
/* static properties */
MongoosePromise.ES6(function (complete, error) {
mongoose.Promise.ES6(function (complete: any, error: any) {
complete.apply(this);
error.apply(this);
});
});
/* Practical Examples */
interface IUser extends mongoose.Document {
name: string;
age: number;
}
var UserSchema = new mongoose.Schema({
name: String,
age: Number
});
var UserModel: mongoose.Model<IUser> = mongoose.model<IUser>('Model', UserSchema);
UserModel.findOne({}).exec().fulfill();
UserModel.find({}).exec().then(() => {}).catch(() => {}).reject('');

View File

@@ -3,126 +3,125 @@
// Definitions by: simonxca <https://github.com/simonxca/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/*
* These are the default promises included in the Mongoose v4.x
* definitions. They will be deprecated beginning Mongoose V5.x
* in favor of native ES6 Promises.
*
* You can switch the promise library that mongoose uses by:
*
* 1. Including this somewhere in your code:
* mongoose.Promise = YOUR_PROMISE;
*
* 2. Including this somewhere in your main .d.ts file:
* type MongoosePromise<T> = YOUR_PROMISE<T>;
*/
/// <reference path="../mongoose/mongoose.d.ts" />
/// <reference path="../mpromise/mpromise.d.ts" />
/*
* http://mongoosejs.com/docs/api.html#promise-js
*
* Callback signatures are from the mPromise type definitions.
* mongoose.d.ts uses global.Promise by default. This is the MongooseJS
* mpromise implementation (which are deprecated). If you still want to
* use it, install these definitions in your project.
*/
interface MongoosePromise<T> {
/**
* Promise constructor.
* Promises are returned from executed queries.
* @param fn a function which will be called when the promise
* is resolved that accepts fn(err, ...){} as signature
* @event err Emits when the promise is rejected
* @event complete Emits when the promise is fulfilled
* @deprecated Mongoose 5.0 will use native promises by default (or bluebird, if native
* promises are not present) but still support plugging in your own ES6-compatible
* promises library. Mongoose 5.0 will not support mpromise.
declare module 'mongoose' {
import mpromise = require('mpromise');
type Promise<T> = MongoosePromise<T>;
/*
* mpromise definitions.
* Callback signatures are from the mPromise type definitions.
*/
new(fn?: (err: any, arg: T) => void): MongoosePromise<T>;
new(fn?: (err: any, ...args: T[]) => void): MongoosePromise<T>;
class MongoosePromise<T> extends mpromise<T, any> {
/**
* Promise constructor.
* Promises are returned from executed queries.
* @param fn a function which will be called when the promise
* is resolved that accepts fn(err, ...){} as signature
* @event err Emits when the promise is rejected
* @event complete Emits when the promise is fulfilled
* @deprecated Mongoose 5.0 will use native promises by default (or bluebird, if native
* promises are not present) but still support plugging in your own ES6-compatible
* promises library. Mongoose 5.0 will not support mpromise.
*/
constructor(fn?: (err: any, arg: T) => void);
constructor(fn?: (err: any, ...args: T[]) => void);
/**
* Adds a single function as a listener to both err and complete.
* It will be executed with traditional node.js argument position when the promise is resolved.
* @deprecated Use onResolve instead.
*/
addBack(listener: (err: any, arg: T) => void): this;
addBack(listener: (err: any, ...args: T[]) => void): this;
/**
* Adds a listener to the complete (success) event.
* @deprecated Adds a listener to the complete (success) event.
*/
addCallback(listener: (arg: T) => void): this;
addCallback(listener: (...args: T[]) => void): this;
/**
* Adds a listener to the err (rejected) event.
* @deprecated Use onReject instead.
*/
addErrback(listener: (err: any) => void): this;
/** ES6-style .catch() shorthand */
catch<TRes>(onReject?: (err: any) => void | TRes | PromiseLike<TRes>): MongoosePromise<TRes>;
/**
* Signifies that this promise was the last in a chain of then()s: if a handler passed
* to the call to then which produced this promise throws, the exception will go uncaught.
*/
end(): void;
/**
* Rejects this promise with err.
* If the promise has already been fulfilled or rejected, not action is taken.
* Differs from #reject by first casting err to an Error if it is not instanceof Error.
*/
error(err: any): this;
/**
* Adds listener to the event.
* If event is either the success or failure event and the event has already been emitted,
* thelistener is called immediately and passed the results of the original emitted event.
*/
on(event: string, listener: Function): this;
/**
* Rejects this promise with reason.
* If the promise has already been fulfilled or rejected, not action is taken.
*/
reject(reason: Object | string | Error): this;
/**
* Resolves this promise to a rejected state if err is passed or a fulfilled state if no err is passed.
* If the promise has already been fulfilled or rejected, not action is taken.
* err will be cast to an Error if not already instanceof Error.
* NOTE: overrides mpromise#resolve to provide error casting.
* @param err error or null
* @param val value to fulfill the promise with
*/
resolve(err?: any, val?: Object): this;
/**
* Creates a new promise and returns it. If onFulfill or onReject are passed, they are added as
* SUCCESS/ERROR callbacks to this promise after the nextTick.
* Conforms to promises/A+ specification.
*/
then<TRes>(onFulFill: (arg: T) => void | TRes | PromiseLike<TRes>,
onReject?: (err: any) => void | TRes | PromiseLike<TRes>): MongoosePromise<TRes>;
then<TRes>(onFulfill: (...args: T[]) => void | TRes | PromiseLike<TRes>,
onReject?: (err: any) => void | TRes | PromiseLike<TRes>): MongoosePromise<TRes>;
/**
* Fulfills this promise with passed arguments. Alias of mpromise#fulfill.
* @deprecated Use fulfill instead.
*/
complete(args: T): this;
complete(...args: T[]): this;
/** Fulfills this promise with passed arguments. */
fulfill(...args: T[]): this;
fulfill(arg: T): this;
/** ES6-style promise constructor wrapper around mpromise. */
static ES6<TRes>(resolver: (
complete: (...args: TRes[]) => void | TRes | PromiseLike<TRes>,
error: (e: any) => void | TRes | PromiseLike<TRes>
) => void): MongoosePromise<TRes>;
}
}
declare class MongoosePromise<T> {
/**
* Adds a single function as a listener to both err and complete.
* It will be executed with traditional node.js argument position when the promise is resolved.
* @deprecated Use onResolve instead.
*/
addBack(listener: (err: any, arg: T) => void): this;
addBack(listener: (err: any, ...args: T[]) => void): this;
/**
* Adds a listener to the complete (success) event.
* @deprecated Adds a listener to the complete (success) event.
*/
addCallback(listener: (arg: T) => void): this;
addCallback(listener: (...args: T[]) => void): this;
/**
* Adds a listener to the err (rejected) event.
* @deprecated Use onReject instead.
*/
addErrback(listener: (err: any) => void): this;
/** ES6-style .catch() shorthand */
catch<TRes>(onReject?: (err: any) => void | TRes | PromiseLike<TRes>): MongoosePromise<TRes>;
/**
* Signifies that this promise was the last in a chain of then()s: if a handler passed
* to the call to then which produced this promise throws, the exception will go uncaught.
*/
end(): void;
/**
* Rejects this promise with err.
* If the promise has already been fulfilled or rejected, not action is taken.
* Differs from #reject by first casting err to an Error if it is not instanceof Error.
*/
error(err: any): this;
/**
* Adds listener to the event.
* If event is either the success or failure event and the event has already been emitted,
* thelistener is called immediately and passed the results of the original emitted event.
*/
on(event: string, listener: Function): this;
/**
* Rejects this promise with reason.
* If the promise has already been fulfilled or rejected, not action is taken.
*/
reject(reason: Object | string | Error): this;
/**
* Resolves this promise to a rejected state if err is passed or a fulfilled state if no err is passed.
* If the promise has already been fulfilled or rejected, not action is taken.
* err will be cast to an Error if not already instanceof Error.
* NOTE: overrides mpromise#resolve to provide error casting.
* @param err error or null
* @param val value to fulfill the promise with
*/
resolve(err?: any, val?: Object): this;
/**
* Creates a new promise and returns it. If onFulfill or onReject are passed, they are added as
* SUCCESS/ERROR callbacks to this promise after the nextTick.
* Conforms to promises/A+ specification.
*/
then<TRes>(onFulFill: (arg: T) => void | TRes | PromiseLike<TRes>,
onReject?: (err: any) => void | TRes | PromiseLike<TRes>): MongoosePromise<TRes>;
then<TRes>(onFulfill: (...args: T[]) => void | TRes | PromiseLike<TRes>,
onReject?: (err: any) => void | TRes | PromiseLike<TRes>): MongoosePromise<TRes>;
/**
* Fulfills this promise with passed arguments. Alias of mpromise#fulfill.
* @deprecated Use fulfill instead.
*/
complete(args: T): this;
complete(...args: T[]): this;
/** Fulfills this promise with passed arguments. */
fulfill(...args: T[]): this;
fulfill(arg: T): this;
/** ES6-style promise constructor wrapper around mpromise. */
static ES6<TRes>(resolver: (
complete: (...args: TRes[]) => void | TRes | PromiseLike<TRes>,
error: (e: any) => void | TRes | PromiseLike<TRes>
) => void): MongoosePromise<TRes>;
}

208
mongoose/README.md Normal file
View File

@@ -0,0 +1,208 @@
## MongooseJS Typescript Docs
Below are some examples of how to use these Definitions.<br>
Scenarios where the Typescript code is identical to plain Javascript code are omitted.
### Table of Contents
* [Mongoose Methods, Properties, Constructors](#mongoose-methods-properties-constructors)
* [Creating and Saving Documents](#creating-and-saving-documents)
* [Instance Methods, Virtual Properties](#instance-methods-and-virtual-properties)
* [Static Methods](#static-methods)
* [Plugins](#plugins)
* [Promises](#promises)
* [FAQ](#faq)
#### Mongoose Methods, Properties, Constructors
You can call methods from the mongoose instance using:
```
import * as mongoose from 'mongoose';
var MyModel = mongoose.model(...);
var MySchema: mongoose.Schema = new mongoose.Schema(...);
```
Alternatively, you can import individual names and call them:
```
import {model, Schema} from 'mongoose';
var MyModel = model(...);
var MySchema: Schema = new Schema(...):
```
[top](#mongoosejs-typescript-docs)
#### Creating and Saving Documents
```
import {Document, model, Model, Schema} from 'mongoose';
var UserSchema: Schema = new Schema({
username: {
type: String,
required: true,
unique: true
},
age: Number,
friends: [String],
data: [Schema.Types.Mixed]
});
interface IUser extends Document {
username: string;
age: number;
friends: string[];
data: any[];
}
var UserModel: Model<IUser> = mongoose.model<IUser>('User', UserSchema);
var user = new UserModel({name: 'Jane'});
user.username; // IUser properties are available
user.save(); // mongoose Document methods are available
UserModel.findOne({}, (err: any, user: IUser) => {
user.username; // IUser properties are available
user.save(); // mongoose Document methods are available
});
```
[top](#mongoosejs-typescript-docs)
#### Instance Methods and Virtual Properties
```
import {Document, model, Model, Schema} from 'mongoose';
var UserSchema: Schema = new Schema({
name: String
});
UserSchema.methods.method1 = function () { return '' };
UserSchema.virtual('nameInCaps').get(function () {
return this.name.toUpperCase();
});
UserSchema.virtual('nameInCaps').set(function (caps) {
this.name = caps.toLowerCase();
});
interface IUser extends Document {
name: string;
nameInCaps: string;
method1: () => string;
}
var UserModel: Model<IUser> = model<IUser>('User', UserSchema);
var user = new UserModel({name: 'Billy'});
user.method1(); // IUser methods are available
user.nameInCaps; // virtual properties can be used
UserModel.findOne({}, (err: any, user: IUser) => {
user.method1(); // IUser methods are available
user.nameInCaps; // virtual properties can be used
});
```
[top](#mongoosejs-typescript-docs)
#### Static Methods
```
import {Document, model, Model, Schema} from 'mongoose';
var UserSchema = new Schema({});
UserSchema.statics.static1 = function () { return '' };
interface IUserDocument extends Document {...}
interface IUserModel extends Model<IUserDocument> {
static1: () => string;
}
var UserModel: IUserModel = model<IUser, IUserModel>('User', UserSchema);
UserModel.static1(); // static methods are available
```
[top](#mongoosejs-typescript-docs)
#### Plugins
To write definitions for plugins, extend the mongoose module and create a simple plugin module:
```
// plugin.d.ts
declare module 'mongoose' {
export interface PassportLocalDocument {...}
export interface PassportLocalSchema extends Schema {...}
export interface PassportLocalModel<T extends PassportLocalDocument> extends Model<T> {...}
...
}
declare module 'passport-local-mongoose' {
import mongoose = require('mongoose');
var _: (schema: mongoose.Schema, options?: Object) => void;
export = _;
}
// user.ts
import {
model,
PassportLocalDocument,
PassportLocalSchema,
PassportLocalModel
Schema
} from 'mongoose';
import * as passportLocalMongoose from 'passport-local-mongoose';
var UserSchema: PassportLocalSchema = new Schema({});
UserSchema.plugin(passportLocalMongoose, options);
interface IUser extends PassportLocalDocument {...}
interface IUserModel<T extends PassportLocalDocument> extends PassportLocalModel<T> {...}
var UserModel: IUserModel<IUser> = model<IUser>('User', UserSchema);
```
Full example for [Passport Local Mongoose](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/passport-local-mongoose/passport-local-mongoose.d.ts)<br>
[top](#mongoosejs-typescript-docs)
#### Promises
These definitions use global.Promise by default. If you would like to use mongoose's own mpromise
definition (which is deprecated), you can install definitions for [mongoose-promise](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/mongoose-promise).
If you'd like to use something other than global.Promise, you'll need to create a simple .d.ts file:
```
// promise-bluebird.d.ts
import * as Bluebird from 'bluebird';
declare module 'mongoose' {
type Promise<T> = Bluebird<T>;
}
// promise-q.d.ts
import * as Q from 'q';
declare module 'mongoose' {
type Promise<T> = Q.Promise<T>;
}
// another-promise.d.ts
...
```
To use it, you will need to `/// <reference path="promise-bluebird.d.ts" />` in one of your source code files,
or include the `.d.ts` file in your compile.
To assign the new promise library in your code, you will need to use one of the following options (since
Typescript does not allow assigning properties of imported modules):
* `(<any>mongoose).Promise = YOUR_PROMISE;`
* `require('mongoose').Promise = YOUR_PROMISE;`
* `import mongoose = require('mongoose'); ... mongoose.Promise = YOUR_PROMISE;`
[top](#mongoosejs-typescript-docs)
#### FAQ
Q: Why are there 2 interfaces for Documents called Document and MongooseDocument?<br>
A: People have been using this for a long time:
```
interface IUser extends mongoose.Document {
...
}
```
When it should really be this:
```
interface IUser extends mongoose.model {
...
}
```
For backwards compatibility Document is an interface for [mongoose.model](https://github.com/Automattic/mongoose/blob/master/lib/model.js#L3162)<br>
And MongooseDocument is an interface for [mongoose.Document](https://github.com/Automattic/mongoose/blob/master/lib/model.js#L3162)<br>
At some point in the future this may get fixed, which would require fixing your code.
<br>
[top](#mongoosejs-typescript-docs)

View File

@@ -27,7 +27,7 @@ mongoose.connect(connectUri, {
autoIndex: true
},
mongos: true
}).then(cb).fulfill();
}).then(cb);
mongoose.connect(connectUri, function (error) {
error.stack;
});
@@ -45,14 +45,14 @@ mongoose.createConnection('localhost', 'database', 3000, {
autoIndex: false
}
}).open('');
mongoose.disconnect(cb).then(cb).fulfill;
mongoose.disconnect(cb).then(cb);
mongoose.get('test');
mongoose.model('Actor', new mongoose.Schema({
name: String
}), 'collectionName', true).find({});
mongoose.model('Actor').find({});
mongoose.modelNames()[0].toLowerCase();
new (new mongoose.Mongoose()).Mongoose().connect('');
new (new mongoose.Mongoose(9, 8, 7)).Mongoose(1, 2, 3).connect('');
mongoose.plugin(cb, {}).connect('');
mongoose.set('test', 'value');
mongoose.set('debug', function(collectionName: any, methodName: any, arg1: any, arg2: any) {});
@@ -136,7 +136,6 @@ conn1.model('myModel', new mongoose.Schema({}), 'myCol').find();
interface IStatics {
staticMethod1: (a: number) => string;
}
conn1.model<{}, IStatics>('').staticMethod1;
conn1.modelNames()[0].toLowerCase();
conn1.config.hasOwnProperty('');
conn1.db.bufferMaxEntries;
@@ -350,7 +349,7 @@ new mongoose.Schema({
* section document.js
* http://mongoosejs.com/docs/api.html#document-js
*/
var doc: mongoose.Document;
var doc: mongoose.MongooseDocument;
doc.$isDefault('path').valueOf();
doc.depopulate('path');
doc.equals(doc).valueOf();
@@ -465,7 +464,7 @@ mongooseArray.length;
* http://mongoosejs.com/docs/api.html#types-documentarray-js
*/
// The constructor is private api, but we'll use it to test
var documentArray: mongoose.Types.DocumentArray<mongoose.Document> =
var documentArray: mongoose.Types.DocumentArray<mongoose.MongooseDocument> =
new mongoose.Types.DocumentArray();
documentArray.create({}).errors;
documentArray.id(new Buffer('hi'));
@@ -500,7 +499,7 @@ var objectId: mongoose.Types.ObjectId = mongoose.Types.ObjectId.createFromHexStr
objectId = new mongoose.Types.ObjectId(12345);
objectId.getTimestamp();
/* practical examples */
export interface IManagerSchema extends mongoose.Document {
export interface IManagerSchema extends mongoose.MongooseDocument {
user: mongoose.Schema.Types.ObjectId;
}
export var ManagerSchema = new mongoose.Schema({
@@ -530,7 +529,7 @@ embeddedDocument.execPopulate();
* section query.js
* http://mongoosejs.com/docs/api.html#query-js
*/
var query: mongoose.Query<mongoose.Document[]>;
var query: mongoose.Query<mongoose.MongooseDocument[]>;
query.$where('').$where(cb);
query.all(99).all('path', 99);
query.and([{ color: 'green' }, { status: 'ok' }]).and([]);
@@ -541,7 +540,7 @@ query.where('loc').within().box(lowerLeft, upperRight)
query.box({ ll : lowerLeft, ur : upperRight }).box({});
var queryModel = mongoose.model('QModel')
query.cast(new queryModel(), {}).hasOwnProperty('');
query.catch(function (err) {}).catch();
query.catch(cb).catch(cb);
query.center({}).center({});
query.centerSphere({ center: [50, 50], radius: 10 }).centerSphere('path', {});
query.circle({ center: [50, 50], radius: 10 }).circle('path');
@@ -696,7 +695,7 @@ query.stream().on('data', function (doc: any) {
});
query.tailable().tailable(false);
query.then(cb).catch(cb);
(new (query.toConstructor())()).toConstructor();
(new (query.toConstructor())(1, 2, 3)).toConstructor();
query.update({}, doc, {
}, cb);
@@ -761,8 +760,9 @@ schemaArray.sparse(true);
* section schema/string.js
* http://mongoosejs.com/docs/api.html#schema-string-js
*/
var MongoDocument: mongoose.Document;
var schemastring: mongoose.Schema.Types.String = new mongoose.Schema.Types.String('hello');
schemastring.checkRequired(234, new mongoose.Document()).valueOf();
schemastring.checkRequired(234, MongoDocument).valueOf();
schemastring.enum(['hi', 'a', 'b']).enum('hi').enum({});
schemastring.lowercase().lowercase();
schemastring.match(/re/, 'error').match(/re/);
@@ -790,7 +790,7 @@ documentarray.sparse(true);
* http://mongoosejs.com/docs/api.html#schema-number-js
*/
var schemanumber: mongoose.Schema.Types.Number = new mongoose.Schema.Types.Number('num', {});
schemanumber.checkRequired(999, new mongoose.Document()).valueOf();
schemanumber.checkRequired(999, MongoDocument).valueOf();
schemanumber.max(999, 'error').max(999);
schemanumber.min(999, 'error').min(999);
/* static properties */
@@ -803,7 +803,7 @@ schemanumber.sparse(true);
* http://mongoosejs.com/docs/api.html#schema-date-js
*/
var schemadate: mongoose.Schema.Types.Date = new mongoose.Schema.Types.Date('99');
schemadate.checkRequired([], new mongoose.Document()).valueOf();
schemadate.checkRequired([], MongoDocument).valueOf();
schemadate.expires(99).expires('now');
schemadate.max(new Date(), 'error').max(new Date(''));
schemadate.min(new Date(), 'error').min(new Date(''));
@@ -817,7 +817,7 @@ schemadate.sparse(true);
* http://mongoosejs.com/docs/api.html#schema-buffer-js
*/
var schemabuffer: mongoose.Schema.Types.Buffer = new mongoose.Schema.Types.Buffer('99');
schemabuffer.checkRequired(999, new mongoose.Document()).valueOf();
schemabuffer.checkRequired(999, MongoDocument).valueOf();
/* static properties */
mongoose.Schema.Types.Buffer.schemaName.toLowerCase();
/* inherited properties */
@@ -840,7 +840,7 @@ schemaboolean.sparse(true);
*/
var schemaobjectid: mongoose.Schema.Types.ObjectId = new mongoose.Schema.Types.ObjectId('99');
schemaobjectid.auto(true).auto(false);
schemaobjectid.checkRequired(99, new mongoose.Document()).valueOf();
schemaobjectid.checkRequired(99, MongoDocument).valueOf();
/* static properties */
mongoose.Schema.Types.ObjectId.schemaName.toLowerCase();
/* inherited properties */
@@ -1060,12 +1060,13 @@ mongoose.model('').aggregate()
});
/* pluggable promise */
mongoose.Promise = Promise;
(<any>mongoose).Promise = Promise;
require('mongoose').Promise = Promise;
mongoose.Promise.race;
mongoose.Promise.all;
mongoose.model('').findOne()
.exec().addErrback(cb);
.exec().then(cb);
/*
* section model.js
@@ -1078,8 +1079,9 @@ var MongoModel = mongoose.model('MongoModel', new mongoose.Schema({
required: true
}
}), 'myCollection', true);
MongoModel.$where('indexOf("val") !== -1').exec(function (err, docs) {
MongoModel.find({}).$where('indexOf("val") !== -1').exec(function (err, docs) {
docs[0].save();
docs[0].__v;
});
MongoModel.findById(999, function (err, doc) {
doc.increment();
@@ -1249,6 +1251,10 @@ mongoModel.discriminators;
mongoModel.modelName.toLowerCase();
MongoModel = mongoModel.base.model('new', mongoModel.schema);
/* inherited properties */
MongoModel.modelName;
mongoModel.modelName;
MongoModel.collection;
mongoModel.collection;
mongoModel._id;
mongoModel.execPopulate();
mongoModel.on('data', cb);
@@ -1310,7 +1316,7 @@ LocModel.find()
});
});
});
LocModel.$where('')
LocModel.find({}).$where('')
.exec(function (err, locations) {
locations[0].name;
locations[1].openingTimes;
@@ -1346,10 +1352,38 @@ LocModel.geoSearch({}, {
interface IStatics {
staticMethod2: (a: number) => string;
}
var StaticModel = mongoose.model<Location, IStatics>('Location');
StaticModel.staticMethod2(9).toUpperCase();
(new StaticModel()).save(function (err, doc) {
doc.openingTimes;
doc.model<Location, IStatics>('').staticMethod2;
interface MyDocument extends mongoose.Document {
prop: string;
method: () => void;
}
interface MyModel extends mongoose.Model<MyDocument> {
staticProp: string;
staticMethod: () => void;
}
interface ModelStruct {
doc: MyDocument;
model: MyModel;
method1: (callback: (model: MyModel, doc: MyDocument) => void) => MyModel;
}
var modelStruct1: ModelStruct;
var myModel1: MyModel;
var myDocument1: MyDocument;
modelStruct1.method1(function (myModel1, myDocument1) {
myModel1.staticProp;
myModel1.staticMethod();
myDocument1.prop;
myDocument1.method();
}).staticProp.toLowerCase();
var mySchema = new mongoose.Schema({});
export var Final: MyModel = <MyModel>mongoose.connection.model<MyDocument>('Final', mySchema);
Final.findOne(function (err: any, doc: MyDocument) {
doc.save();
doc.remove();
doc.model('');
});
StaticModel.model<Location, IStatics>('').staticMethod2;
export var Final2: MyModel = mongoose.model<MyDocument, MyModel>('Final2', mySchema);
Final2.staticMethod();
Final2.staticProp;
var final2 = new Final2();
final2.prop;
final2.method;

4622
mongoose/mongoose.d.ts vendored

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
// Type definitions for morris.js 0.5.1
// Project: http://morrisjs.github.io/morris.js/
// Definitions by: Matthieu Mourisson <https://github.com/mareek>
// Definitions by: Matthieu Mourisson <https://github.com/mareek>, Matanel Sindilevich <https://github.com/sindilevich>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace morris {
@@ -143,4 +143,8 @@ declare namespace morris {
}
}
declare var Morris: morris.MorrisStatic;
declare module "morris" {
export = Morris;
}
declare var Morris: morris.MorrisStatic;

2
multer/multer.d.ts vendored
View File

@@ -81,7 +81,7 @@ declare module "multer" {
interface DiskStorageOptions {
/** A function used to determine within which folder the uploaded files should be stored. Defaults to the system's default temporary directory. */
destination?: (req: Express.Request, file: Express.Multer.File, callback: (error: Error, destination: string) => void) => void;
destination?: string | ((req: Express.Request, file: Express.Multer.File, callback: (error: Error, destination: string) => void) => void);
/** A function used to determine what the file should be named inside the folder. Defaults to a random name with no file extension. */
filename?: (req: Express.Request, file: Express.Multer.File, callback: (error: Error, filename: string) => void) => void;
}

View File

@@ -0,0 +1,10 @@
/// <reference path="../node/node.d.ts" />
/// <reference path="./musicmetadata.d.ts" />
import * as fs from "fs";
import * as mm from "musicmetadata";
mm(fs.createReadStream("hype-train.mp3"), (err: Error, metadata: MM.Metadata) => {
if (err) throw err;
console.log(`Parsed song ${metadata.title}`);
});

48
musicmetadata/musicmetadata.d.ts vendored Normal file
View File

@@ -0,0 +1,48 @@
// Type definitions for musicmetadata 2.0.4
// Project: https://www.npmjs.com/package/musicmetadata
// Definitions by: Xavier Stouder <https://github.com/Xstoudi>
// Definitions: https://github.com/DefinitelyTyped/
/// <reference path="../node/node.d.ts" />
declare module "musicmetadata" {
import {Readable} from "stream";
import {EventEmitter} from "events";
function mm(readStream: Readable, callback: (err: Error, metadata: MM.Metadata) => void): EventEmitter;
function mm(readStream: Readable, options: MM.Options, callback: (err: Error, metadata: MM.Metadata) => void): EventEmitter;
namespace mm { }
export = mm;
}
declare namespace MM {
export interface Options {
duration: boolean;
fileSize: number;
}
export interface Metadata {
artist: string[];
album: string;
albumartist: string[];
title: string;
year: string;
track: NoOf;
disk: NoOf;
genre: string;
picture: Picture[];
duration: number;
}
export interface NoOf {
no: number;
of: number;
}
export interface Picture {
format: string;
data: Buffer;
}
}

View File

@@ -0,0 +1,48 @@
/// <reference path="./node-dogstatsd.d.ts" />
import * as datadog from 'node-dogstatsd';
function test_statsd_client() {
// can create client with defaults
let client = new datadog.StatsD('localhost');
let options: datadog.StatsDOptions = { global_tags: ['environment:definitely_typed']};
// can create client with all params
client = new datadog.StatsD('localhost', 8125, null, options);
let key: string = 'key';
let timeValue: number = 99;
let sampleRate: number = 0.85;
let incrementBy: number = 7;
let decrementBy: number = 5;
let gaugeValue: number = 199;
let tags: string[] = ['tag1', 'tag2'];
client.timing(key, timeValue);
client.timing(key, timeValue, sampleRate);
client.timing(key, timeValue, sampleRate, tags);
client.increment(key);
client.increment(key, sampleRate);
client.increment(key, sampleRate, tags);
client.incrementBy(key, incrementBy);
client.incrementBy(key, incrementBy, tags);
client.decrement(key);
client.decrement(key, sampleRate);
client.decrement(key, sampleRate, tags);
client.decrementBy(key, decrementBy);
client.decrementBy(key, decrementBy, tags);
client.gauge(key, gaugeValue);
client.gauge(key, gaugeValue, sampleRate);
client.gauge(key, gaugeValue, sampleRate, tags);
client.histogram(key, timeValue);
client.histogram(key, timeValue, sampleRate);
client.histogram(key, timeValue, sampleRate, tags);
client.close();
}

29
node-dogstatsd/node-dogstatsd.d.ts vendored Normal file
View File

@@ -0,0 +1,29 @@
// Type definitions for Datadog's nodejs metrics client node-dogstatsd
// Project: https://github.com/joybro/node-dogstatsd
// Definitions by: Chris Bobo <https://github.com/chrisbobo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "node-dogstatsd" {
export interface StatsDOptions {
global_tags?: string[];
}
export class StatsD {
constructor(host: string, port?: number, socket?: string, options?: StatsDOptions);
timing(stat: string, time: number, sample_rate?: number, tags?: string[]): void;
increment(stat: string, sample_rate?: number, tags?: string[]): void;
incrementBy(stat: string, value: number, tags?: string[]): void;
decrement(stat: string, sample_rate?: number, tags?: string[]): void;
decrementBy(stat: string, value: number, tags?: string[]): void;
gauge(stat: string, value: number, sample_rate?: number, tags?: string[]): void;
histogram(stat: string, time: number, sample_rate?: number, tags?: string[]): void;
close(): void;
}
}

1
node/node-4.d.ts vendored
View File

@@ -290,6 +290,7 @@ declare namespace NodeJS {
cwd(): string;
env: any;
exit(code?: number): void;
exitCode: number;
getgid(): number;
setgid(id: number): void;
setgid(id: string): void;

View File

@@ -259,6 +259,47 @@ function bufferTests() {
index = buffer.lastIndexOf(buffer);
}
{
let buffer = new Buffer('123');
let val: [number, number];
for (let entry of buffer.entries()) {
val = entry;
}
}
{
let buffer = new Buffer('123');
let includes: boolean;
includes = buffer.includes("23");
includes = buffer.includes("23", 1);
includes = buffer.includes("23", 1, "utf8");
includes = buffer.includes(23);
includes = buffer.includes(23, 1);
includes = buffer.includes(23, 1, "utf8");
includes = buffer.includes(buffer);
includes = buffer.includes(buffer, 1);
includes = buffer.includes(buffer, 1, "utf8");
}
{
let buffer = new Buffer('123');
let val: number;
for (let key of buffer.keys()) {
val = key;
}
}
{
let buffer = new Buffer('123');
let val: number;
for (let value of buffer.values()) {
val = value;
}
}
// Imported Buffer from buffer module works properly
{
let b = new ImportedBuffer('123');

14
node/node.d.ts vendored
View File

@@ -509,10 +509,10 @@ interface NodeBuffer extends Uint8Array {
fill(value: any, offset?: number, end?: number): this;
indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
// TODO: entries
// TODO: includes
// TODO: keys
// TODO: values
entries(): IterableIterator<[number, number]>;
includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean;
keys(): IterableIterator<number>;
values(): IterableIterator<number>;
}
/************************************************
@@ -753,7 +753,7 @@ declare module "cluster" {
id: string;
process: child.ChildProcess;
suicide: boolean;
send(message: any, sendHandle?: any): void;
send(message: any, sendHandle?: any): boolean;
kill(signal?: string): void;
destroy(signal?: string): void;
disconnect(): void;
@@ -1075,7 +1075,7 @@ declare module "child_process" {
stdio: [stream.Writable, stream.Readable, stream.Readable];
pid: number;
kill(signal?: string): void;
send(message: any, sendHandle?: any): void;
send(message: any, sendHandle?: any): boolean;
connected: boolean;
disconnect(): void;
unref(): void;
@@ -2632,4 +2632,4 @@ declare module "constants" {
declare module "process" {
export = process;
}
}

37
nvd3/nvd3.d.ts vendored
View File

@@ -126,6 +126,41 @@ declare namespace nv {
width(value: number): this;
}
interface Focus extends Nvd3Element {
color(value: string[]): this;
color(func: (d: any, i: number) => string): this;
width(): number;
width(value: number): this;
height(): number;
height(value: number): this;
margin(): Margin;
margin(value: Margin): this;
x(): (d: any) => any;
x(func: (d: any) => any): this;
y(): (d: any) => number;
y(func: (d: any) => number): this;
showXAxis(): boolean;
showXAxis(value: boolean): this;
showYAxis(): boolean;
showYAxis(value: boolean): this;
brushExtent(): [number, number] | [[number, number], [number, number]];
brushExtent(value: [number, number] | [[number, number], [number, number]]) : this;
duration(): number;
duration(value: number): this;
xTickFormat(): (d: any) => string;
xTickFormat(format: (t: any) => string): this;
xTickFormat(format: string): this;
xTickFormat(format: (d: any, i: any) => string): this;
yTickFormat(): (d: any) => string;
yTickFormat(format: (t: any) => string): this;
yTickFormat(format: string): this;
yTickFormat(format: (d: any, i: any) => string): this;
interpolate(): string;
interpolate(value: string): this;
rightAlignYAxis(): boolean;
rightAlignYAxis(value: boolean): this;
}
interface Nvd3Axis extends d3.svg.Axis {
axisLabel(): string;
axisLabel(value: string): this;
@@ -1805,6 +1840,7 @@ id(value: number|string): this;
yAxis: Nvd3Axis;
legend: Legend;
tooltip: Tooltip;
focus: Focus;
clearHighlights(): this;
/*If true, masks lines within the X and Y scales using a clip-path*/
@@ -3238,6 +3274,7 @@ id(value: number|string): this;
yAxis: Nvd3Axis;
y2Axis: Nvd3Axis;
tooltip: Tooltip;
focus: Focus;
controlLabels(): any;
/*Object that defines the labels for control items in the graph. For instance, in the stackedAreaChart, there are controls for making it stacked, expanded, or stream. For stacked bar charts, there is stacked and grouped.*/

65
opentok/opentok-tests.ts Normal file
View File

@@ -0,0 +1,65 @@
/// <reference path='opentok.d.ts'' />
import * as OpenTok from 'opentok';
const client = new OpenTok('API_KEY', 'API_SECRET');
const sessionOptions: OpenTok.SessionOptions = {
mediaMode: 'routed',
archiveMode: 'manual',
location: '12.34.56.78',
};
client.createSession(sessionOptions, (err: Error, session: OpenTok.Session) => {
if (err) return console.log(err);
console.log(session.sessionId);
});
const tokenOptions: OpenTok.TokenOptions = {
role: 'subscriber',
data: 'name=Seth',
expireTime: 123456,
};
const token = client.generateToken('SESSION_ID', tokenOptions);
const archiveOptions: OpenTok.ArchiveOptions = {
name: 'name',
hasAudio: true,
hasVideo: true,
outputMode: 'individual',
};
client.startArchive('SESSION_ID', archiveOptions, (err: Error, archive: OpenTok.Archive) => {
if (err) return console.log(err);
console.log(archive.id);
});
client.stopArchive('ARCHIVE_ID', (err: Error, archive: OpenTok.Archive) => {
if (err) return console.log(err);
console.log('Stopped archive:' + archive.id);
});
client.getArchive('ARCHIVE_ID', (err: Error, archive: OpenTok.Archive) => {
if (err) return console.log(err);
console.log(archive);
});
client.deleteArchive('ARCHIVE_ID', (err: Error) => {
if (err) return console.log(err);
console.log('success');
});
const listArchivesOptions: OpenTok.ListArchivesOptions = {
count: 10,
offset: 5,
}
client.listArchives(listArchivesOptions, (err: Error, archives: OpenTok.Archive[], totalCount: number) => {
if (err) return console.log(err);
console.log(totalCount + ' archives');
for (var i = 0; i < archives.length; i++) {
console.log(archives[i].id);
}
});

80
opentok/opentok.d.ts vendored Normal file
View File

@@ -0,0 +1,80 @@
// Type definitions for opentok v2.3.2
// Project: https://github.com/opentok/opentok-node
// Definitions by: Seth Westphal <https://github.com/westy92>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'opentok' {
namespace OpenTok {
export type OutputMode = 'composed' | 'individual';
export type ArchiveStatus = 'available' | 'expired' | 'failed' | 'paused' | 'started' | 'stopped' | 'uploaded';
export interface Archive {
createdAt: number;
duration: string;
id: string;
name: string;
partnerId: string;
reason: string;
sessionId: string;
size: number;
status: ArchiveStatus;
hasAudio: boolean;
hasVideo: boolean;
outputMode: OutputMode;
url: string;
}
export interface ArchiveOptions {
name?: string;
hasAudio?: boolean;
hasVideo?: boolean;
outputMode?: OutputMode;
}
export type MediaMode = 'relayed' | 'routed';
export type ArchiveMode = 'manual' | 'always';
export interface SessionOptions {
mediaMode?: MediaMode;
archiveMode?: ArchiveMode;
location?: string;
}
export interface Session {
sessionId: string;
}
export type Token = string;
export type Role = 'subscriber' | 'publisher' | 'moderator';
export interface TokenOptions {
role?: Role;
data?: string;
expireTime?: number;
}
export interface ListArchivesOptions {
count?: number;
offset?: number;
}
}
class OpenTok {
constructor(apiKey: string, apiSecret: string);
public createSession(options: OpenTok.SessionOptions, callback: (err: Error, session: OpenTok.Session) => void): void;
public generateToken(sessionId: string, options: OpenTok.TokenOptions): OpenTok.Token;
public startArchive(sessionId: string, options: OpenTok.ArchiveOptions, callback: (err: Error, archive: OpenTok.Archive) => void): void;
public stopArchive(archiveId: string, callback: (err: Error, archive: OpenTok.Archive) => void): void;
public getArchive(archiveId: string, callback: (err: Error, archive: OpenTok.Archive) => void): void;
public deleteArchive(archiveId: string, callback: (err: Error) => void): void;
public listArchives(options: OpenTok.ListArchivesOptions, callback: (err: Error, archives: OpenTok.Archive[], totalCount: number) => void): void;
}
export = OpenTok;
}

View File

@@ -11,6 +11,7 @@
import {
Schema,
model,
Document,
PassportLocalDocument,
PassportLocalSchema,
PassportLocalModel,
@@ -34,7 +35,7 @@ interface User extends PassportLocalDocument {
last: Date;
}
const UserSchema: PassportLocalSchema = <PassportLocalSchema>new Schema({
const UserSchema: PassportLocalSchema = new Schema({
username: String,
hash: String,
salt: String,
@@ -77,10 +78,9 @@ options.errorMessages = errorMessages;
UserSchema.plugin(passportLocalMongoose, options);
type UserModel<T extends PassportLocalDocument> = _UserModel<T> & PassportLocalModel<T>;
interface _UserModel<T extends PassportLocalDocument> {}
interface UserModel<T extends Document> extends PassportLocalModel<T> {}
let UserModel: UserModel<User> = model<User>('User', UserSchema) as UserModel<User>;
let UserModel: UserModel<User> = model<User>('User', UserSchema);
//#endregion
@@ -96,7 +96,7 @@ passport.use('login', new LocalStrategy({
process.nextTick(() => {
UserModel
.findOne({ 'username': username })
.exec((err: any, user: model<User>) => {
.exec((err: any, user: User) => {
if (err) {
console.log(err);
return done(err, null);

View File

@@ -10,14 +10,13 @@ declare module 'mongoose' {
import passportLocal = require('passport-local');
// methods
export interface PassportLocalDocument {
export interface PassportLocalDocument extends Document {
setPassword(password: string, cb: (err: any, res: any) => void): void;
authenticate(password: string, cb: (err: any, res: any, error: any) => void): void;
}
// statics
export type PassportLocalModel<T extends PassportLocalDocument> = _PassportLocalModel<T> & Model<T>;
interface _PassportLocalModel<T extends PassportLocalDocument> {
interface PassportLocalModel<T extends Document> extends Model<T> {
authenticate(): (username: string, password: string, cb: (err: any, res: T, error: any) => void) => void;
serializeUser(): (user: PassportLocalModel<T>, cb: (err: any) => void) => void;
deserializeUser(): (username: string, cb: (err: any) => void) => void;
@@ -77,11 +76,17 @@ declare module 'mongoose' {
): this;
}
export function model<T extends PassportLocalDocument, Statics>(
export function model<T extends Document>(
name: string,
schema?: PassportLocalSchema,
collection?: string,
skipInit?: boolean): Statics & PassportLocalModel<T>;
skipInit?: boolean): PassportLocalModel<T>;
export function model<T extends Document, U extends PassportLocalModel<T>>(
name: string,
schema?: PassportLocalSchema,
collection?: string,
skipInit?: boolean): U;
}
declare module 'passport-local-mongoose' {

View File

@@ -0,0 +1,17 @@
/// <reference path="./pathfinding.d.ts" />
import * as PF from "pathfinding";
var matrix = [
[0, 0, 0, 1, 0],
[1, 0, 0, 0, 1],
[0, 0, 1, 0, 0],
];
var grid = new PF.Grid(matrix);
var gridBackup = grid.clone();
var finder = new PF.AStarFinder();
var path = finder.findPath(1, 2, 4, 2, grid);
var newPath = PF.Util.smoothenPath(grid, path);

172
pathfinding/pathfinding.d.ts vendored Normal file
View File

@@ -0,0 +1,172 @@
// Type definitions for pathfinding
// Project: https://github.com/qiao/PathFinding.js
// Definitions by: BNedry <https://github.com/BNedry>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "pathfinding" {
namespace Pathfinding {
export namespace Heuristic {
function manhattan(dx: number, dy: number): number;
function euclidean(dx: number, dy: number): number;
function octile(dx: number, dy: number): number;
function chebyshev(dx: number, dy: number): number;
}
export namespace Util {
function smoothenPath(grid: Grid, path: number[][]): number[][];
function compressPath(path: number[][]): number[][];
function expandPath(path: number[][]): number[][];
}
export enum DiagonalMovement {
Always = 1,
Never = 2,
IfAtMostOneObstacle = 3,
OnlyWhenNoObstacle = 4
}
interface Node {
x: number;
y: number;
walkable: boolean;
}
interface Heuristic {
heuristic?: (dx: number, dy: number) => number;
}
interface FinderOptions extends Heuristic {
diagonalMovement?: DiagonalMovement;
weight?: number;
}
interface IDAStarFinderOptions extends FinderOptions {
trackRecursion?: boolean;
timeLimit?: number;
}
interface JumpPointFinderBaseOptions extends Heuristic {
trackJumpRecursion?: boolean;
}
interface JumpPointFinderOptions extends Heuristic {
diagonalMovement?: DiagonalMovement;
}
interface BiBreadthFirstFinderOptions {
diagonalMovement?: DiagonalMovement;
}
interface Grid {
new (width: number, height: number): Grid;
new (matrix: number[][]): Grid;
setWalkableAt(x: number, y: number, walkable: boolean): void;
clone(): Grid;
getNodeAt(): Pathfinding.Node;
getNeighbors(node: Pathfinding.Node, diagonalMovement: DiagonalMovement): Pathfinding.Node[];
isWalkableAt(x: number, y: number): boolean;
isInside(x: number, y: number): boolean;
width: number;
height: number;
}
interface Finder {
findPath(startX: number, startY: number, endX: number, endY: number, matrix: Grid): number[][];
}
interface AStarFinder extends Finder {
new (): AStarFinder;
new (opt: FinderOptions): AStarFinder;
}
interface BestFirstFinder extends AStarFinder {
new (): BestFirstFinder;
new (opt: JumpPointFinderOptions): BestFirstFinder;
}
interface BiAStarFinder extends Finder {
new (): BiAStarFinder;
new (opt: JumpPointFinderOptions): BiAStarFinder;
}
interface BiBestFirstFinder extends BiAStarFinder {
new (): BiBestFirstFinder;
new (opt: JumpPointFinderOptions): BiBestFirstFinder;
}
interface BiBreadthFirstFinder extends Finder {
new (): BiBreadthFirstFinder;
new (opt: BiBreadthFirstFinderOptions): BiBreadthFirstFinder;
}
interface BiDijkstraFinder extends BiAStarFinder {
new (): BiDijkstraFinder;
new (opt: BiBreadthFirstFinderOptions): BiDijkstraFinder;
}
interface BreadthFirstFinder extends Finder {
new (): BreadthFirstFinder;
new (opt: BiBreadthFirstFinderOptions): BreadthFirstFinder;
}
interface DijkstraFinder extends AStarFinder {
new (): DijkstraFinder;
new (opt: BiBreadthFirstFinderOptions): DijkstraFinder;
}
interface IDAStarFinder extends Finder {
new (): IDAStarFinder;
new (opt: IDAStarFinderOptions): IDAStarFinder;
}
interface JumpPointFinderBase extends Finder {
new (): JumpPointFinderBase;
new (opt: JumpPointFinderBaseOptions): JumpPointFinderBase;
}
interface JPFAlwaysMoveDiagonally extends JumpPointFinderBase {
new (): JPFAlwaysMoveDiagonally;
new (opt: JumpPointFinderBaseOptions): JPFAlwaysMoveDiagonally;
}
interface JPFMoveDiagonallyIfAtMostOneObstacle extends JumpPointFinderBase {
new (): JPFMoveDiagonallyIfAtMostOneObstacle;
new (opt: JumpPointFinderBaseOptions): JPFMoveDiagonallyIfAtMostOneObstacle;
}
interface JPFMoveDiagonallyIfNoObstacles extends JumpPointFinderBase {
new (): JPFMoveDiagonallyIfNoObstacles;
new (opt: JumpPointFinderBaseOptions): JPFMoveDiagonallyIfNoObstacles;
}
interface JPFNeverMoveDiagonally extends JumpPointFinderBase {
new (): JPFNeverMoveDiagonally;
new (opt: JumpPointFinderBaseOptions): JPFNeverMoveDiagonally;
}
interface JumpPointFinder {
(opt: JumpPointFinderOptions): JPFNeverMoveDiagonally | JPFAlwaysMoveDiagonally | JPFMoveDiagonallyIfNoObstacles | JPFMoveDiagonallyIfAtMostOneObstacle;
}
export var Grid: Grid;
export var AStarFinder: AStarFinder;
export var BestFirstFinder: BestFirstFinder;
export var BiAStarFinder: BiAStarFinder;
export var BiBestFirstFinder: BiBestFirstFinder;
export var BiBreadthFirstFinder: BiBreadthFirstFinder;
export var BiDijkstraFinder: BiDijkstraFinder;
export var BreadthFirstFinder: BreadthFirstFinder;
export var DijkstraFinder: DijkstraFinder;
export var IDAStarFinder: IDAStarFinder;
export var JPFAlwaysMoveDiagonally: JPFAlwaysMoveDiagonally;
export var JPFMoveDiagonallyIfAtMostOneObstacle: JPFMoveDiagonallyIfAtMostOneObstacle;
export var JPFMoveDiagonallyIfNoObstacles: JPFMoveDiagonallyIfNoObstacles;
export var JPFNeverMoveDiagonally: JPFNeverMoveDiagonally;
export var JumpPointFinder: JumpPointFinder;
}
export = Pathfinding;
}

View File

@@ -0,0 +1,9 @@
/// <reference path='phone-formatter.d.ts' />
import * as phoneFormatter from 'phone-formatter';
phoneFormatter.normalize('212.555.1212');
phoneFormatter.normalize('+1 (212) 555-1212');
phoneFormatter.format('(212) 555-1212', 'NNN.NNN.NNNN');
phoneFormatter.format('(212) 555-1212', 'NNN.NNN.NNNN', {normalize: false});

14
phone-formatter/phone-formatter.d.ts vendored Normal file
View File

@@ -0,0 +1,14 @@
// Type definitions for phone-formatter v0.0.2
// Project: https://github.com/stevekinney/node-phone-formatter
// Definitions by: Seth Westphal <https://github.com/westy92>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'phone-formatter' {
export interface FormatOptions {
normalize: boolean;
}
export function normalize(digits: string): string;
export function format(digits: string, format: string, options?: FormatOptions): string;
}

View File

@@ -0,0 +1,16 @@
/// <reference path="react-highlighter.d.ts" />
/// <reference path="../react/react.d.ts" />
import * as React from 'react';
import * as Highlight from 'react-highlighter';
export class ReactHolderTest extends React.Component<any, any> {
public render() {
return (
<div>
<Highlight
search="test">test</Highlight>
</div>
);
}
}

View File

@@ -0,0 +1,9 @@
// Type definitions for react-highlighter
// Project: https://github.com/helior/react-highlighter
// Definitions by: Pedro Pereira <https://github.com/oizie>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "react-highlighter" {
var Highlight: any;
export = Highlight;
}

View File

@@ -2,7 +2,8 @@
/// <reference path="react-mdl.d.ts" />
import * as React from 'react';
import {Badge,
import {Chip, ChipContact,
Badge,
FABButton, Button, IconButton,
Card, CardActions, CardTitle, CardText, CardMenu, CardMedia,
Checkbox,
@@ -50,6 +51,34 @@ React.createClass({
}
});
// Chip tests
React.createClass({
render: function() {
return (
<div>
<Chip>Basic chip</Chip>
<Chip onClose={e => { alert('Close icon clicked!'); }}>Deletable Chip</Chip>
<Chip onClick={e => { alert('Clicked!'); }}>Button Chip</Chip>
{/* Contact Chip */}
<Chip>
<ChipContact className="mdl-color--teal mdl-color-text--white">A</ChipContact>
Contact chip
</Chip>
{/* User Contact Chip */}
<Chip onClose={e => { alert('Close icon clicked!'); }}>
<ChipContact
style={{ background: 'url("https://placekitten.com/150/150") 0 0 / cover' }}
/>
Deletable user contact chip
</Chip>
</div>
);
}
});
// Button tests
React.createClass({
render: function() {

View File

@@ -1,4 +1,4 @@
// Type definitions for react-mdl 1.5.3
// Type definitions for react-mdl 1.7.0
// Project: https://github.com/tleunen/react-mdl
// Definitions by: Brad Zacher <https://github.com/bradzacher>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -275,8 +275,17 @@ declare namespace __ReactMDL {
overlap ?: boolean;
}
class Badge extends __MDLComponent<BadgeProps> {}
interface ChipProps extends __MDLOtherProps {
onClick ?:React.MouseEventHandler;
onClose ?:React.MouseEventHandler;
}
class Chip extends __MDLComponent<ChipProps> {}
class ChipContact extends __MDLComponent<__MDLOtherProps> {}
interface ButtonProps extends __MDLOtherProps, RippleComponent, CustomRenderedComponent {
accent ?: boolean;
colored ?: boolean;
@@ -401,9 +410,11 @@ declare namespace __ReactMDL {
transparent ?: boolean;
waterfall ?: boolean;
hideTop ?: boolean;
hideSpacer ?: boolean;
}
interface HeaderRowProps extends __MDLOtherProps {
title ?: string;
hideSpacer ?: boolean;
}
interface HeaderTabsProps extends __MDLOtherProps, RippleComponent {
activeTab ?: number;
@@ -603,4 +614,4 @@ declare namespace __ReactMDL {
declare module 'react-mdl' {
export = __ReactMDL;
}
}

View File

@@ -5977,6 +5977,20 @@ declare namespace __React {
export var NativeModules: any
export var NativeAppEventEmitter: NativeAppEventEmitterStatic
//////////// Plugins //////////////
export interface ComponentInterface<P> {
name?: string;
displayName?: string;
propTypes: P
}
export function requireNativeComponent<P>(
viewName: string,
componentInterface?: ComponentInterface<P>,
extraConfig?: {nativeOnly: Object}
): React.ComponentClass<P>;
//
// /TODO: BGR: These are leftovers of the initial port that must be revisited
//

View File

@@ -129,4 +129,14 @@ let input = { value: "" };
history.createPath('/the/path') // /base/the/path
history.push('/the/path') // push /base/the/path
}
}
{
let history = createHistory()
const { pathname, query, search, state} = history.getCurrentLocation()
console.log(pathname)
console.log(query)
console.log(search)
console.log(state)
}

View File

@@ -29,6 +29,7 @@ declare namespace HistoryModule {
createPath(path: LocationDescriptor): Path
createHref(path: LocationDescriptor): Href
createLocation(path?: LocationDescriptor, action?: Action, key?: LocationKey): Location
getCurrentLocation: () => Location
/** @deprecated use a location descriptor instead */
createLocation(path?: Path, state?: LocationState, action?: Action, key?: LocationKey): Location

1
react/react.d.ts vendored
View File

@@ -1968,7 +1968,6 @@ declare namespace __React {
hrefLang?: string;
htmlFor?: string;
httpEquiv?: string;
icon?: string;
id?: string;
inputMode?: string;
integrity?: string;

View File

@@ -3,4 +3,4 @@
import * as Api from "riot-api-nodejs";
let ClassicApi = new Api.ClassicAPI([""], Api.region_e.EUW);
let TournamentApi = new Api.TournamentAPI("");
let TournamentApi = new Api.TournamentAPI("");

View File

@@ -3,11 +3,17 @@
// Definitions by: Luca Laissue <https://github.com/zafixlrp/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../request/request.d.ts" />
/// <reference path="../riot-games-api/riot-games-api.d.ts" />
declare module "riot-api-nodejs"{
declare module "riot-api-nodejs" {
export const BASE_URL: string;
export const URL_1_2: string;
export const URL_1_3: string;
export const URL_1_4: string;
export const URL_2_2: string;
export const URL_2_4: string;
export const URL_2_5: string;
export enum region_e {
BR = 0,
EUNE = 1,
@@ -22,72 +28,84 @@ declare module "riot-api-nodejs"{
PBE = 10,
}
/**
* Tournament API
*/
export class TournamentAPI {
* Base API
*/
export class API {
private ApiKeys;
private ApiKey;
constructor(ApiKeys: string[]);
/**
* TournamentAPI Constructor
*/
constructor(...ApiKeys: string[]);
/**
* Change the Api Key for the next requests
*/
* Change the Api Key for the next requests
*/
private switchApiKey();
/**
* Send a request to the Riot Games Api and return a formatted json via a callback
* @param {string} url request url
* @param {string} method method(post / put / get)
* @param {[type]} data body parameters
* @param {(JSON} callback callback function with formatted JSON
*/
private getJSON(url, method, data, callback);
* Send a request to the Riot Games Api and return a formatted json via a callback
* @param {string} url request url
* @param {string} method method(post / put / get)
* @param {[type]} data body parameters
* @param {(JSON} callback callback function with formatted JSON
*/
getJSON(url: string, method: string, data: any): Promise<any>;
request(url: string, method: string, data: any, prop?: string): Promise<any>;
/**
* get tournament Codes for a given tournament
* get the API Key that is used for the requests
* @return {string} the current API Key
*/
getCurrentApiKey(): string;
/**
* set the API Keys
* @param {string[]} ApiKeys the API Keys
*/
setApikeys(ApiKeys: string[]): void;
}
/**
* Tournament API
*/
export class TournamentAPI extends API {
constructor(...apiKeys: string[]);
/**
* create tournament Codes for a given tournament
* @param {number} tournamentId the ID of the tournament
* @param {number} count Number of codes you want
* @param {RiotGamesAPI.TournamentProvider.TournamentCodeParameters} params Tournament Code parameters
* @param {number[]} callback Tournaments Codes [description]
*/
getTournamentCodes(tournamentId: number, count: number, params: RiotGamesAPI.TournamentProvider.TournamentCodeParameters, callback: (tournamentCodes: number[]) => void): any;
createTournamentCodes(tournamentId: number, count: number, params: RiotGamesAPI.TournamentProvider.TournamentCodeParameters): Promise<number[]>;
/**
* get tournament infos for a given tournament code
* @param {string} tournamentCode Tournament Code
* @param {RiotGamesAPI.TournamentProvider.TournamentCodeDto} callback Tournament Infos
*/
getTournamentByCode(tournamentCode: string, callback: (tournament: RiotGamesAPI.TournamentProvider.TournamentCodeDto) => void): any;
getTournamentByCode(tournamentCode: string): Promise<RiotGamesAPI.TournamentProvider.TournamentCodeDto>;
/**
* edit the tournament Code parameters for a given tournament Code
* @param {string} tournamentCode Tournament Code to update
* @param {RiotGamesAPI.TournamentProvider.TournamentCodeUpdateParameters} params parameters to edit
* @param {(} callback callback if succes
*/
editTournamentByCode(tournamentCode: string, params: RiotGamesAPI.TournamentProvider.TournamentCodeUpdateParameters, callback: () => void): any;
editTournamentByCode(tournamentCode: string, params: RiotGamesAPI.TournamentProvider.TournamentCodeUpdateParameters): Promise<() => void>;
/**
* get the lobby envents for a given tournament Code
* @param {string} tournamentCode the tournament code to get the lobby events
* @param {RiotGamesAPI.TournamentProvider.LobbyEventDto} callback lobby events
*/
getLobbyEventByCode(tournamentCode: string, callback: (lobbyEventDto: RiotGamesAPI.TournamentProvider.LobbyEventDto) => void): any;
getLobbyEventByCode(tournamentCode: string): Promise<RiotGamesAPI.TournamentProvider.LobbyEventDto>;
/**
* Register a new tournament provider
* @param {region_e} region region where you want to register the provider
* @param {string} url url of callback for the POST notifications
* @param {number} callback returns the tounament provider ID
*/
registerProvider(region: region_e, url: string, callback: (providerId: number) => void): any;
registerProvider(region: region_e, url: string): Promise<number>;
/**
* Register a new tournament
* @param {string} name Name of tournament
* @param {number} providerId Provider ID
* @param {number} callback returns the tournament ID
*/
registerTournament(name: string, providerId: number, callback: (tournamentId: number) => void): any;
registerTournament(name: string, providerId: number): Promise<number>;
}
export class ClassicAPI {
private ApiKeys;
private ApiKey;
export class ClassicAPI extends API {
private region;
/**
* ClassicAPI Constructor
@@ -95,37 +113,17 @@ declare module "riot-api-nodejs"{
* @param {region_e} region region where you want to send requests
*/
constructor(ApiKeys: string[], region: region_e);
/**
* change the API Key for the next requests
*/
private switchApiKey();
/**
* get the JSON response code for a given URL
* @param {string} url Request url
* @param {Function} callback JSON formatted data
*/
private getJSON(url, callback);
/**
* Edit the consts for a valid url for the riot games api
* @param {string} unparsedURL the URL to parse
* @return {string} the Parsed URL
*/
private parseURL(unparsedURL);
/**
* get the API Key that is used for the requests
* @return {string} the current API Key
*/
getCurrentApiKey(): string;
parseURL(unparsedURL: string): string;
/**
* get the region where send send request
* @return {region_e} the current region
*/
getRegion(): region_e;
/**
* set the API Keys
* @param {string[]} ApiKeys the API Keys
*/
setApikeys(ApiKeys: string[]): void;
/**
* set the region where you want to send requests
* @param {region_e} region the region
@@ -135,278 +133,278 @@ declare module "riot-api-nodejs"{
* get all champions of league of legends
* @param {RiotGamesAPI.Champion.ChampionListDto} callback data callback
*/
getChampions(callback: (championListDto: RiotGamesAPI.Champion.ChampionListDto) => void): any;
getChampions(): Promise<RiotGamesAPI.Champion.ChampionListDto>;
/**
* get the champion for a given id
* @param {number} id the champion id
* @param {RiotGamesAPI.Champion.ChampionDto} callback data callback
*/
getChampionById(id: number, callback: (ChampionDto: RiotGamesAPI.Champion.ChampionDto) => void): any;
getChampionById(id: number): Promise<RiotGamesAPI.Champion.ChampionDto>;
/**
* get the free to play champions
* @param {RiotGamesAPI.Champion.ChampionListDto} callback data callback
*/
getFreeToPlayChampions(callback: (championsListDto: RiotGamesAPI.Champion.ChampionListDto) => void): any;
getFreeToPlayChampions(): Promise<RiotGamesAPI.Champion.ChampionListDto>;
/**
* get Champion mastery of a player for a given champion ID
* @param {number} summonerId summoner ID
* @param {number} championId Champion ID
* @param {RiotGamesAPI.ChampionMastery.ChampionMasteryDto} callback data callback
*/
getChampionMastery(summonerId: number, championId: number, callback: (championMastery: RiotGamesAPI.ChampionMastery.ChampionMasteryDto) => void): any;
getChampionMastery(summonerId: number, championId: number): Promise<RiotGamesAPI.ChampionMastery.ChampionMasteryDto>;
/**
* get all champion masteries for a given summoner
* @param {number} summonerId Summoner ID
* @param {[RiotGamesAPI.ChampionMastery.ChampionMasteryDto]} callback data callback
*/
getChampionMasteryBySummoner(summonerId: number, callback: (championsMastery: [RiotGamesAPI.ChampionMastery.ChampionMasteryDto]) => void): any;
getChampionMasteryBySummoner(summonerId: number): Promise<[RiotGamesAPI.ChampionMastery.ChampionMasteryDto]>;
/**
* get the mastery score of a summoner
* @param {number} summonerId Summoner ID
* @param {number} callback Mastery Score
*/
getChampionMasteryScore(summonerId: number, callback: (score: number) => void): any;
getChampionMasteryScore(summonerId: number): Promise<number>;
/**
* get The 3 best champion masteries
* @param {[type]} summonerId Summoner ID
* @param {[RiotGamesAPI.ChampionMastery.ChampionMasteryDto]} callback data callback
*/
getTopChampionMastery(summonerId: any, callback: (championsMastery: [RiotGamesAPI.ChampionMastery.ChampionMasteryDto]) => void): any;
getTopChampionMastery(summonerId: any): Promise<[RiotGamesAPI.ChampionMastery.ChampionMasteryDto]>;
/**
* get the current game infos for a given summoner ID
* @param {number} summonerId Summoner ID
* @param {RiotGamesAPI.CurrentGame.CurrentGameInfo} callback data callback
*/
getCurrentGame(summonerId: number, callback: (gameInfoDto: RiotGamesAPI.CurrentGame.CurrentGameInfo) => void): any;
getCurrentGame(summonerId: number): Promise<RiotGamesAPI.CurrentGame.CurrentGameInfo>;
/**
* get the featured games
* @param {RiotGamesAPI.FeaturedGames.FeaturedGames} callback data callback
*/
getFeaturedGame(callback: (featuredGamesInfos: RiotGamesAPI.FeaturedGames.FeaturedGames) => void): any;
getFeaturedGame(): Promise<RiotGamesAPI.FeaturedGames.FeaturedGames>;
/**
* get the recents games for a given Summoner ID
* @param {number} summonerId Summoner ID
* @param {RiotGamesAPI.Game.RecentGamesDto} callback data callback
*/
getRecentGames(summonerId: number, callback: (RecentGamesDto: RiotGamesAPI.Game.RecentGamesDto) => void): any;
getRecentGames(summonerId: number): Promise<RiotGamesAPI.Game.RecentGamesDto>;
/**
* Get League infos of a summoner
* @param {number} summonerId Summoner ID
* @param {RiotGamesAPI.League.LeagueDto[]} callback data callback
*/
getLeagueBySummonerId(summonerId: number, callback: (LeagueDto: RiotGamesAPI.League.LeagueDto[]) => void): any;
getLeagueBySummonerId(summonerId: number): Promise<RiotGamesAPI.League.LeagueDto[]>;
/**
* get League infos of a summoner
* @param {number} summonerId Summoner ID
* @param {RiotGamesAPI.League.LeagueDto[]} callback data callback
*/
getLeagueBySummonerIdEntry(summonerId: number, callback: (LeagueDto: RiotGamesAPI.League.LeagueDto[]) => void): any;
getLeagueBySummonerIdEntry(summonerId: number): Promise<RiotGamesAPI.League.LeagueDto[]>;
/**
* get league infos by team
* @param {string} teamId Team ID
* @param {RiotGamesAPI.League.LeagueDto[]} callback data callback
*/
getLeagueByTeamId(teamId: string, callback: (LeagueDto: RiotGamesAPI.League.LeagueDto[]) => void): any;
getLeagueByTeamId(teamId: string): Promise<RiotGamesAPI.League.LeagueDto[]>;
/**
* get league infos by team
* @param {string} teamId Team ID
* @param {RiotGamesAPI.League.LeagueDto[]} callback data callback
*/
getLeagueByTeamIdEntry(teamId: string, callback: (LeagueDto: RiotGamesAPI.League.LeagueDto[]) => void): any;
getLeagueByTeamIdEntry(teamId: string): Promise<RiotGamesAPI.League.LeagueDto[]>;
/**
* get Challengers in SOLO Queue
* @param {RiotGamesAPI.League.LeagueDto} callback data callback
*/
getChallengers_SOLO(callback: (League: RiotGamesAPI.League.LeagueDto) => void): any;
getChallengers_SOLO(): Promise<RiotGamesAPI.League.LeagueDto>;
/**
* get Challengers Teams in 3x3
* @param {RiotGamesAPI.League.LeagueDto} callback data callback
*/
getChallengers_3x3(callback: (League: RiotGamesAPI.League.LeagueDto) => void): any;
getChallengers_3x3(): Promise<RiotGamesAPI.League.LeagueDto>;
/**
* get Challengers Teams in 5x5
* @param {RiotGamesAPI.League.LeagueDto} callback data callback
*/
getChallengers_5x5(callback: (League: RiotGamesAPI.League.LeagueDto) => void): any;
getChallengers_5x5(): Promise<RiotGamesAPI.League.LeagueDto>;
/**
* get Masters in Solo Queue
* @param {RiotGamesAPI.League.LeagueDto} callback data callback
*/
getMasters_SOLO(callback: (League: RiotGamesAPI.League.LeagueDto) => void): any;
getMasters_SOLO(): Promise<RiotGamesAPI.League.LeagueDto>;
/**
* get Master Teams in 3x3
* @param {RiotGamesAPI.League.LeagueDto} callback data callback
*/
getMasters_3x3(callback: (League: RiotGamesAPI.League.LeagueDto) => void): any;
getMasters_3x3(): Promise<RiotGamesAPI.League.LeagueDto>;
/**
* get Master Teams in 5x5
* @param {RiotGamesAPI.League.LeagueDto} callback data callback
*/
getMasters_5x5(callback: (League: RiotGamesAPI.League.LeagueDto) => void): any;
getMasters_5x5(): Promise<RiotGamesAPI.League.LeagueDto>;
/**
* get Champions (static data)
* @param {RiotGamesAPI.LolStaticData.ChampionListDto} callback data callback
*/
staticDataChampions(callback: (championListDto: RiotGamesAPI.LolStaticData.ChampionListDto) => void): any;
staticDataChampions(): Promise<RiotGamesAPI.LolStaticData.ChampionListDto>;
/**
* get data by champion ID
* @param {number} championsId Champion ID
* @param {RiotGamesAPI.LolStaticData.ChampionDto} callback data callback
*/
staticDataChampionById(championsId: number, callback: (championDto: RiotGamesAPI.LolStaticData.ChampionDto) => void): any;
staticDataChampionById(championsId: number): Promise<RiotGamesAPI.LolStaticData.ChampionDto>;
/**
* get League of Legends Items
* @param {RiotGamesAPI.LolStaticData.ItemListDto} callback data callback
*/
staticDataItems(callback: (itemsDto: RiotGamesAPI.LolStaticData.ItemListDto) => void): any;
staticDataItems(): Promise<RiotGamesAPI.LolStaticData.ItemListDto>;
/**
* Get item infos by ID
* @param {number} itemId item ID
* @param {RiotGamesAPI.LolStaticData.ItemDto} callback data callback
*/
staticDataItemById(itemId: number, callback: (itemDto: RiotGamesAPI.LolStaticData.ItemDto) => void): any;
staticDataItemById(itemId: number): Promise<RiotGamesAPI.LolStaticData.ItemDto>;
/**
* get league of legends languages
* @param {RiotGamesAPI.LolStaticData.LanguageStringsDto} callback data callback
*/
staticDataLanguagesStrings(callback: (languageStringsDto: RiotGamesAPI.LolStaticData.LanguageStringsDto) => void): any;
staticDataLanguagesStrings(): Promise<RiotGamesAPI.LolStaticData.LanguageStringsDto>;
/**
* get league of legends languages
* @param {string[]} callback data callback
*/
staticDataLanguages(callback: (languages: string[]) => void): any;
staticDataLanguages(): Promise<string[]>;
/**
* get Map data
* @param {RiotGamesAPI.LolStaticData.MapDataDto} callback data callback
*/
staticDataMap(callback: (mapDataDto: RiotGamesAPI.LolStaticData.MapDataDto) => void): any;
staticDataMap(): Promise<RiotGamesAPI.LolStaticData.MapDataDto>;
/**
* get all masteries
* @param {RiotGamesAPI.LolStaticData.MasteryListDto} callback data callback
*/
staticDataMastery(callback: (masteryListDto: RiotGamesAPI.LolStaticData.MasteryListDto) => void): any;
staticDataMastery(): Promise<RiotGamesAPI.LolStaticData.MasteryListDto>;
/**
* get data by mastery ID
* @param {number} masteryId Mastery ID
* @param {RiotGamesAPI.LolStaticData.MasteryDto} callback data callback
*/
staticDataMasteryById(masteryId: number, callback: (masteryDto: RiotGamesAPI.LolStaticData.MasteryDto) => void): any;
staticDataRealm(callback: (realmDto: RiotGamesAPI.LolStaticData.RealmDto) => void): any;
staticDataMasteryById(masteryId: number): Promise<RiotGamesAPI.LolStaticData.MasteryDto>;
staticDataRealm(): Promise<RiotGamesAPI.LolStaticData.RealmDto>;
/**
* get all runes
* @param {RiotGamesAPI.LolStaticData.RuneListDto} callback data callback
*/
staticDataRunes(callback: (runeListDto: RiotGamesAPI.LolStaticData.RuneListDto) => void): any;
staticDataRunes(): Promise<RiotGamesAPI.LolStaticData.RuneListDto>;
/**
* get rune by Rune ID
* @param {number} runeId Rune ID
* @param {RiotGamesAPI.LolStaticData.RuneDto} callback data callback
*/
staticDataRuneById(runeId: number, callback: (runeDto: RiotGamesAPI.LolStaticData.RuneDto) => void): any;
staticDataRuneById(runeId: number): Promise<RiotGamesAPI.LolStaticData.RuneDto>;
/**
* get all summoner spells
* @param {RiotGamesAPI.LolStaticData.SummonerSpellListDto} callback data callback
*/
staticDataSummonerSpells(callback: (summonerSpellListDto: RiotGamesAPI.LolStaticData.SummonerSpellListDto) => void): any;
staticDataSummonerSpells(): Promise<RiotGamesAPI.LolStaticData.SummonerSpellListDto>;
/**
* get summoner spell by summoner spell ID
* @param {number} summonerSpellId Summoner spell ID
* @param {RiotGamesAPI.LolStaticData.SummonerSpellDto} callback data callback
*/
staticDataSummonSpellById(summonerSpellId: number, callback: (runeDto: RiotGamesAPI.LolStaticData.SummonerSpellDto) => void): any;
staticDataSummonSpellById(summonerSpellId: number): Promise<RiotGamesAPI.LolStaticData.SummonerSpellDto>;
/**
* get league of legends versions
* @param {string[]} callback data callback
*/
staticDataVersion(callback: (versions: string[]) => void): any;
staticDataVersion(): Promise<string[]>;
/**
* get league of legends status
* @param {RiotGamesAPI.LolStatus.Shard[]} callback data callback
*/
getSatus(callback: (shardList: RiotGamesAPI.LolStatus.Shard[]) => void): any;
getSatus(): Promise<RiotGamesAPI.LolStatus.Shard[]>;
/**
* get status for a given region
* @param {region_e} region region
* @param {RiotGamesAPI.LolStatus.Shard} callback data callback
*/
getSatusByRegion(region: region_e, callback: (shard: RiotGamesAPI.LolStatus.Shard) => void): any;
getSatusByRegion(region: region_e): Promise<RiotGamesAPI.LolStatus.Shard>;
/**
* get match infos for a given match ID
* @param {number} matchId Match ID
* @param {RiotGamesAPI.Match.MatchDetail} callback data callback
*/
getMatch(matchId: number, callback: (matchDetails: RiotGamesAPI.Match.MatchDetail) => void): any;
getMatch(matchId: number): Promise<RiotGamesAPI.Match.MatchDetail>;
/**
* get all matches for a given tournament code
* @param {string} tournamentCode Tournament Code
* @param {number[]} callback data callback
*/
getMatchIdsByTournamentCode(tournamentCode: string, callback: (matchIds: number[]) => void): any;
getMatchIdsByTournamentCode(tournamentCode: string): Promise<number[]>;
/**
* get match by ID in a tournament
* @param {number} matchId Match ID
* @param {RiotGamesAPI.Match.MatchDetail} callback data callback
*/
getMatchForTournament(matchId: number, callback: (matchDetails: RiotGamesAPI.Match.MatchDetail) => void): any;
getMatchForTournament(matchId: number): Promise<RiotGamesAPI.Match.MatchDetail>;
/**
* get match list of a summoner
* @param {number} summonerId Summoner ID
* @param {RiotGamesAPI.MatchList.MatchList} callback data callback
*/
getMatchList(summonerId: number, callback: (matchList: RiotGamesAPI.MatchList.MatchList) => void): any;
getMatchList(summonerId: number): Promise<RiotGamesAPI.MatchList.MatchList>;
/**
* get ranked stats of summoner
* @param {number} summonerId Summoner ID
* @param {RiotGamesAPI.Stats.RankedStatsDto} callback data callback
*/
getStatsRanked(summonerId: number, callback: (rankedStatsDto: RiotGamesAPI.Stats.RankedStatsDto) => void): any;
getStatsRanked(summonerId: number): Promise<RiotGamesAPI.Stats.RankedStatsDto>;
/**
* get summary ranked stats of summoner
* @param {number} summonerId Summoner ID
* @param {RiotGamesAPI.Stats.PlayerStatsSummaryListDto} callback data callback
*/
getStatsSummary(summonerId: number, callback: (playerStatsSummaryListDto: RiotGamesAPI.Stats.PlayerStatsSummaryListDto) => void): any;
getStatsSummary(summonerId: number): Promise<RiotGamesAPI.Stats.PlayerStatsSummaryListDto>;
/**
* get summoner infos by Summoner Name
* @param {string} summonerName Summoner Name
* @param {RiotGamesAPI.Summoner.SummonerDto} callback data callback
*/
getSummonerByName(summonerName: string, callback: (summonerDto: RiotGamesAPI.Summoner.SummonerDto) => void): any;
getSummonerByName(summonerName: string): Promise<RiotGamesAPI.Summoner.SummonerDto>;
/**
* get summoner infos by summoner ID
* @param {number} summonerId Summoner ID
* @param {RiotGamesAPI.Summoner.SummonerDto} callback data callback
*/
getSummonerById(summonerId: number, callback: (summonerDto: RiotGamesAPI.Summoner.SummonerDto) => void): any;
getSummonerById(summonerId: number): Promise<RiotGamesAPI.Summoner.SummonerDto>;
/**
* get masteries of a summoner
* @param {number} summonerId Summoner ID
* @param {RiotGamesAPI.Summoner.MasteryPagesDto} callback data callback
*/
getSummonerMasteries(summonerId: number, callback: (masteryPagesDto: RiotGamesAPI.Summoner.MasteryPagesDto) => void): any;
getSummonerMasteries(summonerId: number): Promise<RiotGamesAPI.Summoner.MasteryPagesDto>;
/**
* get the Summoner Name of a summoner ID
* @param {number} summonerId Summoner ID
* @param {string} callback data callback
*/
getSummonerName(summonerId: number, callback: (summonerName: string) => void): any;
getSummonerName(summonerId: number): Promise<string>;
/**
* get the runes of a summoner
* @param {number} summonerId Summoner ID
* @param {RiotGamesAPI.Summoner.RunePagesDto} callback data callback
*/
getSummonerRunes(summonerId: number, callback: (runePagesDto: RiotGamesAPI.Summoner.RunePagesDto) => void): any;
getSummonerRunes(summonerId: number): Promise<RiotGamesAPI.Summoner.RunePagesDto>;
/**
* get teams of a summoner
* @param {number} summonerId Summoner ID
* @param {RiotGamesAPI.Team.TeamDto[]} callback data callback
*/
getTeamsBySummoner(summonerId: number, callback: (teamsList: RiotGamesAPI.Team.TeamDto[]) => void): any;
getTeamsBySummoner(summonerId: number): Promise<RiotGamesAPI.Team.TeamDto[]>;
/**
* get Team infos by Team ID
* @param {string} teamId Team ID
* @param {RiotGamesAPI.Team.TeamDto} callback data callback
*/
getTeamById(teamId: string, callback: (teamDto: RiotGamesAPI.Team.TeamDto) => void): any;
getTeamById(teamId: string): Promise<RiotGamesAPI.Team.TeamDto>;
}
}

View File

@@ -23,9 +23,16 @@ declare module "slate-irc" {
motd: string[];
}
interface TopicEvent {
nick: string;
hostmask: string;
channel: string;
topic: string;
}
interface MessageEvent {
from: string;
hostmask: any;
hostmask: string;
to: string;
message: string;
}
@@ -48,6 +55,18 @@ declare module "slate-irc" {
new: string;
}
interface ModeEvent {
nick: string;
target: string;
mode: string;
client: string;
}
interface AwayEvent {
nick: string;
message: string;
}
interface QuitEvent {
nick: string;
hostmask: string;
@@ -87,9 +106,12 @@ declare module "slate-irc" {
on(event: "message", callback: (event: MessageEvent) => void): void;
on(event: "notice", callback: (event: MessageEvent) => void): void;
on(event: "motd", callback: (event: MOTDEvent) => void): void;
on(event: "topic", callback: (event: TopicEvent) => void): void;
on(event: "join", callback: (event: JoinEvent) => void): void;
on(event: "part", callback: (event: PartEvent) => void): void;
on(event: "nick", callback: (event: NickEvent) => void): void;
on(event: "mode", callback: (event: ModeEvent) => void): void;
on(event: "away", callback: (event: AwayEvent) => void): void;
on(event: "quit", callback: (event: QuitEvent) => void): void;
}
}

2
soap/soap.d.ts vendored
View File

@@ -11,7 +11,7 @@ declare module 'soap' {
interface Security {
}
class WSSecurity implements Security {
constructor(username: string, password: string, options: any);
constructor(username: string, password: string, options?: any);
}
class ClientSSLSecurity implements Security {
constructor(key: string, cert: string, ca: string, defaults: any);

View File

@@ -13,7 +13,7 @@ var config: tedious.ConnectionConfig = {
database: "somedb",
instanceName: "someinstance",
}
}
};
var connection = new tedious.Connection(config);
connection.on("connect", (): void => {
@@ -23,7 +23,12 @@ connection.on("connect", (): void => {
connection.beginTransaction((error: Error): void => {}, "some name");
connection.rollbackTransaction((error: Error): void => {});
connection.commitTransaction((error: Error): void => {});
connection.saveTransaction((error: Error): void => {});
connection.transaction((error: Error, done: (error?: Error) => void): void => {
done();
done(error);
}, "some name", tedious.ISOLATION_LEVEL.NO_CHANGE);
connection.transaction((error: Error, done: (error?: Error) => void): void => {});
var request = new tedious.Request("SELECT * FROM foo", (error: Error, rowCount: number): void => {
});

26
tedious/tedious.d.ts vendored
View File

@@ -443,7 +443,7 @@ declare module 'tedious' {
* a connection, another request should not be initiated until this callback is called.
* @param callback The callback is called when the request to start the transaction has completed, either successfully or with an error. If an error occured then err will describe the error.
* @param name A string representing a name to associate with the transaction. Optional, and defaults to an empty string. Required when isolationLevel is present.
* @param isolationLevel The isolation level that the transaction is to be run with.
* @param isolationLevel The isolation level that the transaction is to be run with.
*/
beginTransaction(callback: (error?: Error) => void, name?: string, isolationLevel?: ISOLATION_LEVEL): void;
@@ -456,12 +456,32 @@ declare module 'tedious' {
commitTransaction(callback: (error: Error) => void): void;
/**
* Rollback a transaction. There should be an active transaction. That is, beginTransaction should have been previously called.
* @param callback The callback is called when the request to rollback the transaction has completed, either successfully or with an error. If an error occured then err will describe the error.
* Rollback a transaction. There should be an active transaction. That is, beginTransaction should have been previously called.
* @param callback The callback is called when the request to rollback the transaction has completed, either successfully or with an error. If an error occured then err will describe the error.
* As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called.
*/
rollbackTransaction(callback: (error: Error) => void): void;
/**
* Set a savepoint within a transaction. There should be an active transaction. That is, beginTransaction should have been previously called.
* @param callback The callback is called when the request to set a savepoint within the transaction has completed, either successfully or with an error. If an error occured then err will describe the error.
* As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called.
*/
saveTransaction(callback: (error: Error) => void): void;
/**
* Run the given callback after starting a transaction, and commit or rollback the transaction afterwards.
* This is a helper that employs beginTransaction, commitTransaction, rollbackTransaction and saveTransaction to greatly simplify the use of database transactions and automatically handle transaction nesting.
* @param callback The callback is called when the request to start a transaction (or create a savepoint, in the case of a nested transaction) has completed, either successfully or with an error.
* If an error occured, then err will describe the error. If no error occured, the callback should perform its work and eventually call done with an error or null
* (to trigger a transaction rollback or a transaction commit) and an additional completion callback that will be called when the request to rollback or commit the current transaction
* has completed, either successfully or with an error. Additional arguments given to done will be passed through to this callback.
* As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called.
* @param name A string representing a name to associate with the transaction. Optional, and defaults to an empty string. In case of a nested transaction, naming the transaction name has no effect.
* @param isolationLevel The isolation level that the transaction is to be run with.
*/
transaction(callback: (error: Error, done: (error?: Error) => void) => void, name?: string, isolationLevel?: ISOLATION_LEVEL): void;
/**
* Prepare the SQL represented by the request. The request can then be used in subsequent calls to execute and unprepare
* @param request A Request object representing the request. Parameters only require a name and type. Parameter values are ignored.

View File

@@ -1,4 +1,4 @@
import { twilio } from './twilio';
import * as twilio from './twilio';
// Examples taken from https://twilio.github.io/twilio-node/ (v2.1.0)

7
twilio/twilio.d.ts vendored
View File

@@ -12,11 +12,11 @@ import * as Http from 'http';
import q = require('q');
export interface twilio {
declare interface twilio {
(sid?: string, tkn?: string, options?: twilio.ClientOptions): twilio.RestClient;
}
export module twilio {
declare module twilio {
// Composite Classes:
//==============================
@@ -871,5 +871,6 @@ export module twilio {
originationUrls: OriginationURLResource;
}
export interface TrunkResource extends ListMappedResource<TrunkInstance> {}
}
}
export = twilio;

35
ws/ws.d.ts vendored
View File

@@ -34,21 +34,8 @@ declare module "ws" {
onclose: (event: {wasClean: boolean; code: number; reason: string; target: WebSocket}) => void;
onmessage: (event: {data: any; type: string; target: WebSocket}) => void;
constructor(address: string, options?: {
protocol?: string;
agent?: http.Agent;
headers?: {[key: string]: string};
protocolVersion?: any;
host?: string;
origin?: string;
pfx?: any;
key?: any;
passphrase?: string;
cert?: any;
ca?: any[];
ciphers?: string;
rejectUnauthorized?: boolean;
});
constructor(address: string, options?: WebSocket.IClientOptions);
constructor(address: string, protocols?: string | string[], options?: WebSocket.IClientOptions);
close(code?: number, data?: any): void;
pause(): void;
@@ -92,7 +79,23 @@ declare module "ws" {
type VerifyClientCallbackSync = (info: {origin: string; secure: boolean; req: http.ServerRequest}) => boolean;
type VerifyClientCallbackAsync = (info: {origin: string; secure: boolean; req: http.ServerRequest}
, callback: (res: boolean) => void) => void;
export interface IClientOptions {
protocol?: string;
agent?: http.Agent;
headers?: {[key: string]: string};
protocolVersion?: any;
host?: string;
origin?: string;
pfx?: any;
key?: any;
passphrase?: string;
cert?: any;
ca?: any[];
ciphers?: string;
rejectUnauthorized?: boolean;
}
export interface IServerOptions {
host?: string;
port?: number;