Merge branch 'master' into jquery.fileupload

This commit is contained in:
Neil Culver
2016-05-27 14:35:06 +01:00
197 changed files with 30395 additions and 1549 deletions
+1 -1
View File
@@ -695,7 +695,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](heap/heap.d.ts) [heap](https://github.com/qiao/heap.js) by [Ryan McNamara](https://github.com/ryan10132)
* [:link:](heatmap.js/heatmap.d.ts) [heatmap.js](https://github.com/pa7/heatmap.js) by [Yang Guan](https://github.com/lookuptable)
* [:link:](hellojs/hellojs.d.ts) [hello.js](http://adodson.com/hello.js) by [Pavel Zika](https://github.com/PavelPZ)
* [:link:](helmet/helmet.d.ts) [helmet](https://github.com/helmetjs/helmet) by [Cyril Schumacher](https://github.com/cyrilschumacher)
* [:link:](helmet/helmet.d.ts) [helmet](https://github.com/helmetjs/helmet) by [Cyril Schumacher](https://github.com/cyrilschumacher), [Evan Hahn](https://github.com/EvanHahn)
* [:link:](highcharts/highcharts.d.ts) [Highcharts](http://www.highcharts.com) by [Damiano Gambarotto](http://github.com/damianog), [Dan Lewi Harkestad](http://github.com/baltie)
* [:link:](highcharts-ng/highcharts-ng.d.ts) [highcharts-ng](https://github.com/pablojim/highcharts-ng) by [Scott Hatcher](https://github.com/scatcher)
* [:link:](highland/highland.d.ts) [Highland](http://highlandjs.org) by [Bart van der Schoor](https://github.com/Bartvds)
+9
View File
@@ -0,0 +1,9 @@
/// <reference path="CybozuLabs-md5.d.ts" />
var hash: string;
hash = CybozuLabs.MD5.calc("abc");
hash = CybozuLabs.MD5.calc("abc", CybozuLabs.MD5.BY_ASCII);
hash = CybozuLabs.MD5.calc("abc", CybozuLabs.MD5.BY_UTF16);
var version: string;
version = CybozuLabs.MD5.VERSION;
+11
View File
@@ -0,0 +1,11 @@
// Type definitions for CybozuLabs.MD5
// Project: http://labs.cybozu.co.jp/blog/mitsunari/2007/07/md5js_1.html
// Definitions by: MIZUNE Pine <https://github.com/pine613>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace CybozuLabs.MD5 {
var VERSION: string;
var BY_ASCII: number;
var BY_UTF16: number;
function calc(str: string, option?: number): string;
}
@@ -55,6 +55,18 @@ myApp.controller('DialogController', ($scope: ng.IScope, $mdDialog: ng.material.
$scope['confirmDialog'] = () => {
$mdDialog.show($mdDialog.confirm().htmlContent('<span>Confirm!</span>'));
};
$scope['promptDialog'] = () => {
$mdDialog.show($mdDialog.prompt().textContent('Prompt!'));
};
$scope['promptDialog'] = () => {
$mdDialog.show($mdDialog.prompt().htmlContent('<span>Prompt!</span>'));
};
$scope['promptDialog'] = () => {
$mdDialog.show($mdDialog.prompt().cancel('Prompt "Cancel" button text'));
};
$scope['promptDialog'] = () => {
$mdDialog.show($mdDialog.prompt().placeholder('Prompt input placeholder text'));
};
$scope['hideDialog'] = $mdDialog.hide.bind($mdDialog, 'hide');
$scope['cancelDialog'] = $mdDialog.cancel.bind($mdDialog, 'cancel');
});
+6
View File
@@ -59,6 +59,11 @@ declare namespace angular.material {
interface IConfirmDialog extends IPresetDialog<IConfirmDialog> {
cancel(cancel: string): IConfirmDialog;
}
interface IPromptDialog extends IPresetDialog<IPromptDialog> {
cancel(cancel: string): IPromptDialog;
placeholder(placeholder: string): IPromptDialog;
}
interface IDialogOptions {
templateUrl?: string;
@@ -90,6 +95,7 @@ declare namespace angular.material {
show(dialog: IDialogOptions|IAlertDialog|IConfirmDialog): angular.IPromise<any>;
confirm(): IConfirmDialog;
alert(): IAlertDialog;
prompt(): IPromptDialog;
hide(response?: any): angular.IPromise<any>;
cancel(response?: any): void;
}
+3 -3
View File
@@ -35,7 +35,7 @@ declare namespace angular.ui {
/**
* String HTML content, or function that returns an HTML string
*/
template?: string | {(): string};
template?: string | {(params: IStateParamsService): string};
/**
* String URL path to template file OR Function, returns URL path string
*/
@@ -229,9 +229,9 @@ declare namespace angular.ui {
*/
notify?: boolean;
/**
* {boolean=false}, If true will force transition even if the state or params have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd use this when you want to force a reload when everything is the same, including search params.
* {boolean=false|string|IState}, If true will force transition even if the state or params have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd use this when you want to force a reload when everything is the same, including search params.
*/
reload?: boolean;
reload?: boolean | string | IState;
}
interface IHrefOptions {
+31 -4
View File
@@ -389,9 +389,9 @@ declare namespace angular {
$submitted: boolean;
$error: any;
$pending: any;
$addControl(control: INgModelController): void;
$removeControl(control: INgModelController): void;
$setValidity(validationErrorKey: string, isValid: boolean, control: INgModelController): void;
$addControl(control: INgModelController | IFormController): void;
$removeControl(control: INgModelController | IFormController): void;
$setValidity(validationErrorKey: string, isValid: boolean, control: INgModelController | IFormController): void;
$setDirty(): void;
$setPristine(): void;
$commitViewValue(): void;
@@ -1845,7 +1845,7 @@ declare namespace angular {
controller(name: string): any;
injector(): any;
scope(): IScope;
/**
* Overload for custom scope interfaces
*/
@@ -1870,6 +1870,33 @@ declare namespace angular {
annotate(fn: Function, strictDi?: boolean): string[];
annotate(inlineAnnotatedFunction: any[]): string[];
get<T>(name: string, caller?: string): T;
get(name: '$anchorScroll'): IAnchorScrollService
get(name: '$cacheFactory'): ICacheFactoryService
get(name: '$compile'): ICompileService
get(name: '$controller'): IControllerService
get(name: '$document'): IDocumentService
get(name: '$exceptionHandler'): IExceptionHandlerService
get(name: '$filter'): IFilterService
get(name: '$http'): IHttpService
get(name: '$httpBackend'): IHttpBackendService
get(name: '$httpParamSerializer'): IHttpParamSerializer
get(name: '$httpParamSerializerJQLike'): IHttpParamSerializer
get(name: '$interpolate'): IInterpolateService
get(name: '$interval'): IIntervalService
get(name: '$locale'): ILocaleService
get(name: '$location'): ILocationService
get(name: '$log'): ILogService
get(name: '$parse'): IParseService
get(name: '$q'): IQService
get(name: '$rootElement'): IRootElementService
get(name: '$rootScope'): IRootScopeService
get(name: '$sce'): ISCEService
get(name: '$sceDelegate'): ISCEDelegateService
get(name: '$templateCache'): ITemplateCacheService
get(name: '$templateRequest'): ITemplateRequestService
get(name: '$timeout'): ITimeoutService
get(name: '$window'): IWindowService
get<T>(name: '$xhrFactory'): IXhrFactory<T>
has(name: string): boolean;
instantiate<T>(typeConstructor: Function, locals?: any): T;
invoke(inlineAnnotatedFunction: any[]): any;
+15
View File
@@ -0,0 +1,15 @@
/// <reference path="argv.d.ts" />
import argv = require('argv');
argv.version( 'v1.0' );
argv.info( 'Special script info' );
argv.clear()
.option({
name: 'option',
short: 'o',
type: 'string',
description: 'Defines an option for your script',
example: "'script --opiton=value' or 'script -o value'"
})
.run([ '--option=123', '-o', '123' ]);
argv.run();
argv.help();
+59
View File
@@ -0,0 +1,59 @@
// Type definitions for argv
// Project: https://www.npmjs.com/package/argv
// Definitions by: Hookclaw <https://github.com/hookclaw>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "argv" {
// argv module
type args = {
targets:string[],
options:{[key:string]:any}
};
type helpOption = {
name: string,
type: string,
short?: string,
description?: string,
example?: string
};
type module = {
mod: string,
description: string,
options: {[key:string]:helpOption}
};
type typeFunction = (value:any, ...arglist:any[]) => any;
type argv = {
// Runs the arguments parser
run: ( argv?:string[] ) => args,
// Adding options to definitions list
option: ( mod:helpOption|helpOption[] ) => argv,
// Creating module
mod: ( object:module|module[] ) => argv,
// Creates custom type function
type: ( name:string|{[key:string]:typeFunction}, callback?:typeFunction ) => any,
// Setting version number, and auto setting version option
version: ( v:string ) => argv,
// Description setup
info: ( mod:string, description?:module ) => argv,
// Cleans out current options
clear: () => argv,
// Prints out the help doc
help: ( mod?:string ) => argv
};
var argv:argv;
export = argv;
}
+3 -2
View File
@@ -102,5 +102,6 @@ declare namespace Atmosphere {
}
declare var atmosphere:Atmosphere.Atmosphere;
declare module 'atmosphere' {
export = atmosphere;
}
+7 -1
View File
@@ -101,4 +101,10 @@ function TestGlobalApiAndChannels() {
Backbone.Radio.reply('auth', 'authenticate', onStart);
Backbone.Radio.request('auth', 'authenticate', 'pelle', 42);
}
}
import Radio = require('backbone.radio');
function TestImport() {
var channel: Backbone.Radio.Channel = Radio.channel('channel-name');
channel.command('show:view');
}
+6
View File
@@ -90,3 +90,9 @@ declare namespace Backbone {
}
}
}
declare module 'backbone.radio' {
import Backbone = require('backbone');
export = Backbone.Radio;
}
+1 -1
View File
@@ -316,7 +316,7 @@ declare namespace Backbone {
stop(): void;
route(route: string, callback: Function): number;
checkUrl(e?: any): void;
loadUrl(fragmentOverride: string): boolean;
loadUrl(fragmentOverride?: string): boolean;
navigate(fragment: string, options?: any): boolean;
static started: boolean;
options: any;
+3
View File
@@ -166,6 +166,9 @@ function test_collection() {
//////////
Backbone.history.start();
Backbone.History.started;
Backbone.history.loadUrl();
Backbone.history.loadUrl('12345');
namespace v1Changes {
namespace events {
+95
View File
@@ -0,0 +1,95 @@
/// <reference path="./bezier-js.d.ts" />
function test() {
var bezierjs: typeof BezierJs;
var bezier = new bezierjs.Bezier([1,2,3,4]);
var cap = new bezierjs.BezierCap([]);
var point: BezierJs.Point = { x: 0, y: 0 };
var utils = bezier.getUtils();
var line: BezierJs.Line = { p1: { x:0, y: 0}, p2: {x:1, y: 1}};
var abc: BezierJs.ABC = { A: null, B: null, C: null };
var arc: BezierJs.Arc = { e: 0, s: 0, x: 0, y: 0, r: 1 };
var bbox: BezierJs.BBox = bezier.bbox();
var closest: BezierJs.Closest = { mdist: 1, mpos: 0 };
var inflection: BezierJs.Inflection = { values: null, x: [0], y: [0], z:[0] };
var minmax: BezierJs.MinMax = { min: 0, max: 0 };
var offset: BezierJs.Offset = { x: 0, y: 0, c: point, n: point };
var pair: BezierJs.Pair = { left: bezier, right: bezier };
var poly: BezierJs.PolyBezier = bezier.outline(1);
var projection: BezierJs.Projection = { x: 0, y: 0, t: 9, d: 4 };
var shape: BezierJs.Shape = { startcap: cap, endcap: cap, forward: bezier, back: bezier, bbox: bbox };
var split: BezierJs.Split = { left: bezier, right: bezier, span: [point] };
bezier.arcs();
bezier.clockwise;
bezier.compute(.5);
bezier.computedirection();
bezier.curveintersects([bezier], [bezier]);
bezier.derivative(0);
bezier.get(1);
bezier.getLUT()[0].x;
bezier.hull(0);
bezier.inflections().values;
bezier.intersects(bezier);
bezier.length();
bezier.lineIntersects(line);
bezier.normal(0);
bezier.offset(1,2);
bezier.on(point, 0);
bezier.order = 5;
bezier.outlineshapes(1,3);
bezier.overlaps(bezier);
bezier.point(9);
bezier.project(point);
bezier.raise();
bezier.reduce();
bezier.scale(4);
bezier.selfintersects();
bezier.simple();
bezier.split(0, 1);
bezier.toSVG();
bezier.update();
cap.virtual = true;
poly.addCurve(bezier);
poly.bbox();
poly.curve(7);
poly.curves[0]._3d;
poly.length();
poly.offset(9).points[0].y;
poly.points[0];
utils.abcratio(0, 1);
utils.align([point], line);
utils.angle(point, point, point);
utils.approximately(5, 7, .001);
utils.arcfn(1, function(){});
utils.bboxoverlap(bbox, bbox);
utils.between(0, 0, 1);
utils.closest([point], point);
utils.copy({});
utils.dist(point, point);
utils.droots([9]);
utils.expandbox(bbox, bbox);
utils.findbbox([bezier]);
utils.getccenter(point, point, point);
utils.getminmax(bezier, 'x', [0]);
utils.length(function(){});
utils.lerp(1, point, point);
utils.lli(offset, offset);
utils.lli4(point, point, point, point);
utils.lli8(0, 0, 0, 0, 0, 0, 0, 0);
utils.makeline(point, point);
utils.makeshape(bezier, bezier);
utils.map(0, 0, 0, 0, 0);
utils.pairiteration(bezier, bezier);
utils.pointsToString([point]);
utils.projectionratio(0, 0);
utils.roots([point], line);
utils.round(.999, .001);
utils.shapeintersections(shape, bbox, shape, bbox);
}
+197
View File
@@ -0,0 +1,197 @@
// Type definitions for Bezier.js
// Project: https://github.com/Pomax/bezierjs
// Definitions by: Dan Marshall <https://github.com/danmarshall>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module BezierJs {
interface Point {
x: number;
y: number;
z?: number;
}
interface Projection extends Point {
t?: number;
d?: number;
}
interface Inflection {
x: number[];
y: number[];
z?: number[];
values: number[];
}
interface Offset extends Point {
c: Point;
n: Point;
}
interface Pair {
left: Bezier;
right: Bezier;
}
interface Split extends Pair {
span: Point[];
_t1?: number;
_t2?: number;
}
interface MinMax {
min: number;
mid?: number;
max: number;
size?: number;
}
interface BBox {
x: MinMax;
y: MinMax;
z?: MinMax;
}
interface Line {
p1: Point;
p2: Point;
}
interface Arc extends Point {
e: number;
r: number;
s: number;
}
interface Shape {
startcap: BezierCap;
forward: Bezier;
back: Bezier;
endcap: BezierCap;
bbox: BBox;
}
interface ABC {
A: Point;
B: Point;
C: Point;
}
interface Closest {
mdist: number;
mpos: number;
}
/**
* Bezier curve constructor. The constructor argument can be one of three things:
*
* 1. array/4 of {x:..., y:..., z:...}, z optional
* 2. numerical array/8 ordered x1,y1,x2,y2,x3,y3,x4,y4
* 3. numerical array/12 ordered x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4
*
*/
class Bezier {
clockwise: boolean;
private _linear;
_3d: boolean;
_t1: number;
_t2: number;
_lut: Point[];
dpoints: Point[][];
order: number;
points: Point[];
dims: string[];
dimlen: number;
constructor(points: Point[]);
constructor(coords: number[]);
constructor(n1: number, n2: number, n3: number, n4: number, n5: number, n6: number, n7: number, n8: number);
constructor(p1: Point, p2: Point, p3: Point, p4?: Point);
static fromSVG(svgString: string): Bezier;
static getABC(n: number, S: Point, B: Point, E: Point, t: number): ABC;
static quadraticFromPoints(p1: Point, p2: Point, p3: Point, t: number): Bezier;
static cubicFromPoints(S: Point, B: Point, E: Point, t: number, d1: number): Bezier;
static getUtils(): typeof utils;
getUtils(): typeof utils;
valueOf(): string;
toString(): string;
toSVG(): string;
update(): void;
computedirection(): void;
length(): number;
getLUT(steps?: number): Point[];
on(point: Point, error: number): number;
project(point: Point): Projection;
get(t: number): Point;
point(idx: number): Point;
compute(t: number): Point;
raise(): Bezier;
derivative(t: number): Point;
inflections(): number[];
normal(t: number): Point;
private __normal2(t);
private __normal3(t);
private __normal(t);
hull(t: number): Point[];
split(t1: number, t2?: number): Bezier | Split;
extrema(): Inflection;
bbox(): BBox;
overlaps(curve: Bezier): boolean;
offset(t: number, d?: number): Offset | Bezier[];
simple(): boolean;
reduce(): any[];
scale(d: Function): Bezier;
scale(d: number): Bezier;
outline(d1: number, d2?: number, d3?: number, d4?: number): PolyBezier;
outlineshapes(d1: number, d2: number): Shape[];
intersects(curve: Bezier): string[] | number[];
intersects(curve: Line): string[] | number[];
lineIntersects(line: Line): number[];
selfintersects(): string[];
curveintersects(c1: Bezier[], c2: Bezier[]): string[];
arcs(errorThreshold?: number): Arc[];
private _error(pc, np1, s, e);
private _iterate(errorThreshold, circles);
}
class BezierCap extends Bezier {
virtual: boolean;
}
}
declare module BezierJs.utils {
var Tvalues: number[];
var Cvalues: number[];
function arcfn(t: number, derivativeFn: Function): number;
function between(v: number, m: number, M: number): boolean;
function approximately(a: number, b: number, precision?: number): boolean;
function length(derivativeFn: Function): number;
function map(v: number, ds: number, de: number, ts: number, te: number): number;
function lerp(r: number, v1: Point, v2: Point): Point;
function pointToString(p: Point): string;
function pointsToString(points: Point[]): string;
function copy(obj: Object): any;
function angle(o: Point, v1: Point, v2: Point): number;
function round(v: number, d: number): number;
function dist(p1: Point, p2: Point): number;
function closest(LUT: Point[], point: Point): Closest;
function abcratio(t: number, n: number): number;
function projectionratio(t: number, n: number): number;
function lli8(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, x4: number, y4: number): Point;
function lli4(p1: Point, p2: Point, p3: Point, p4: Point): Point;
function lli(v1: Offset, v2: Offset): Point;
function makeline(p1: Point, p2: Point): Bezier;
function findbbox(sections: Bezier[]): BBox;
function shapeintersections(s1: Shape, bbox1: BBox, s2: Shape, bbox2: BBox): string[][] | number[][];
function makeshape(forward: Bezier, back: Bezier): Shape;
function getminmax(curve: Bezier, d: string, list: number[]): MinMax;
function align(points: Point[], line: Line): Point[];
function roots(points: Point[], line: Line): number[];
function droots(p: number[]): number[];
function inflections(points: Point[]): number[];
function bboxoverlap(b1: BBox, b2: BBox): boolean;
function expandbox(bbox: BBox, _bbox: BBox): void;
function pairiteration(c1: Bezier, c2: Bezier): string[];
function getccenter(p1: Point, p2: Point, p3: Point): Arc;
}
declare module BezierJs {
/**
* Poly Bezier
* @param {[type]} curves [description]
*/
class PolyBezier {
curves: Bezier[];
private _3d;
points: Point[];
constructor(curves: Bezier[]);
valueOf(): string;
toString(): string;
addCurve(curve: Bezier): void;
length(): number;
curve(idx: number): Bezier;
bbox(): BBox;
offset(d: number): PolyBezier;
}
}
File diff suppressed because it is too large Load Diff
+67 -23
View File
@@ -6,23 +6,25 @@
/// <reference path="../bluebird/bluebird.d.ts" />
/// <reference path='../lodash/lodash-3.10.d.ts' />
/// <reference path="../knex/knex.d.ts" />
/// <reference path="../create-error/create-error.d.ts" />
declare module 'bookshelf' {
import knex = require('knex');
import Promise = require('bluebird');
import Lodash = require('lodash');
import * as Knex from 'knex';
import * as Promise from 'bluebird';
import * as Lodash from 'lodash';
import * as createError from 'create-error';
interface Bookshelf extends Bookshelf.Events<any> {
VERSION : string;
knex : knex;
knex : Knex;
Model : typeof Bookshelf.Model;
Collection : typeof Bookshelf.Collection;
plugin(name: string | string[] | Function, options?: any) : Bookshelf;
transaction<T>(callback : (transaction : knex.Transaction) => T) : Promise<T>;
transaction<T>(callback : (transaction : Knex.Transaction) => T) : T;
}
function Bookshelf(knex : knex) : Bookshelf;
function Bookshelf(knex : Knex) : Bookshelf;
namespace Bookshelf {
abstract class Events<T> {
@@ -44,6 +46,13 @@ declare module 'bookshelf' {
/** If overriding, must use a getter instead of a plain property. */
idAttribute : string;
// See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/base/model.js#L178
// See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/base/model.js#L213
id : any;
// See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/base/model.js#L28
attributes : any;
constructor(attributes? : any, options? : ModelOptions);
clear() : T;
@@ -54,7 +63,7 @@ declare module 'bookshelf' {
has(attribute : string) : boolean;
hasChanged(attribute? : string) : boolean;
isNew() : boolean;
parse(response : any) : any;
parse(response : Object) : Object;
previousAttributes() : any;
previous(attribute : string) : any;
related<R extends Model<any>>(relation : string) : R | Collection<R>;
@@ -88,7 +97,7 @@ declare module 'bookshelf' {
belongsTo<R extends Model<any>>(target : {new(...args : any[]) : R}, foreignKey? : string) : R;
belongsToMany<R extends Model<any>>(target : {new(...args : any[]) : R}, table? : string, foreignKey? : string, otherKey? : string) : Collection<R>;
count(column? : string, options? : SyncOptions) : Promise<number>;
destroy(options? : SyncOptions) : Promise<T>;
destroy(options? : DestroyOptions) : Promise<T>;
fetch(options? : FetchOptions) : Promise<T>;
fetchAll(options? : FetchAllOptions) : Promise<Collection<T>>;
hasMany<R extends Model<any>>(target : {new(...args : any[]) : R}, foreignKey? : string) : Collection<R>;
@@ -98,20 +107,35 @@ declare module 'bookshelf' {
morphOne<R extends Model<any>>(target : {new(...args : any[]) : R}, name? : string, columnNames? : string[], morphValue? : string) : R;
morphTo(name : string, columnNames? : string[], ...target : typeof Model[]) : T;
morphTo(name : string, ...target : typeof Model[]) : T;
// Declaration order matters otherwise TypeScript gets confused between query() and query(...query: string[])
query() : Knex.QueryBuilder;
query(callback : (qb : Knex.QueryBuilder) => void) : T;
query(...query : string[]) : T;
query(query : {[key : string] : any}) : T;
query(callback : (qb : knex.QueryBuilder) => void) : T;
query() : knex.QueryBuilder;
refresh(options? : FetchOptions) : Promise<T>;
resetQuery() : T;
save(key? : string, val? : string, options? : SaveOptions) : Promise<T>;
save(key? : string, val? : any, options? : SaveOptions) : Promise<T>;
save(attrs? : {[key : string] : any}, options? : SaveOptions) : Promise<T>;
through<R extends Model<any>>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R | Collection<R>;
through<R extends Model<any>>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R;
where(properties : {[key : string] : any}) : T;
where(key : string, operatorOrValue : string|number|boolean, valueIfOperator? : string|number|boolean) : T;
// See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/errors.js
// See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/model.js#L1280
static NotFoundError: createError.Error<Error>;
static NoRowsUpdatedError: createError.Error<Error>;
static NoRowsDeletedError: createError.Error<Error>;
}
abstract class CollectionBase<T extends Model<any>> extends Events<T> {
// See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/base/collection.js#L573
length : number;
// See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/base/collection.js#L21
constructor(models? : T[], options? : CollectionOptions<T>);
add(models : T[]|{[key : string] : any}[], options? : CollectionAddOptions) : Collection<T>;
at(index : number) : T;
clone() : Collection<T>;
@@ -127,11 +151,11 @@ declare module 'bookshelf' {
remove(model : T, options? : EventOptions) : T;
remove(model : T[], options? : EventOptions) : T[];
reset(model : any[], options? : CollectionAddOptions) : T[];
serialize(options? : SerializeOptions) : any;
serialize(options? : SerializeOptions) : any[];
set(models : T[]|{[key : string] : any}[], options? : CollectionSetOptions) : Collection<T>;
shift(options? : EventOptions) : void;
slice(begin? : number, end? : number) : void;
toJSON(options? : SerializeOptions) : any;
toJSON(options? : SerializeOptions) : any[];
unshift(model : any, options? : CollectionAddOptions) : void;
where(match : {[key : string] : any}, firstOnly : boolean) : T|Collection<T>;
@@ -177,8 +201,13 @@ declare module 'bookshelf' {
keys() : string[];
last() : T;
lastIndexOf(value : any, fromIndex? : number) : number;
map(predicate? : Lodash.ListIterator<T, boolean>|Lodash.DictionaryIterator<T, boolean>|string, thisArg? : any) : T[];
map<R extends {}>(predicate? : R) : T[];
// See https://github.com/DefinitelyTyped/DefinitelyTyped/blob/1ec3d51/lodash/lodash-3.10.d.ts#L7119
// See https://github.com/Microsoft/TypeScript/blob/v1.8.10/lib/lib.core.es7.d.ts#L1122
map<U>(predicate? : Lodash.ListIterator<T, U>|string, thisArg? : any) : U[];
map<U>(predicate? : Lodash.DictionaryIterator<T, U>|string, thisArg? : any) : U[];
map<U>(predicate? : string) : U[];
max(predicate? : Lodash.ListIterator<T, boolean>|string, thisArg? : any) : T;
max<R extends {}>(predicate? : R) : T;
min(predicate? : Lodash.ListIterator<T, boolean>|string, thisArg? : any) : T;
@@ -208,20 +237,27 @@ declare module 'bookshelf' {
/** @deprecated should use `new` objects instead. */
static forge<T>(attributes? : any, options? : ModelOptions) : T;
attach(ids : any[], options? : SyncOptions) : Promise<Collection<T>>;
attach(ids : any|any[], options? : SyncOptions) : Promise<Collection<T>>;
count(column? : string, options? : SyncOptions) : Promise<number>;
create(model : {[key : string] : any}, options? : CollectionCreateOptions) : Promise<T>;
detach(ids : any[], options? : SyncOptions) : Promise<any>;
detach(options? : SyncOptions) : Promise<any>;
fetchOne(options? : CollectionFetchOneOptions) : Promise<T>;
load(relations : string|string[], options? : SyncOptions) : Promise<Collection<T>>;
// Declaration order matters otherwise TypeScript gets confused between query() and query(...query: string[])
query() : Knex.QueryBuilder;
query(callback : (qb : Knex.QueryBuilder) => void) : Collection<T>;
query(...query : string[]) : Collection<T>;
query(query : {[key : string] : any}) : Collection<T>;
query(callback : (qb : knex.QueryBuilder) => void) : Collection<T>;
query() : knex.QueryBuilder;
resetQuery() : Collection<T>;
through<R extends Model<any>>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R | Collection<R>;
through<R extends Model<any>>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : Collection<R>;
updatePivot(attributes : any, options? : PivotOptions) : Promise<number>;
withPivot(columns : string[]) : Collection<T>;
// See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/collection.js#L389
static EmptyError: createError.Error<Error>;
}
interface ModelOptions {
@@ -231,13 +267,17 @@ declare module 'bookshelf' {
}
interface LoadOptions extends SyncOptions {
withRelated: string|any|any[];
withRelated : (string|WithRelatedQuery)[];
}
interface FetchOptions extends SyncOptions {
require? : boolean;
columns? : string|string[];
withRelated? : string|any|any[];
withRelated? : (string|WithRelatedQuery)[];
}
interface WithRelatedQuery {
[index : string] : (query : Knex.QueryBuilder) => Knex.QueryBuilder;
}
interface FetchAllOptions extends SyncOptions {
@@ -251,6 +291,10 @@ declare module 'bookshelf' {
require? : boolean;
}
interface DestroyOptions extends SyncOptions {
require? : boolean;
}
interface SerializeOptions {
shallow? : boolean;
omitPivot? : boolean;
@@ -265,7 +309,7 @@ declare module 'bookshelf' {
}
interface SyncOptions {
transacting? : knex.Transaction;
transacting? : Knex.Transaction;
debug? : boolean;
}
+1 -1
View File
@@ -1,5 +1,5 @@
/// <reference path="./browser-sync.d.ts"/>
import browserSync = require("browser-sync");
import * as browserSync from "browser-sync";
(() => {
//make sure that the interfaces are correctly exposed
+19 -8
View File
@@ -8,10 +8,10 @@
/// <reference path="../micromatch/micromatch.d.ts" />
declare module "browser-sync" {
import chokidar = require("chokidar");
import fs = require("fs");
import http = require("http");
import mm = require("micromatch");
import * as chokidar from "chokidar";
import * as fs from "fs";
import * as http from "http";
import * as mm from "micromatch";
namespace browserSync {
interface Options {
@@ -23,14 +23,14 @@ declare module "browser-sync" {
* weinre.port - Default: 8080
* Note: requires at least version 2.0.0
*/
ui?: UIOptions;
ui?: UIOptions | boolean;
/**
* Browsersync can watch your files as you work. Changes you make will either be injected into the page (CSS
* & images) or will cause all browsers to do a full-page refresh. See anymatch for more information on glob
* patterns.
* Default: false
*/
files?: string | string[];
files?: string | (string | FileCallback)[];
/**
* File watching options that get passed along to Chokidar. Check their docs for available options
* Default: undefined
@@ -245,7 +245,7 @@ declare module "browser-sync" {
* Note: requires at least version 1.6.2
*/
socket?: SocketOptions;
middleware?: MiddlewareHandler | MiddlewareHandler[];
middleware?: MiddlewareHandler | PerRouteMiddleware | (MiddlewareHandler | PerRouteMiddleware)[];
}
interface Hash<T> {
@@ -261,6 +261,12 @@ declare module "browser-sync" {
};
}
interface FileCallback {
match?: string | string[];
fn: (event: string, file: string) => any;
options?: chokidar.WatchOptions;
}
interface ServerOptions {
/** set base directory */
baseDir?: string | string[];
@@ -274,7 +280,7 @@ declare module "browser-sync" {
*/
routes?: Hash<string>;
/** configure custom middleware */
middleware?: MiddlewareHandler[];
middleware?: (MiddlewareHandler | PerRouteMiddleware)[];
}
interface ProxyOptions {
@@ -289,6 +295,11 @@ declare module "browser-sync" {
(req: http.ServerRequest, res: http.ServerResponse, next: Function): any;
}
interface PerRouteMiddleware {
route: string;
handle: MiddlewareHandler;
}
interface GhostOptions {
clicks?: boolean;
scroll?: boolean;
+34
View File
@@ -0,0 +1,34 @@
/// <reference path="cachefactory.d.ts" />
CacheFactory.get('test');
CacheFactory.createCache('test', {
deleteOnExpire: 'aggressive',
recycleFreq: 60000
});
let testCache = CacheFactory.get('test');
testCache.put('testOne', {title: 'testOne', id: 1});
let item = testCache.get('testOne');
let profileCache = CacheFactory('profileCache', {
maxAge: 60 * 60 * 1000,
deleteOnExpire: 'aggressive'
});
let localStoragePolyfill = {
getItem: (key: string) => { return ""; },
setItem: (key: string, value: string) => { },
removeItem: (key: string) => { }
};
let myAwesomeCache = CacheFactory('myAwesomeCache', {
maxAge: 15 * 60 * 1000,
cacheFlushInterval: 60 * 60 * 1000,
deleteOnExpire: 'aggressive',
storageMode: 'localStorage',
storageImpl: localStoragePolyfill
});
+443
View File
@@ -0,0 +1,443 @@
// Type definitions for CacheFactory 1.4.0
// Project: https://github.com/jmdobry/CacheFactory
// Definitions by: Vaggelis Mparmpas <https://github.com/vag1830>, Daniel Massa <https://github.com/danielmassa>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module CacheFactory {
export interface IStoreImplementation {
getItem(key: string): string;
setItem(key: string, value: string): void;
removeItem(key: string): void;
}
export interface CacheGetOptions {
/*
* A callback function to be executed whenever an expired item is removed from a cache when the cache is in passive
* or aggressive mode. Will be passed the key and value of the expired item.
*
* Will be passed a third done argument if the cache is in passive mode. This allows you to synchronously access the
* key and value of the expired item when you make the cache#get(key[, options]) call that is the reason the expired
* item is being removed in the first place. Default: null.
*/
onExpire?(key: string, value: any): any;
}
export interface CachePutOptions {
/*
* The number of milliseconds until a newly inserted item expires. Default: Number.MAX_VALUE.
*/
maxAge?: number;
/*
* If inserting a promise into a cache, also insert the rejection value if the promise rejects. Default: false.
*/
storeOnReject?: boolean;
/*
* If inserting a promise into a cache, also insert the resolved value if the promise resolves. Default: false.
*/
storeOnResolve?: boolean;
created?: Date;
access?: Date;
expires?: Date;
}
export interface CacheTouchOptions extends CachePutOptions { }
export interface CacheOptions {
/*
* If set, remove all items from a cache on an interval after the given number of milliseconds. Default: null.
*/
cacheFlushInterval?: number;
/*
* Maximum number of items a cache can hold. Adding more items than the capacity will cause the cache to operate
* like an LRU cache, removing the least recently used items to stay under capacity. Default: Number.MAX_VALUE.
*/
capacity?: number;
/*
* Determines the behavior of a cache when an item expires. Default: none.
*
* Possible values:
*
* none - cache will do nothing when an item expires.
* passive - cache will do nothing when an item expires. Expired items will remain in the cache until requested,
* at which point they are removed, and undefined is returned.
* aggressive - cache will remove expired items as soon as they are discovered.
*/
deleteOnExpire?: string;
/*
* Determines whether a cache is disabled. Default: false.
*/
disabled?: boolean;
/*
* The number of milliseconds until a newly inserted item expires. Default: Number.MAX_VALUE.
*/
maxAge?: number;
/*
* Determines how often a cache will scan for expired items when in aggressive mode. Default: 1000 (milliseconds).
*/
recycleFreq?: number;
/*
* If inserting a promise into a cache, also insert the rejection value if the promise rejects. Default: false.
*/
storeOnReject?: boolean;
/*
* If inserting a promise into a cache, also insert the resolved value if the promise resolves. Default: false.
*/
storeOnResolve?: boolean;
/*
* Provide a custom storage medium, e.g. a polyfill for localStorage. Default: null.
*
* Must implement:
*
* setItem - Same API as localStorage.setItem(key, value)
* getItem - Same API as localStorage.getItem(key)
* removeItem - Same API as localStorage.removeItem(key)
*/
storageImpl?: IStoreImplementation;
/*
* Determines the storage medium used by a cache. Default: memory.
*
* Possible values:
*
* memory - cache will hold data in memory. Data is cleared when the page is refreshed.
* localStorage - cache will hold data in localStorage if available. Data is not cleared when the page is refreshed.
* sessionStorage - cache will hold data in sessionStorage if available. Data is not cleared when the page is refreshed.
*/
storageMode?: string;
/*
* Determines the namespace of a cache when storageMode is set to localStorage or sessionStorage. Make it a shorter
* string to save space. Default: angular-cache.caches.
*/
storagePrefix?: string;
/*
* A callback function to be executed whenever an expired item is removed from a cache when the cache is in passive
* or aggressive mode. Will be passed the key and value of the expired item.
*
* Will be passed a third done argument if the cache is in passive mode. This allows you to synchronously access the
* key and value of the expired item when you make the cache#get(key[, options]) call that is the reason the expired
* item is being removed in the first place. Default: null.
*/
onExpire?(key: string, value: any): any;
}
export interface ICache {
$$id: string;
/**
* Return the item with the given key.options, if provided, must be an object.
*
* If the cache is in passive mode, then options.onExpire can be a function that will be called with the key
* and value of the requested item if the requested item is expired, with the get call itself returning undefined.
* @param key
* @returns {}
*/
get<T>(key: string, options?: CacheGetOptions): T;
/**
* Insert the item with the given key and value into the cache.options, if provided, must be an object.
*
* If inserting a promise, options.storeOnReject determines whether to insert the rejection value if the promise
* rejects (overriding the default storeOnReject setting for the cache). If inserting a promise, options.storeOnResolve
* determines whether to insert the resolved value if the promise resolves (overriding the default storeOnResolve setting for the cache).
*
* @param key
* @param value
* @param options
*/
put<T>(key: string, value: T, options?: CachePutOptions): void;
/**
* Remove and return the item with the given key, if it is in the cache.
* @param key
* @returns {}
*/
remove<T>(key: string): T;
/**
* Remove all items in the cache.
*/
removeAll(): void;
/**
* Remove and return all expired items in the cache.
* @returns {}
*/
removeExpired(): { [key: string]: any };
/**
* Completely destroy this cache and its data.
* @returns {}
*/
destroy(): void;
/**
* Returns an object containing information about the cache.
*
* @param key
*/
info(): CacheInfo;
/**
* Returns an object containing information about the item with the given key, if the item is in the cache.
*
* @param key
*/
info(key: string): CacheItemInfo;
/**
* Return the keys of all items in the cache as an object.
* @returns {}
*/
keySet(): any;
/**
* Return the keys of all items in the cache as an array.
* @returns []
*/
keys(): Array<string>;
/**
* Enable the cache.
*/
enable(): void;
/**
* Disable the cache.
*/
disable(): void;
/**
* cache#touch() will "touch" all items in the cache.
* cache#touch(key) will "touch" the item with the given key.
*
* @param key
*/
touch(key?: string, options?: CacheTouchOptions): void;
/**
* Set the cacheFlushInterval for the cache.
* @param cacheFlushInterval
*/
setCacheFlushInterval(cacheFlushInterval: number): void;
/**
* Set the capacity for the cache.Setting this lower than the current item count will result in those items being removed.
* @param capacity
*/
setCapacity(capacity: number): void;
/**
* Set the deleteOnExpire for the cache.
* @param deleteOnExpire
*/
setDeleteOnExpire(deleteOnExpire: string): void;
/**
* Set the maxAge for the cache.
*/
setMaxAge(maxAge: number): void;
/**
* Set the onExpire for the cache.
* @param onExpire
*/
setOnExpire(onExpire: Function): void;
/**
* Set the recycleFreq for the cache.
* @param recycleFreq
*/
setRecycleFreq(recycleFreq: number): void;
/**
* Set the storageMode for the cache.This will move data from the current storage medium to the new one.
* @param storageMode
*/
setStorageMode(storageMode: string): void;
/**
* Set multiple options for the cache at a time.Setting strict to true will reset options for the cache
* that are not specifically set in the options hash to CacheFactoryProvider.defaults.
* @param options
*/
setOptions(options: CacheOptions, strict?: boolean): void;
/**
* Return the values of all items in the cache as an array.
* @returns Array<any>
*/
values(): Array<any>
}
export interface ICacheFactory {
BinaryHeap: IBinaryHeap;
utils: IUtils;
defaults: CacheOptions;
/**
* Create a cache. cache must not already exist. cacheId must be a string. options is an optional argument and must be an object.
* Any options you pass here will override any default options.
* @param cacheId
* @param options
* @returns ICache
*/
(cacheId: string, options?: CacheOptions): ICache;
/**
* Create a cache. cache must not already exist. cacheId must be a string. options is an optional argument and must be an object.
* Any options you pass here will override any default options.
* @param cacheId
* @param options
* @returns ICache
*/
createCache(cacheId: string, options?: CacheOptions): ICache;
/**
* Return the cache with the given cacheId.
* @param cacheId The id of the cache storage.
* @returns ICache
*/
get(cacheId: string, options?: CacheOptions): ICache;
/**
* Return an object of key- value pairs, the keys being cache ids and the values being the result of .info() being called on each cache.
* @returns CacheInfo
*/
info(): CacheInfo;
/**
* Return the ids of all registered caches as an object.
* @returns {[key: string]: ICache}
*/
keySet(): { [key: string]: ICache };
/**
* Return the ids of all registered caches as an array.
* @returns Array<string>
*/
keys(): Array<string>;
/**
* Destroy the cache with the given cacheId.
* @param cacheId
*/
destroy(cacheId: string): void;
/**
* Destroy all registered caches.
*/
destroyAll(): void;
/**
* Remove all data from all registered caches.
*/
clearAll(): void;
/**
* Enable all registered caches.
*/
enableAll(): void;
/**
* Disable all registered caches.
*/
disableAll(): void;
/**
* Call.touch() on all registered caches.
*/
touchAll(): void;
/**
* Call.removeExpired() on all registered caches.Returns a hash of any expired items, keyed by cache id.
* @returns {}
*/
removeExpiredFromAll(): Array<{ [key: string]: Array<{ [key: string]: any }> }>;
}
export interface IUtils {
isNumber(value: any): boolean;
isString(value: any): boolean;
isObject(value: any): boolean;
isFunction(value: any): boolean;
equals(a: any, b: any): boolean;
fromJson(value: any): {}
Promise: any;
}
export interface HeapItem {
key: string;
accessed: Date;
}
export interface IBinaryHeap {
(w?: IWeightFunc, c?: ICompareFunc): void;
heap: Array<HeapItem>;
weightFunc: IWeightFunc;
compareFunc: ICompareFunc;
push(node: HeapItem): void;
pop(): HeapItem;
peek(): HeapItem;
remove(node: HeapItem): HeapItem;
removeAll(): void;
size(): Number;
}
export interface IWeightFunc {
<T>(x: T): T;
}
export interface ICompareFunc {
<T>(x: T, y: T): boolean;
}
export interface CacheInfo {
size: Number;
caches: { [key: string]: any };
capacity: Number;
maxAge: Number;
deleteOnExpire: string;
onExpire: Function;
cacheFlushInterval: Number;
recycleFreq: Number;
storageMode: string;
storageImpl: IStoreImplementation;
disabled: boolean;
storagePrefix: string;
storeOnResolve: boolean;
storeOnReject: boolean;
}
export interface CacheItemInfo {
created: Date;
accessed: Date;
expires: Date;
isExpired: boolean;
}
}
declare var CacheFactory: CacheFactory.ICacheFactory;
declare module "cachefactory" {
export = CacheFactory;
}
+109
View File
@@ -1125,6 +1125,115 @@ declare namespace CodeMirror {
severity?: string;
to?: Position;
}
/**
* A function that calculates either a two-way or three-way merge between different sets of content.
*/
function MergeView(element: HTMLElement, options?: MergeView.MergeViewEditorConfiguration): MergeView.MergeViewEditor;
namespace MergeView {
/**
* Options available to MergeView.
*/
interface MergeViewEditorConfiguration extends EditorConfiguration {
/**
* Determines whether the original editor allows editing. Defaults to false.
*/
allowEditingOriginals?: boolean;
/**
* When true stretches of unchanged text will be collapsed. When a number is given, this indicates the amount
* of lines to leave visible around such stretches (which defaults to 2). Defaults to false.
*/
collapseIdentical?: boolean | number;
/**
* Sets the style used to connect changed chunks of code. By default, connectors are drawn. When this is set to "align",
* the smaller chunk is padded to align with the bigger chunk instead.
*/
connect?: string;
/**
* Callback for when stretches of unchanged text are collapsed.
*/
onCollapse?(mergeView: MergeViewEditor, line: number, size: number, mark: TextMarker): void;
/**
* Provides original version of the document to be shown on the right of the editor.
*/
orig: any;
/**
* Provides original version of the document to be shown on the left of the editor.
* To create a 2-way (as opposed to 3-way) merge view, provide only one of origLeft and origRight.
*/
origLeft?: any;
/**
* Provides original version of document to be shown on the right of the editor.
* To create a 2-way (as opposed to 3-way) merge view, provide only one of origLeft and origRight.
*/
origRight?: any;
/**
* Determines whether buttons that allow the user to revert changes are shown. Defaults to true.
*/
revertButtons?: boolean;
/**
* When true, changed pieces of text are highlighted. Defaults to true.
*/
showDifferences?: boolean;
}
interface MergeViewEditor extends Editor {
/**
* Returns the editor instance.
*/
editor(): Editor;
/**
* Left side of the merge view.
*/
left: DiffView;
leftChunks(): MergeViewDiffChunk;
leftOriginal(): Editor;
/**
* Right side of the merge view.
*/
right: DiffView;
rightChunks(): MergeViewDiffChunk;
rightOriginal(): Editor;
/**
* Sets whether or not the merge view should show the differences between the editor views.
*/
setShowDifferences(showDifferences: boolean): void;
}
/**
* Tracks changes in chunks from oroginal to new.
*/
interface MergeViewDiffChunk {
editFrom: number;
editTo: number;
origFrom: number;
origTo: number;
}
interface DiffView {
/**
* Forces the view to reload.
*/
forceUpdate(): (mode: string) => void;
/**
* Sets whether or not the merge view should show the differences between the editor views.
*/
setShowDifferences(showDifferences: boolean): void;
}
}
}
declare module "codemirror" {
+1 -1
View File
@@ -35,7 +35,7 @@ interface Cordova {
* @param action The action name to call on the native side (generally corresponds to the native class method).
* @param args An array of arguments to pass into the native environment.
*/
exec(success: () => any, fail: () => any, service: string, action: string, args?: string[]): void;
exec(success: () => any, fail: () => any, service: string, action: string, args?: any[]): void;
/** Gets the operating system name. */
platformId: string;
/** Gets Cordova framework version */
+1
View File
@@ -47,6 +47,7 @@ interface Connection {
*/
type: string;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var Connection: {
+2
View File
@@ -500,3 +500,5 @@ s = s.unescapeHTML();
// #############################################################################################
promiseOfVoid = delay(i);
console.log('core-js version number:', core.version);
+2
View File
@@ -1266,6 +1266,8 @@ interface String {
declare function delay(msec: number): Promise<void>;
declare namespace core {
var version: string;
namespace Reflect {
function apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any;
function construct(target: Function, argumentsList: ArrayLike<any>): any;
+14
View File
@@ -2706,3 +2706,17 @@ function testMultiUtcFormat() {
["%Y", function() { return true; }]
]);
}
function testEnterSizeEmpty() {
var selectionSize: number,
emptyStatus: boolean;
var newNodes = d3.selectAll('.test')
.data(['1', '2', '3'])
.enter();
emptyStatus = newNodes.empty();
selectionSize = newNodes.size();
}
Vendored
+3
View File
@@ -415,6 +415,9 @@ declare namespace d3 {
select(name: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection<Datum>;
call(func: (selection: Enter<Datum>, ...args: any[]) => any, ...args: any[]): Enter<Datum>;
empty(): boolean;
size(): number;
}
}
+1
View File
@@ -14,5 +14,6 @@ namespace DagreD3Tests {
const render = new dagreD3.render();
const svg = d3.select("svg");
render.arrows()["arrowType"] = (parent: JQuery, id: string, edge: Dagre.Edge, type: string) => {};
render(svg, graph);
}
+3
View File
@@ -5,6 +5,7 @@
/// <reference path="../d3/d3.d.ts"/>
/// <reference path="../dagre/dagre.d.ts"/>
/// <reference path="../jquery/jquery.d.ts" />
declare namespace Dagre {
@@ -23,6 +24,8 @@ declare namespace Dagre {
}
interface Render {
// see http://cpettitt.github.io/project/dagre-d3/latest/demo/user-defined.html for example usage
arrows (): { [arrowStyleName: string]: (parent: JQuery, id: string, edge: Dagre.Edge, type: string) => void };
new (): Render;
(selection: d3.Selection<any>, g: Dagre.Graph): void;
}
+59
View File
@@ -0,0 +1,59 @@
/// <reference path="daterangepicker.d.ts"/>
function tests_simple() {
$('#daterange').daterangepicker();
$('input[name="daterange"]').daterangepicker({
timePicker: true,
timePickerIncrement: 30,
locale: {
format: 'MM/DD/YYYY h:mm A'
}
});
$('#reportrange').daterangepicker({
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
}
});
$('input[name="datefilter"]').on('apply.daterangepicker', function (ev, picker) {
$(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY'));
});
$('input[name="datefilter"]').on('cancel.daterangepicker', function (ev, picker) {
$(this).val('');
});
$('#demo').daterangepicker({
"startDate": "05/06/2016",
"endDate": "05/12/2016"
}, function (start: string, end: string, label: string) {
console.log("New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')");
});
$(function() {
function cb(start: moment.Moment, end: moment.Moment) {
$('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
}
cb(moment().subtract(29, 'days'), moment());
$('#reportrange').daterangepicker({
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
}
}, cb);
});
}
+142
View File
@@ -0,0 +1,142 @@
// Type definitions for Date Range Picker v2.1.19
// Project: http://www.daterangepicker.com/
// Definitions by: SirMartin <https://github.com/SirMartin/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
/// <reference path="../moment/moment.d.ts"/>
interface JQuery {
daterangepicker(settings?: daterangepicker.Settings): JQuery;
daterangepicker(settings?: daterangepicker.Settings, callback?: (start?: string | Date | moment.Moment, end?: string | Date | moment.Moment, label?: string) => any): JQuery;
}
declare module daterangepicker {
interface DatepickerEventObject extends JQueryEventObject {
date: Date;
format(format?: string): string;
}
interface Settings {
/**
* The start of the initially selected date range
*/
startDate?: string | moment.Moment | Date;
/**
* The end of the initially selected date range
*/
endDate?: string | moment.Moment | Date;
/**
* The earliest date a user may select
*/
minDate?: string | moment.Moment | Date;
/**
* The latest date a user may select
*/
maxDate?: string | moment.Moment | Date;
/**
* The maximum span between the selected start and end dates. Can have any property you can add to a moment object (i.e. days, months)
*/
dateLimit?: any;
/**
* Show year and month select boxes above calendars to jump to a specific month and year
*/
showDropdowns?: boolean;
/**
* Show localized week numbers at the start of each week on the calendars
*/
showWeekNumbers?: boolean;
/**
* Show ISO week numbers at the start of each week on the calendars
*/
showISOWeekNumbers?: boolean;
/**
* Allow selection of dates with times, not just dates
*/
timePicker?: boolean;
/**
* Increment of the minutes selection list for times (i.e. 30 to allow only selection of times ending in 0 or 30)
*/
timePickerIncrement?: number;
/**
* Use 24- hour instead of 12- hour times, removing the AM/ PM selection.
*/
timePicker24Hour?: boolean;
/**
* Show seconds in the timePicker.
*/
timePickerSeconds?: boolean;
/**
* Set predefined date ranges the user can select from.Each key is the label for the range, and its value an array with two dates representing the bounds of the range.
*/
ranges?: any;
/**
* (string: 'left'/'right'/'center') Whether the picker appears aligned to the left, to the right, or centered under the HTML element it's attached to
*/
opens?: string;
/**
* (string: 'down' or 'up') Whether the picker appears below (default) or above the HTML element it's attached to
*/
drops?: string;
/**
* CSS class names that will be added to all buttons in the picker
*/
buttonClasses?: string[];
/**
* CSS class string that will be added to the apply button
*/
applyClass?: string;
/**
* CSS class string that will be added to the cancel button
*/
cancelClass?: string;
/**
* Allows you to provide localized strings for buttons and labels, customize the date display format, and change the first day of week for the calendars.
*/
locale?: Locale;
/**
* Show only a single calendar to choose one date, instead of a range picker with two calendars; the start and end dates provided to your callback will be the same single date chosen.
*/
singleDatePicker?: boolean;
/**
* Hide the apply and cancel buttons, and automatically apply a new date range as soon as two dates or a predefined range is selected.
*/
autoApply?: boolean;
/**
* When enabled, the two calendars displayed will always be for two sequential months (i.e.January and February), and both will be advanced when clicking the left or right arrows above the calendars.When disabled, the two calendars can be individually advanced and display any month/ year.
*/
linkedCalendars?: boolean;
/**
* jQuery selector of the parent element that the date range picker will be added to, if not provided this will be 'body'
*/
parentEl?: string;
/**
* A function that is passed each date in the two calendars before they are displayed, and may return true or false to indicate whether that date should be available for selection or not.
*/
isInvalidDate?(startDate: string | moment.Moment | Date, endDate?: string | moment.Moment | Date): boolean;
/**
* Indicates whether the date range picker should automatically update the value of an < input > element it's attached to at initialization and when the selected dates change.
*/
autoUpdateInput?: boolean;
/**
* Normally, if you use the ranges option to specify pre- defined date ranges, calendars for choosing a custom date range are not shown until the user clicks "Custom Range".When this option is set to true, the calendars for choosing a custom date range are always shown instead.
*/
alwaysShowCalendars?: boolean;
}
interface Locale {
/**
* Text for cancel label.
*/
cancelLabel?: string;
/**
* Text for apply label.
*/
applyLabel?: string;
/**
* Format of the date string. example: 'YYYY-MM-DD'
*/
format?: string;
}
}
+259
View File
@@ -0,0 +1,259 @@
// Test file for db.js Definition file
/// <reference path="db.js.d.ts" />
/* Type for use in tests */
interface Person {
firstName: string;
lastName: string;
answer: number;
group?: string;
}
/* Opening/creating a database and connection */
var server: DbJs.Server;
db.open({
server: 'my-app',
version: 1,
schema: {
people: {
key: { keyPath: 'id', autoIncrement: true },
indexes: {
firstName: {},
answer: { unique: true }
}
}
}
}).then(function (s: DbJs.Server) {
server = s;
});
var typedStore: DbJs.TypedObjectStoreServer<Person> = server['people'];
/* Basic server operations */
var idb = server.getIndexedDB();
server.close();
/* General server/store methods */
// Adding items
server.add<Person>('people', {
firstName: 'Aaron',
lastName: 'Powell',
answer: 42
}).then(function (item) { });
typedStore.add({
firstName: 'Aaron',
lastName: 'Powell',
answer: 42
}).then(function (item) { });
// Updating
server.update<Person>('people', {
firstName: 'Aaron',
lastName: 'Powell',
answer: 42
}).then(function (item) { });
typedStore.update({
firstName: 'Aaron',
lastName: 'Powell',
answer: 42
}).then(function (item) { });
// Removing
server.remove('people', 1).then(function (key) { });
typedStore.remove(1).then(function (key) { });
// Clearing
server.clear('people').then(function() { });
typedStore.clear().then(function() { });
// Fetching
// Getting a single object by key
server.get<Person>('people', 5).then(function (results) { });
typedStore.get(5).then(function (results) { });
// Getting a single object by key range
// With a MongoDB-style range:
server.get<Person>('people', {gte: 1, lt: 3})
.then(function (results) { });
typedStore.get({gte: 1, lt: 3})
.then(function (results) { });
// With an IDBKeyRange :
server.get<Person>('people', IDBKeyRange.bound(1, 3, false, true))
.then(function (results) { });
typedStore.get(IDBKeyRange.bound(1, 3, false, true))
.then(function (results) { });
// Querying
// Querying all objects
server.query<Person>('people')
.all()
.execute()
.then(function (results) { });
typedStore.query()
.all()
.execute()
.then(function (results) { });
// Querying using indexes
server.query<Person>('people', 'specialProperty')
.all()
.execute()
.then(function (results) { });
typedStore.query('specialProperty')
.all()
.execute()
.then(function (results) { });
// Filter with property and value
server.query<Person>('people')
.filter('firstName', 'Aaron')
.execute()
.then(function (results) { });
// Filter with function
server.query<Person>('people')
.filter(function(person: any) { return person.group === 'hipster'; })
.execute()
.then(function (results) { });
typedStore.query('people')
.filter(function(person) { return person.group === 'hipster'; })
.execute()
.then(function (results) { });
// Querying with ranges
server.query<Person>('people', 'firstName')
.only('Aaron')
.then(function (results) { });
server.query<Person>('people', 'answer')
.bound(30, 50)
.then(function (results) { });
server.query<Person>('people', 'firstName')
.range({ eq: 'Aaron' })
.then(function (results) { });
server.query<Person>('people', 'answer')
.range({ gte: 30, lte: 50 })
.then(function (results) { });
// Querying for distinct values
server.query<Person>('people', 'firstName')
.only('Aaron')
.distinct()
.execute()
.then(function (data) { });
// Limiting cursor range
server.query<Person>('people', 'firstName')
.all()
.limit(1, 3)
.execute()
.then(function (data) { });
// Cursor direction (desc)
server.query<Person>('people')
.all()
.desc()
.execute()
.then(function (results) { });
// Keys
server.query<Person>('people', 'firstName')
.only('Aaron')
.keys()
.execute()
.then(function (results) { });
// Mapping
server.query<Person>('people', 'age')
.lowerBound(30)
.map(function (value) {
return {
fullName: value.firstName + ' ' + value.lastName,
raw: value
};
})
.execute()
.then(function (data) { });
// Counting
server.query<Person>('people', 'firstName')
.only('Aaron')
.count()
.execute()
.then(function (results) { });
// With no arguments (count all items)
server.count().then(function (ct) { });
// With a key
server.count('myKey').then(function (ct) { });
// With a MongoDB-style range
server.count({gte: 1, lt: 3}).then(function (ct) { });
// With an IDBKeyRange range
server.count(IDBKeyRange.bound(1, 3, false, true)).then(function (ct) { });
// Atomic updates
server.query('users', 'last_mod')
.lowerBound(new Date().getTime() - 10000)
.modify({ last_mod: new Date().getTime() })
.execute()
.then(function(results) { });
server.query('users', 'changed')
.only(true)
.modify({ changed: false })
.execute()
.then(function () { });
server.query('users', 'name')
.lowerBound('marcy')
.modify({ views: function(profile: any) { return profile.views + 1; } })
.execute()
.then(function () { });
/* Other server methods */
// Closing connection
server.close();
// Retrieving the indexedDB.open result object in use
var storeNames = server.getIndexedDB().objectStoreNames;
// Server event handlers
server.addEventListener('abort', function (e: Event) { });
server.addEventListener('error', function (err: Event) { });
server.addEventListener('versionchange', function (e: Event) { });
server
.abort(function (e) { })
.error(function (err) { })
.versionchange(function (e) { });
// Deleting a database
db.delete('dbName').then(function () { }, function (err: Error) { });
db.delete('dbName').catch(function (err) { }).then(function (ev) { });
// Comparing two keys
db.cmp('key1', 'key2');
+154
View File
@@ -0,0 +1,154 @@
// Type definitions for db.js v0.14.0
// Project: https://github.com/aaronpowell/db.js/
// Definitions by: Chris Wrench <https://github.com/cgwrench>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module DbJs {
interface ErrorListener {
(err: Error): void;
}
interface OpenOptions {
server: string;
version: number;
schema?: any;
}
interface DbJsStatic {
open(options: OpenOptions): Promise<Server>;
delete(dbName: string): Promise<void>;
cmp(key1: any, key2: any): number;
}
// Query API
interface ExecutableQuery<T> {
execute(): Promise<T[]>;
}
interface CountableQuery<T> {
count(): ExecutableQuery<T>;
}
interface KeysQuery<T> extends DescableQuery<T>, ExecutableQuery<T>, FilterableQuery<T>, DistinctableQuery<T>, MappableQuery<T> {
}
interface KeyableQuery<T> {
keys(): KeysQuery<T>;
}
interface FilterQuery<T> extends KeyableQuery<T>, ExecutableQuery<T>, FilterableQuery<T>, DescableQuery<T>, DistinctableQuery<T>, ModifiableQuery<T>, LimitableQuery<T>, MappableQuery<T> {
}
interface FilterableQuery<T> {
filter<TValue>(index: string, value: TValue): FilterQuery<T>;
filter(filter: (value: T) => boolean): FilterQuery<T>;
}
interface DescQuery<T> extends KeyableQuery<T>, CountableQuery<T>, ExecutableQuery<T>, FilterableQuery<T>, DescableQuery<T>, ModifiableQuery<T>, MappableQuery<T> {
}
interface DescableQuery<T> {
desc(): DescQuery<T>;
}
interface DistinctQuery<T> extends KeyableQuery<T>, ExecutableQuery<T>, FilterableQuery<T>, DescableQuery<T>, ModifiableQuery<T>, MappableQuery<T>, CountableQuery<T> {
}
interface DistinctableQuery<T> {
distinct(filter?: (value: T) => boolean): DistinctQuery<T>;
}
interface ModifiableQuery<T> {
modify(filter: (value: T) => boolean): ExecutableQuery<T>;
modify(modifyObj: any): ExecutableQuery<T>;
}
interface LimitableQuery<T> {
limit(n: any, m: any): ExecutableQuery<T>;
}
interface MappableQuery<T> {
map<TMap>(fn: (value: T) => TMap): Query<TMap>;
}
interface Query<T> extends Promise<T>, KeyableQuery<T>, ExecutableQuery<T>, FilterableQuery<T>, DescableQuery<T>, DistinctableQuery<T>, ModifiableQuery<T>, LimitableQuery<T>, MappableQuery<T>, CountableQuery<T> {
}
interface IndexQuery<T> extends Query<T> {
only(...args: any[]): Query<T>;
bound(lowerBound: any, upperBound: any): Query<T>;
upperBound(upperBound: any): Query<T>;
lowerBound(lowerBound: any): Query<T>;
range(opts: any): Query<T>;
all(): Query<T>;
}
interface KeyValuePair<TKey, TValue> {
key: TKey;
item: TValue;
}
interface BaseServer {
getIndexedDB(): IDBDatabase;
close(): void;
}
interface IndexAccessibleServer {
[store: string]: TypedObjectStoreServer<any>;
}
interface ObjectStoreServer {
add<T>(table: string, entity: T): Promise<T>;
add<T>(table: string, ...entities: T[]): Promise<T[]>;
add<TKey, TValue>(table: string, entity: KeyValuePair<TKey, TValue>): Promise<KeyValuePair<TKey, TValue>>;
add<TKey, TValue>(table: string, ...entities: KeyValuePair<TKey, TValue>[]): Promise<KeyValuePair<TKey, TValue>[]>;
update<T>(table: string, entity: T): Promise<T>;
update<T>(table: string, ...entities: T[]): Promise<T[]>;
update<TKey, TValue>(table: string, entity: KeyValuePair<TKey, TValue>): Promise<KeyValuePair<TKey, TValue>>;
update<TKey, TValue>(table: string, ...entities: KeyValuePair<TKey, TValue>[]): Promise<KeyValuePair<TKey, TValue>[]>;
remove<TKey>(table: string, key: TKey): Promise<TKey>;
remove<TKey>(table: string, ...keys: TKey[]): Promise<TKey[]>;
clear(table: string): Promise<void>;
get<T>(table: string, key: any): Promise<T>;
query<T>(table: string): IndexQuery<T>;
query<T>(table: string, index: string): IndexQuery<T>;
count(): Promise<number>;
count(keyOrRange: any): Promise<number>;
count(table: string, key: any): Promise<number>;
addEventListener(type: 'abort', listener: (ev: Event) => any): void;
addEventListener(type: 'versionchange', listener: (ev: Event) => any): void;
addEventListener(type: 'error', listener: (err: Error) => any): void;
addEventListener(type: string, listener: EventListener | ErrorListener): void;
abort(listener: (ev: Event) => any): ObjectStoreServer;
versionchange(listener: (ev: Event) => any): ObjectStoreServer;
error(listener: (ev: Error) => any): ObjectStoreServer;
}
interface TypedObjectStoreServer<T> {
add(entity: T): Promise<T>;
add(...entities: T[]): Promise<T[]>;
add<TKey, TValue>(entity: KeyValuePair<TKey, TValue>): Promise<KeyValuePair<TKey, TValue>>;
add<TKey, TValue>(...entities: KeyValuePair<TKey, TValue>[]): Promise<KeyValuePair<TKey, TValue>[]>;
update(entity: T): Promise<T>;
update(...entities: T[]): Promise<T[]>;
update<TKey, TValue>(entity: KeyValuePair<TKey, TValue>): Promise<KeyValuePair<TKey, TValue>>;
update<TKey, TValue>(...entities: KeyValuePair<TKey, TValue>[]): Promise<KeyValuePair<TKey, TValue>[]>;
remove<TKey>(key: TKey): Promise<TKey>;
remove<TKey>(...keys: TKey[]): Promise<TKey[]>;
clear(): Promise<void>;
get(key: any): Promise<T>;
query(): IndexQuery<T>;
query(index: string): IndexQuery<T>;
count(key: any): Promise<number>;
}
type Server = DbJs.IndexAccessibleServer & DbJs.ObjectStoreServer & DbJs.BaseServer;
}
declare module "db" {
var db: DbJs.DbJsStatic;
export = db;
}
declare var db: DbJs.DbJsStatic;
+35
View File
@@ -0,0 +1,35 @@
/// <reference path="df-visible.d.ts" />
// https://github.com/customd/jquery-visible/blob/master/examples/demo-basic.html
$(function(){
// Add the spans to the container element.
$('#container dt').each(function(){ $(this).append('<span></span>'); });
// Trigger the
$('#detect').on('click',function(){
// Select the detection type.
var detectPartial = $('#detect_type').val() == 'partial';
// Loop over each container, and check if it's visible.
$('#container dt').each(function(){
// Is this element visible onscreen?
var visible = $(this).visible( detectPartial );
// Set the visible status into the span.
$(this).find('span').text( visible ? 'Onscreen' : 'Offscreen' ).toggleClass('visible',visible);
});
});
});
// https://www.customd.com/articles/13/checking-if-an-element-is-visible-on-screen-using-jquery
// Check both vertical, and horizontal at once
$('#element').visible(true, false, 'both');
// Check only horizontal
$('#element').visible(true, false, 'horizontal');
// Check only vertical
$('#element').visible(true, false, 'vertical');
+18
View File
@@ -0,0 +1,18 @@
// Type definitions for jquery-visible
// Project: https://github.com/customd/jquery-visible
// Definitions by: Andrey Lipatkin <https://github.com/Litee>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
type Direction = "horizontal" | "vertical" | "both";
interface JQuery {
/**
* Gets the value of a setting.
* @param details Which setting to consider.
* @param callback The callback parameter should be a function that looks like this:
* function(object details) {...};
*/
visible(partial?: boolean, hidden?: boolean, direction?: Direction): boolean;
}
+1 -1
View File
@@ -649,7 +649,7 @@ declare namespace dojo {
* @param url URL to request
* @param options OptionalOptions for the request.
*/
interface xhr { (url: String, options?: dojo.request.xhr.__Options): void }
interface xhr { (url: String, options?: dojo.request.xhr.__Options): dojo.request.__Promise }
interface xhr {
/**
* Send an HTTP DELETE request using XMLHttpRequest with the given URL and options.
+1
View File
@@ -4,6 +4,7 @@
$("span").dotdotdot({ ellipsis: ":::" });
$("span").dotdotdot({ wrap: "letter" });
$("span").dotdotdot({ fallbackToLetter: false });
$("span").dotdotdot({ after: "a.after" });
$("span").dotdotdot({ after: $("#after") });
$("span").dotdotdot({ watch: true });
$("span").dotdotdot({ height: 42 });
+1 -1
View File
@@ -31,7 +31,7 @@ declare namespace JQueryDotDotDot {
/** jQuery-selector for the element to keep and put after the ellipsis.
* Default: null
*/
after?: JQuery;
after?: string | JQuery;
/** Whether to update the ellipsis: true/'window'
* Default: false
+605
View File
@@ -0,0 +1,605 @@
/// <reference path="enzyme-1.2.0.d.ts" />
/// <reference path="../react/react.d.ts"/>
import { shallow, mount, render, describeWithDOM, spyLifecycle } from "enzyme";
import * as React from "react";
import {Component, ReactElement, HTMLAttributes} from "react";
import {ShallowWrapper, ReactWrapper, CheerioWrapper} from "enzyme";
// Help classes/interfaces
interface MyComponentProps {
propsProperty: any;
numberProp?: number;
}
interface StatelessProps {
stateless: any;
}
interface MyComponentState {
stateProperty: any;
}
class MyComponent extends Component<MyComponentProps, MyComponentState> {
setState(...args: any[]) {
}
}
const MyStatelessComponent = (props: StatelessProps) => <span />;
// API
namespace SpyLifecycleTest {
spyLifecycle(MyComponent);
}
// ShallowWrapper
namespace ShallowWrapperTest {
var shallowWrapper: ShallowWrapper<MyComponentProps, MyComponentState> =
shallow<MyComponentProps, MyComponentState>(<MyComponent propsProperty="value"/>);
var reactElement: ReactElement<any>,
objectVal: Object,
boolVal: Boolean,
stringVal: String,
elementWrapper: ShallowWrapper<HTMLAttributes, {}>
function test_find() {
elementWrapper = shallowWrapper.find('.selector');
shallowWrapper = shallowWrapper.find(MyComponent);
shallowWrapper.find(MyStatelessComponent).props().stateless;
shallowWrapper.find(MyStatelessComponent).shallow();
}
function test_findWhere() {
shallowWrapper =
shallowWrapper.findWhere((aShallowWrapper: ShallowWrapper<MyComponentProps, MyComponentState>) => true);
}
function test_filter() {
elementWrapper = shallowWrapper.filter('.selector');
shallowWrapper = shallowWrapper.filter(MyComponent).shallow();
}
function test_filterWhere() {
shallowWrapper =
shallowWrapper.filterWhere(wrapper => {
wrapper.props().propsProperty;
return true;
});
}
function test_contains() {
boolVal = shallowWrapper.contains(<div className="foo bar"/>);
}
function test_hasClass() {
boolVal = shallowWrapper.find('.my-button').hasClass('disabled');
}
function test_is() {
boolVal = shallowWrapper.is('.some-class');
}
function test_not() {
elementWrapper = shallowWrapper.find('.foo').not('.bar');
}
function test_children() {
shallowWrapper = shallowWrapper.children();
shallowWrapper.children(MyStatelessComponent).props().stateless;
}
function test_parents() {
shallowWrapper = shallowWrapper.parents();
}
function test_parent() {
shallowWrapper = shallowWrapper.parent();
}
function test_closest() {
elementWrapper = shallowWrapper.closest('.selector');
shallowWrapper = shallowWrapper.closest(MyComponent);
}
function test_shallow() {
shallowWrapper = shallowWrapper.shallow();
}
function test_unmount() {
shallowWrapper = shallowWrapper.unmount();
}
function test_render() {
var cheerioWrapper: CheerioWrapper<MyComponentProps, MyComponentState> = shallowWrapper.render();
}
function test_text() {
stringVal = shallowWrapper.text();
}
function test_html() {
stringVal = shallowWrapper.html();
}
function test_get() {
reactElement = shallowWrapper.get(1);
}
function test_at() {
shallowWrapper = shallowWrapper.at(1);
}
function test_first() {
shallowWrapper = shallowWrapper.first();
}
function test_last() {
shallowWrapper = shallowWrapper.last();
}
function test_state() {
shallowWrapper.state();
shallowWrapper.state('key');
}
function test_props() {
objectVal = shallowWrapper.props();
}
function test_prop() {
shallowWrapper.prop('key');
}
function test_simulate(...args: any[]) {
shallowWrapper.simulate('click');
shallowWrapper.simulate('click', args);
}
function test_setState() {
shallowWrapper = shallowWrapper.setState({stateProperty: 'state'});
}
function test_setProps() {
shallowWrapper = shallowWrapper.setProps({propsProperty: 'foo'});
}
function test_setContext() {
shallowWrapper = shallowWrapper.setContext({name: 'baz'});
}
function test_instance() {
var myComponent: MyComponent = shallowWrapper.instance();
}
function test_update() {
shallowWrapper = shallowWrapper.update();
}
function test_debug() {
stringVal = shallowWrapper.debug();
}
function test_type() {
var stringOrFunction: String|Function = shallowWrapper.type();
}
function test_forEach() {
shallowWrapper =
shallowWrapper.forEach(wrapper => wrapper.shallow().props().propsProperty);
}
function test_map() {
var arrayNumbers: Array<Number> =
shallowWrapper.map(wrapper => wrapper.props().numberProp);
}
function test_reduce() {
const total: number[] =
shallowWrapper.reduce(
(amount: number, n: ShallowWrapper<MyComponentProps, MyComponentState>) => amount + n.props().numberProp
);
}
function test_reduceRight() {
const total: number[] =
shallowWrapper.reduceRight<number>(
(amount: number, n: ShallowWrapper<MyComponentProps, MyComponentState>) => amount + n.prop('amount')
);
}
function test_some() {
boolVal = shallowWrapper.some('.selector');
boolVal = shallowWrapper.some(MyComponent);
}
function test_someWhere() {
boolVal = shallowWrapper.someWhere((aShallowWrapper: ShallowWrapper<MyComponentProps, MyComponentState>) => true);
}
function test_every() {
boolVal = shallowWrapper.every('.selector');
boolVal = shallowWrapper.every(MyComponent);
}
function test_everyWhere() {
boolVal = shallowWrapper.everyWhere((aShallowWrapper: ShallowWrapper<MyComponentProps, MyComponentState>) => true);
}
}
// ReactWrapper
namespace ReactWrapperTest {
var reactWrapper: ReactWrapper<MyComponentProps, MyComponentState> =
mount<MyComponentProps, MyComponentState>(<MyComponent propsProperty="value"/>);
var reactElement: ReactElement<any>,
objectVal: Object,
boolVal: Boolean,
stringVal: String,
elementWrapper: ReactWrapper<HTMLAttributes, {}>
function test_unmount() {
reactWrapper = reactWrapper.unmount();
}
function test_mount() {
reactWrapper = reactWrapper.mount();
}
function test_find() {
elementWrapper = reactWrapper.find('.selector');
reactWrapper = reactWrapper.find(MyComponent);
reactWrapper.find(MyStatelessComponent).props().stateless;
}
function test_findWhere() {
reactWrapper =
reactWrapper.findWhere((aReactWrapper: ReactWrapper<MyComponentProps, MyComponentState>) => true);
}
function test_filter() {
elementWrapper = reactWrapper.filter('.selector');
reactWrapper = reactWrapper.filter(MyComponent);
}
function test_filterWhere() {
reactWrapper =
reactWrapper.filterWhere(wrapper => {
wrapper.props().propsProperty;
return true;
});
}
function test_contains() {
boolVal = reactWrapper.contains(<div className="foo bar"/>);
}
function test_hasClass() {
boolVal = reactWrapper.find('.my-button').hasClass('disabled');
}
function test_is() {
boolVal = reactWrapper.is('.some-class');
}
function test_not() {
elementWrapper = reactWrapper.find('.foo').not('.bar');
}
function test_children() {
reactWrapper = reactWrapper.children();
}
function test_parents() {
reactWrapper = reactWrapper.parents();
}
function test_parent() {
reactWrapper = reactWrapper.parent();
}
function test_closest() {
elementWrapper = reactWrapper.closest('.selector');
reactWrapper = reactWrapper.closest(MyComponent);
}
function test_text() {
stringVal = reactWrapper.text();
}
function test_html() {
stringVal = reactWrapper.html();
}
function test_get() {
reactElement = reactWrapper.get(1);
}
function test_at() {
reactWrapper = reactWrapper.at(1);
}
function test_first() {
reactWrapper = reactWrapper.first();
}
function test_last() {
reactWrapper = reactWrapper.last();
}
function test_state() {
reactWrapper.state();
reactWrapper.state('key');
}
function test_props() {
objectVal = reactWrapper.props();
}
function test_prop() {
reactWrapper.prop('key');
}
function test_simulate(...args: any[]) {
reactWrapper.simulate('click');
reactWrapper.simulate('click', args);
}
function test_setState() {
reactWrapper = reactWrapper.setState({stateProperty: 'state'});
}
function test_setProps() {
reactWrapper = reactWrapper.setProps({propsProperty: 'foo'});
}
function test_setContext() {
reactWrapper = reactWrapper.setContext({name: 'baz'});
}
function test_instance() {
var myComponent: MyComponent = reactWrapper.instance();
}
function test_update() {
reactWrapper = reactWrapper.update();
}
function test_debug() {
stringVal = reactWrapper.debug();
}
function test_type() {
var stringOrFunction: String|Function = reactWrapper.type();
}
function test_forEach() {
reactWrapper =
reactWrapper.forEach(wrapper => wrapper.props().propsProperty);
}
function test_map() {
var arrayNumbers: Array<Number> =
reactWrapper.map(wrapper => wrapper.props().numberProp);
}
function test_reduce() {
const total: number[] =
reactWrapper.reduce<number>(
(amount: number, n: ReactWrapper<MyComponentProps, MyComponentState>) => amount + n.prop('amount')
);
}
function test_reduceRight() {
const total: number[] =
reactWrapper.reduceRight<number>(
(amount: number, n: ReactWrapper<MyComponentProps, MyComponentState>) => amount + n.prop('amount')
);
}
function test_some() {
boolVal = reactWrapper.some('.selector');
boolVal = reactWrapper.some(MyComponent);
}
function test_someWhere() {
boolVal = reactWrapper.someWhere((aReactWrapper: ReactWrapper<MyComponentProps, MyComponentState>) => true);
}
function test_every() {
boolVal = reactWrapper.every('.selector');
boolVal = reactWrapper.every(MyComponent);
}
function test_everyWhere() {
boolVal = reactWrapper.everyWhere((aReactWrapper: ReactWrapper<MyComponentProps, MyComponentState>) => true);
}
}
// CheerioWrapper
namespace CheerioWrapperTest {
var cheerioWrapper: CheerioWrapper<MyComponentProps, MyComponentState> =
render<MyComponentProps, MyComponentState>(<MyComponent propsProperty="value"/>);
var reactElement: ReactElement<any>,
objectVal: Object,
boolVal: Boolean,
stringVal: String,
elementWrapper: CheerioWrapper<HTMLAttributes, {}>
function test_find() {
elementWrapper = cheerioWrapper.find('.selector');
cheerioWrapper = cheerioWrapper.find(MyComponent);
cheerioWrapper.find(MyStatelessComponent).props().stateless;
}
function test_findWhere() {
cheerioWrapper =
cheerioWrapper.findWhere((aCheerioWrapper: CheerioWrapper<MyComponentProps, MyComponentState>) => true);
}
function test_filter() {
elementWrapper = cheerioWrapper.filter('.selector');
cheerioWrapper = cheerioWrapper.filter(MyComponent);
}
function test_filterWhere() {
cheerioWrapper =
cheerioWrapper.filterWhere(wrapper => {
wrapper.props().propsProperty;
return true;
});
}
function test_contains() {
boolVal = cheerioWrapper.contains(<div className="foo bar"/>);
}
function test_hasClass() {
boolVal = cheerioWrapper.find('.my-button').hasClass('disabled');
}
function test_is() {
boolVal = cheerioWrapper.is('.some-class');
}
function test_not() {
elementWrapper = cheerioWrapper.find('.foo').not('.bar');
}
function test_children() {
cheerioWrapper = cheerioWrapper.children();
}
function test_parents() {
cheerioWrapper = cheerioWrapper.parents();
}
function test_parent() {
cheerioWrapper = cheerioWrapper.parent();
}
function test_closest() {
elementWrapper = cheerioWrapper.closest('.selector');
cheerioWrapper = cheerioWrapper.closest(MyComponent);
}
function test_text() {
stringVal = cheerioWrapper.text();
}
function test_html() {
stringVal = cheerioWrapper.html();
}
function test_get() {
reactElement = cheerioWrapper.get(1);
}
function test_at() {
cheerioWrapper = cheerioWrapper.at(1);
}
function test_first() {
cheerioWrapper = cheerioWrapper.first();
}
function test_last() {
cheerioWrapper = cheerioWrapper.last();
}
function test_state() {
cheerioWrapper.state();
cheerioWrapper.state('key');
}
function test_props() {
objectVal = cheerioWrapper.props();
}
function test_prop() {
cheerioWrapper.prop('key');
}
function test_simulate(...args: any[]) {
cheerioWrapper.simulate('click');
cheerioWrapper.simulate('click', args);
}
function test_setState() {
cheerioWrapper = cheerioWrapper.setState({stateProperty: 'state'});
}
function test_setProps() {
cheerioWrapper = cheerioWrapper.setProps({propsProperty: 'foo'});
}
function test_setContext() {
cheerioWrapper = cheerioWrapper.setContext({name: 'baz'});
}
function test_instance() {
var myComponent: MyComponent = cheerioWrapper.instance();
}
function test_update() {
cheerioWrapper = cheerioWrapper.update();
}
function test_debug() {
stringVal = cheerioWrapper.debug();
}
function test_type() {
var stringOrFunction: String|Function = cheerioWrapper.type();
}
function test_forEach() {
cheerioWrapper =
cheerioWrapper.forEach((aCheerioWrapper: CheerioWrapper<MyComponentProps, MyComponentState>)=> {
});
}
function test_map() {
var arrayNumbers: Array<Number> =
cheerioWrapper.map(wrapper => wrapper.props().numberProp);
}
function test_reduce() {
const total: number[] =
cheerioWrapper.reduce<number>(
(amount: number, n: CheerioWrapper<MyComponentProps, MyComponentState>) => amount + n.prop('amount')
);
}
function test_reduceRight() {
const total: number[] =
cheerioWrapper.reduceRight<number>(
(amount: number, n: CheerioWrapper<MyComponentProps, MyComponentState>) => amount + n.prop('amount')
);
}
function test_some() {
boolVal = cheerioWrapper.some('.selector');
boolVal = cheerioWrapper.some(MyComponent);
}
function test_someWhere() {
boolVal = cheerioWrapper.someWhere((aCheerioWrapper: CheerioWrapper<MyComponentProps, MyComponentState>) => true);
}
function test_every() {
boolVal = cheerioWrapper.every('.selector');
boolVal = cheerioWrapper.every(MyComponent);
}
function test_everyWhere() {
boolVal = cheerioWrapper.everyWhere((aCheerioWrapper: CheerioWrapper<MyComponentProps, MyComponentState>) => true);
}
}
+473
View File
@@ -0,0 +1,473 @@
// Type definitions for Enzyme v1.2.0
// Project: https://github.com/airbnb/enzyme
// Definitions by: Marian Palkus <https://github.com/MarianPalkus>, Cap3 <http://www.cap3.de>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
///<reference path="../react/react.d.ts" />
declare module "enzyme" {
import {ReactElement, Component, StatelessComponent, ComponentClass, HTMLAttributes} from "react";
export class ElementClass extends Component<any, any> {
}
/**
* Many methods in Enzyme's API accept a selector as an argument. Selectors in Enzyme can fall into one of the
* following three categories:
*
* 1. A Valid CSS Selector
* 2. A React Component Constructor
* 3. A React Component's displayName
*/
export type EnzymeSelector = String | typeof ElementClass;
interface CommonWrapper<P, S> {
/**
* Find every node in the render tree that matches the provided selector.
* @param selector The selector to match.
*/
find<P2>(component: ComponentClass<P2>): CommonWrapper<P2, any>;
find<P2>(statelessComponent: StatelessComponent<P2>): CommonWrapper<P2, {}>;
find(selector: string): CommonWrapper<HTMLAttributes, any>;
/**
* Finds every node in the render tree that returns true for the provided predicate function.
* @param predicate
*/
findWhere(predicate: (wrapper: CommonWrapper<any, any>) => Boolean): CommonWrapper<any, any>;
/**
* Removes nodes in the current wrapper that do not match the provided selector.
* @param selector The selector to match.
*/
filter<P2>(component: ComponentClass<P2>): CommonWrapper<P2, any>;
filter<P2>(statelessComponent: StatelessComponent<P2>): CommonWrapper<P2, {}>;
filter(selector: string): CommonWrapper<HTMLAttributes, any>;
/**
* Returns a new wrapper with only the nodes of the current wrapper that, when passed into the provided predicate function, return true.
* @param predicate
*/
filterWhere(predicate: (wrapper: this) => Boolean): this;
/**
* Returns whether or not the current wrapper has a node anywhere in it's render tree that looks like the one passed in.
* @param node
*/
contains(node: ReactElement<any>): Boolean;
/**
* Returns whether or not the current node has a className prop including the passed in class name.
* @param className
*/
hasClass(className: String): Boolean;
/**
* Returns whether or not the current node matches a provided selector.
* @param selector
*/
is(selector: EnzymeSelector): Boolean;
/**
* Returns a new wrapper with only the nodes of the current wrapper that don't match the provided selector.
* This method is effectively the negation or inverse of filter.
* @param selector
*/
not(selector: EnzymeSelector): this;
/**
* Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector
* can be provided and it will filter the children by this selector.
* @param [selector]
*/
children<P2>(component: ComponentClass<P2>): CommonWrapper<P2, any>;
children<P2>(statelessComponent: StatelessComponent<P2>): CommonWrapper<P2, {}>;
children(selector: string): CommonWrapper<HTMLAttributes, any>;
children(): CommonWrapper<any, any>;
/**
* Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the
* current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector.
*
* Note: can only be called on a wrapper of a single node.
* @param [selector]
*/
parents<P2>(component: ComponentClass<P2>): CommonWrapper<P2, any>;
parents<P2>(statelessComponent: StatelessComponent<P2>): CommonWrapper<P2, {}>;
parents(selector: string): CommonWrapper<HTMLAttributes, any>;
parents(): CommonWrapper<any, any>;
/**
* Returns a wrapper with the direct parent of the node in the current wrapper.
*/
parent(): CommonWrapper<any, any>;
/**
* Returns a wrapper of the first element that matches the selector by traversing up through the current node's
* ancestors in the tree, starting with itself.
*
* Note: can only be called on a wrapper of a single node.
* @param selector
*/
closest<P2>(component: ComponentClass<P2>): CommonWrapper<P2, any>;
closest<P2>(statelessComponent: StatelessComponent<P2>): CommonWrapper<P2, {}>;
closest(selector: string): CommonWrapper<HTMLAttributes, any>;
/**
* Returns a string of the rendered text of the current render tree. This function should be looked at with
* skepticism if being used to test what the actual HTML output of the component will be. If that is what you
* would like to test, use enzyme's render function instead.
*
* Note: can only be called on a wrapper of a single node.
*/
text(): String;
/**
* Returns a string of the rendered HTML markup of the current render tree.
*
* Note: can only be called on a wrapper of a single node.
*/
html(): String;
/**
* Returns the node at a given index of the current wrapper.
* @param index
*/
get(index: number): ReactElement<any>;
/**
* Returns a wrapper around the node at a given index of the current wrapper.
* @param index
*/
at(index: number): this;
/**
* Reduce the set of matched nodes to the first in the set.
*/
first(): this;
/**
* Reduce the set of matched nodes to the last in the set.
*/
last(): this;
/**
* Returns the state hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value.
* @param [key]
*/
state(key?: String): any;
/**
* Returns the props hash for the current node of the wrapper.
*
* NOTE: can only be called on a wrapper of a single node.
*/
props(): P;
/**
* Returns the prop value for the node of the current wrapper with the provided key.
*
* NOTE: can only be called on a wrapper of a single node.
* @param key
*/
prop(key: String): any;
/**
* Simulate events.
* Returns itself.
* @param event
* @param args?
*/
simulate(event: string, ...args: any[]): this;
/**
* A method to invoke setState() on the root component instance similar to how you might in the definition of
* the component, and re-renders. This method is useful for testing your component in hard to achieve states,
* however should be used sparingly. If possible, you should utilize your component's external API in order to
* get it into whatever state you want to test, in order to be as accurate of a test as possible. This is not
* always practical, however.
* Returns itself.
*
* NOTE: can only be called on a wrapper instance that is also the root instance.
* @param state
*/
setState(state: S): this;
/**
* A method that sets the props of the root component, and re-renders. Useful for when you are wanting to test
* how the component behaves over time with changing props. Calling this, for instance, will call the
* componentWillReceiveProps lifecycle method.
*
* Similar to setState, this method accepts a props object and will merge it in with the already existing props.
* Returns itself.
*
* NOTE: can only be called on a wrapper instance that is also the root instance.
* @param state
*/
setProps(props: P): this;
/**
* A method that sets the context of the root component, and re-renders. Useful for when you are wanting to
* test how the component behaves over time with changing contexts.
* Returns itself.
*
* NOTE: can only be called on a wrapper instance that is also the root instance.
* @param state
*/
setContext(context: Object): this;
/**
* Gets the instance of the component being rendered as the root node passed into shallow().
*
* NOTE: can only be called on a wrapper instance that is also the root instance.
*/
instance(): Component<P, S>;
/**
* Forces a re-render. Useful to run before checking the render output if something external may be updating
* the state of the component somewhere.
* Returns itself.
*
* NOTE: can only be called on a wrapper instance that is also the root instance.
*/
update(): this;
/**
* Returns an html-like string of the wrapper for debugging purposes. Useful to print out to the console when
* tests are not passing when you expect them to.
*/
debug(): String;
/**
* Returns the type of the current node of this wrapper. If it's a composite component, this will be the
* component constructor. If it's native DOM node, it will be a string of the tag name.
*
* Note: can only be called on a wrapper of a single node.
*/
type(): String | Function;
/**
* Iterates through each node of the current wrapper and executes the provided function with a wrapper around
* the corresponding node passed in as the first argument.
*
* Returns itself.
* @param fn A callback to be run for every node in the collection. Should expect a ShallowWrapper as the first
* argument, and will be run with a context of the original instance.
*/
forEach(fn: (wrapper: this) => any): this;
/**
* Maps the current array of nodes to another array. Each node is passed in as a ShallowWrapper to the map
* function.
* Returns an array of the returned values from the mapping function..
* @param fn A mapping function to be run for every node in the collection, the results of which will be mapped
* to the returned array. Should expect a ShallowWrapper as the first argument, and will be run
* with a context of the original instance.
*/
map<V>(fn: (wrapper: this) => V): V[];
/**
* Applies the provided reducing function to every node in the wrapper to reduce to a single value. Each node
* is passed in as a ShallowWrapper, and is processed from left to right.
* @param fn
* @param initialValue
*/
reduce<R>(fn: (prevVal: R, wrapper: this, index: number) => R, initialValue?: R): R[];
/**
* Applies the provided reducing function to every node in the wrapper to reduce to a single value.
* Each node is passed in as a ShallowWrapper, and is processed from right to left.
* @param fn
* @param initialValue
*/
reduceRight<R>(fn: (prevVal: R, wrapper: this, index: number) => R, initialValue?: R): R[];
/**
* Returns whether or not any of the nodes in the wrapper match the provided selector.
* @param selector
*/
some(selector: EnzymeSelector): Boolean;
/**
* Returns whether or not any of the nodes in the wrapper pass the provided predicate function.
* @param fn
*/
someWhere(fn: (wrapper: this) => Boolean): Boolean;
/**
* Returns whether or not all of the nodes in the wrapper match the provided selector.
* @param selector
*/
every(selector: EnzymeSelector): Boolean;
/**
* Returns whether or not any of the nodes in the wrapper pass the provided predicate function.
* @param fn
*/
everyWhere(fn: (wrapper: this) => Boolean): Boolean;
length: number;
}
export interface ShallowWrapper<P, S> extends CommonWrapper<P, S> {
shallow(): ShallowWrapper<P, S>;
render(): CheerioWrapper<P, S>;
unmount(): ShallowWrapper<any, any>;
/**
* Find every node in the render tree that matches the provided selector.
* @param selector The selector to match.
*/
find<P2>(component: ComponentClass<P2>): ShallowWrapper<P2, any>;
find<P2>(statelessComponent: (props: P2) => JSX.Element): ShallowWrapper<P2, {}>;
find(selector: string): ShallowWrapper<HTMLAttributes, any>;
/**
* Removes nodes in the current wrapper that do not match the provided selector.
* @param selector The selector to match.
*/
filter<P2>(component: ComponentClass<P2>): ShallowWrapper<P2, any>;
filter<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, {}>;
filter(selector: string): ShallowWrapper<HTMLAttributes, any>;
/**
* Finds every node in the render tree that returns true for the provided predicate function.
* @param predicate
*/
findWhere(predicate: (wrapper: CommonWrapper<any, any>) => Boolean): ShallowWrapper<any, any>;
/**
* Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector
* can be provided and it will filter the children by this selector.
* @param [selector]
*/
children<P2>(component: ComponentClass<P2>): ShallowWrapper<P2, any>;
children<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, {}>;
children(selector: string): ShallowWrapper<HTMLAttributes, any>;
children(): ShallowWrapper<any, any>;
/**
* Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the
* current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector.
*
* Note: can only be called on a wrapper of a single node.
* @param [selector]
*/
parents<P2>(component: ComponentClass<P2>): ShallowWrapper<P2, any>;
parents<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, {}>;
parents(selector: string): ShallowWrapper<HTMLAttributes, any>;
parents(): ShallowWrapper<any, any>;
/**
* Returns a wrapper of the first element that matches the selector by traversing up through the current node's
* ancestors in the tree, starting with itself.
*
* Note: can only be called on a wrapper of a single node.
* @param selector
*/
closest<P2>(component: ComponentClass<P2>): ShallowWrapper<P2, any>;
closest<P2>(statelessComponent: StatelessComponent<P2>): ShallowWrapper<P2, {}>;
closest(selector: string): ShallowWrapper<HTMLAttributes, any>;
/**
* Returns a wrapper with the direct parent of the node in the current wrapper.
*/
parent(): ShallowWrapper<any, any>;
}
export interface ReactWrapper<P, S> extends CommonWrapper<P, S> {
unmount(): ReactWrapper<any, any>;
mount(): ReactWrapper<any, any>;
/**
* Find every node in the render tree that matches the provided selector.
* @param selector The selector to match.
*/
find<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
find<P2>(statelessComponent: (props: P2) => JSX.Element): ReactWrapper<P2, {}>;
find(selector: string): ReactWrapper<HTMLAttributes, any>;
/**
* Finds every node in the render tree that returns true for the provided predicate function.
* @param predicate
*/
findWhere(predicate: (wrapper: CommonWrapper<any, any>) => Boolean): ReactWrapper<any, any>;
/**
* Removes nodes in the current wrapper that do not match the provided selector.
* @param selector The selector to match.
*/
filter<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
filter<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, {}>;
filter(selector: string): ReactWrapper<HTMLAttributes, any>;
/**
* Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector
* can be provided and it will filter the children by this selector.
* @param [selector]
*/
children<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
children<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, {}>;
children(selector: string): ReactWrapper<HTMLAttributes, any>;
children(): ReactWrapper<any, any>;
/**
* Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the
* current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector.
*
* Note: can only be called on a wrapper of a single node.
* @param [selector]
*/
parents<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
parents<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, {}>;
parents(selector: string): ReactWrapper<HTMLAttributes, any>;
parents(): ReactWrapper<any, any>;
/**
* Returns a wrapper of the first element that matches the selector by traversing up through the current node's
* ancestors in the tree, starting with itself.
*
* Note: can only be called on a wrapper of a single node.
* @param selector
*/
closest<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
closest<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, {}>;
closest(selector: string): ReactWrapper<HTMLAttributes, any>;
/**
* Returns a wrapper with the direct parent of the node in the current wrapper.
*/
parent(): ReactWrapper<any, any>;
}
export interface CheerioWrapper<P, S> extends CommonWrapper<P, S> {
}
/**
* Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that
* your tests aren't indirectly asserting on behavior of child components.
* @param node
* @param [options]
*/
export function shallow<P, S>(node: ReactElement<P>, options?: any): ShallowWrapper<P, S>;
/**
* Mounts and renders a react component into the document and provides a testing wrapper around it.
* @param node
* @param [options]
*/
export function mount<P, S>(node: ReactElement<P>, options?: any): ReactWrapper<P, S>;
/**
* Render react components to static HTML and analyze the resulting HTML structure.
* @param node
* @param [options]
*/
export function render<P, S>(node: ReactElement<P>, options?: any): CheerioWrapper<P, S>;
export function describeWithDOM(description: String, fn: Function): void;
export function spyLifecycle(component: typeof Component): void;
}
+191 -14
View File
@@ -73,6 +73,26 @@ namespace ShallowWrapperTest {
boolVal = shallowWrapper.contains(<div className="foo bar"/>);
}
function test_containsMatchingElement() {
boolVal = shallowWrapper.contains(<div className="foo bar"/>);
}
function test_containsAllMatchingElements() {
boolVal = shallowWrapper.containsAllMatchingElements([<div className="foo bar"/>]);
}
function test_containsAnyMatchingElement() {
boolVal = shallowWrapper.containsAnyMatchingElements([<div className="foo bar"/>]);
}
function test_equals() {
boolVal = shallowWrapper.equals(<div className="foo bar"/>);
}
function test_matchesElement() {
boolVal = shallowWrapper.matchesElement(<div className="foo bar"/>);
}
function test_hasClass() {
boolVal = shallowWrapper.find('.my-button').hasClass('disabled');
}
@@ -90,6 +110,20 @@ namespace ShallowWrapperTest {
shallowWrapper.children(MyStatelessComponent).props().stateless;
}
function test_childAt() {
const childWrapper: ShallowWrapper<any, any> = shallowWrapper.childAt(0);
interface TmpType1 {
foo: any
}
interface TmpType2 {
bar: any
}
const childWrapper2: ShallowWrapper<TmpType1, TmpType2> = shallowWrapper.childAt<TmpType1, TmpType2>(0);
}
function test_parents() {
shallowWrapper = shallowWrapper.parents();
}
@@ -107,6 +141,10 @@ namespace ShallowWrapperTest {
shallowWrapper = shallowWrapper.shallow();
}
function test_unmount() {
shallowWrapper = shallowWrapper.unmount();
}
function test_render() {
var cheerioWrapper: CheerioWrapper<MyComponentProps, MyComponentState> = shallowWrapper.render();
}
@@ -139,6 +177,13 @@ namespace ShallowWrapperTest {
function test_state() {
shallowWrapper.state();
shallowWrapper.state('key');
const tmp: String = shallowWrapper.state<String>('key');
}
function test_context() {
shallowWrapper.context();
shallowWrapper.context('key');
const tmp: String = shallowWrapper.context<String>('key');
}
function test_props() {
@@ -147,8 +192,12 @@ namespace ShallowWrapperTest {
function test_prop() {
shallowWrapper.prop('key');
const tmp: String = shallowWrapper.prop<String>('key');
}
function test_key() {
stringVal = shallowWrapper.key();
}
function test_simulate(...args: any[]) {
shallowWrapper.simulate('click');
@@ -156,15 +205,15 @@ namespace ShallowWrapperTest {
}
function test_setState() {
shallowWrapper = shallowWrapper.setState({stateProperty: 'state'});
shallowWrapper = shallowWrapper.setState({ stateProperty: 'state' });
}
function test_setProps() {
shallowWrapper = shallowWrapper.setProps({propsProperty: 'foo'});
shallowWrapper = shallowWrapper.setProps({ propsProperty: 'foo' });
}
function test_setContext() {
shallowWrapper = shallowWrapper.setContext({name: 'baz'});
shallowWrapper = shallowWrapper.setContext({ name: 'baz' });
}
function test_instance() {
@@ -180,7 +229,11 @@ namespace ShallowWrapperTest {
}
function test_type() {
var stringOrFunction: String|Function = shallowWrapper.type();
var stringOrFunction: String | Function = shallowWrapper.type();
}
function test_name() {
var str: String = shallowWrapper.name();
}
function test_forEach() {
@@ -238,6 +291,32 @@ namespace ReactWrapperTest {
stringVal: String,
elementWrapper: ReactWrapper<HTMLAttributes, {}>
function test_unmount() {
reactWrapper = reactWrapper.unmount();
}
function test_mount() {
reactWrapper = reactWrapper.mount();
}
function test_ref() {
reactWrapper = reactWrapper.ref('refName');
interface TmpType1 {
foo: string
}
interface TmpType2 {
bar: string
}
const tmp: ReactWrapper<TmpType1, TmpType2> = reactWrapper.ref<TmpType1, TmpType2>('refName');
}
function test_detach() {
reactWrapper.detach();
}
function test_find() {
elementWrapper = reactWrapper.find('.selector');
reactWrapper = reactWrapper.find(MyComponent);
@@ -266,6 +345,26 @@ namespace ReactWrapperTest {
boolVal = reactWrapper.contains(<div className="foo bar"/>);
}
function test_containsMatchingElement() {
boolVal = reactWrapper.contains(<div className="foo bar"/>);
}
function test_containsAllMatchingElements() {
boolVal = reactWrapper.containsAllMatchingElements([<div className="foo bar"/>]);
}
function test_containsAnyMatchingElement() {
boolVal = reactWrapper.containsAnyMatchingElements([<div className="foo bar"/>]);
}
function test_equals() {
boolVal = reactWrapper.equals(<div className="foo bar"/>);
}
function test_matchesElement() {
boolVal = reactWrapper.matchesElement(<div className="foo bar"/>);
}
function test_hasClass() {
boolVal = reactWrapper.find('.my-button').hasClass('disabled');
}
@@ -282,6 +381,20 @@ namespace ReactWrapperTest {
reactWrapper = reactWrapper.children();
}
function test_childAt() {
const childWrapper: ReactWrapper<any, any> = reactWrapper.childAt(0);
interface TmpType1 {
foo: any
}
interface TmpType2 {
bar: any
}
const childWrapper2: ReactWrapper<TmpType1, TmpType2> = reactWrapper.childAt<TmpType1, TmpType2>(0);
}
function test_parents() {
reactWrapper = reactWrapper.parents();
}
@@ -322,6 +435,13 @@ namespace ReactWrapperTest {
function test_state() {
reactWrapper.state();
reactWrapper.state('key');
const tmp: String = reactWrapper.state<String>('key');
}
function test_context() {
reactWrapper.context();
reactWrapper.context('key');
const tmp: String = reactWrapper.context<String>('key');
}
function test_props() {
@@ -330,8 +450,12 @@ namespace ReactWrapperTest {
function test_prop() {
reactWrapper.prop('key');
const tmp: String = reactWrapper.prop<String>('key');
}
function test_key() {
stringVal = reactWrapper.key();
}
function test_simulate(...args: any[]) {
reactWrapper.simulate('click');
@@ -339,15 +463,15 @@ namespace ReactWrapperTest {
}
function test_setState() {
reactWrapper = reactWrapper.setState({stateProperty: 'state'});
reactWrapper = reactWrapper.setState({ stateProperty: 'state' });
}
function test_setProps() {
reactWrapper = reactWrapper.setProps({propsProperty: 'foo'});
reactWrapper = reactWrapper.setProps({ propsProperty: 'foo' });
}
function test_setContext() {
reactWrapper = reactWrapper.setContext({name: 'baz'});
reactWrapper = reactWrapper.setContext({ name: 'baz' });
}
function test_instance() {
@@ -363,7 +487,11 @@ namespace ReactWrapperTest {
}
function test_type() {
var stringOrFunction: String|Function = reactWrapper.type();
var stringOrFunction: String | Function = reactWrapper.type();
}
function test_name() {
var str: String = reactWrapper.name();
}
function test_forEach() {
@@ -418,7 +546,7 @@ namespace CheerioWrapperTest {
objectVal: Object,
boolVal: Boolean,
stringVal: String,
elementWrapper: ReactWrapper<HTMLAttributes, {}>
elementWrapper: CheerioWrapper<HTMLAttributes, {}>
function test_find() {
elementWrapper = cheerioWrapper.find('.selector');
@@ -448,6 +576,26 @@ namespace CheerioWrapperTest {
boolVal = cheerioWrapper.contains(<div className="foo bar"/>);
}
function test_containsMatchingElement() {
boolVal = cheerioWrapper.contains(<div className="foo bar"/>);
}
function test_containsAllMatchingElements() {
boolVal = cheerioWrapper.containsAllMatchingElements([<div className="foo bar"/>]);
}
function test_containsAnyMatchingElement() {
boolVal = cheerioWrapper.containsAnyMatchingElements([<div className="foo bar"/>]);
}
function test_equals() {
boolVal = cheerioWrapper.equals(<div className="foo bar"/>);
}
function test_matchesElement() {
boolVal = cheerioWrapper.matchesElement(<div className="foo bar"/>);
}
function test_hasClass() {
boolVal = cheerioWrapper.find('.my-button').hasClass('disabled');
}
@@ -464,6 +612,20 @@ namespace CheerioWrapperTest {
cheerioWrapper = cheerioWrapper.children();
}
function test_childAt() {
const childWrapper: CheerioWrapper<any, any> = cheerioWrapper.childAt(0);
interface TmpType1 {
foo: any
}
interface TmpType2 {
bar: any
}
const childWrapper2: CheerioWrapper<TmpType1, TmpType2> = cheerioWrapper.childAt<TmpType1, TmpType2>(0);
}
function test_parents() {
cheerioWrapper = cheerioWrapper.parents();
}
@@ -504,6 +666,13 @@ namespace CheerioWrapperTest {
function test_state() {
cheerioWrapper.state();
cheerioWrapper.state('key');
const tmp: String = cheerioWrapper.state<String>('key');
}
function test_context() {
cheerioWrapper.context();
cheerioWrapper.context('key');
const tmp: String = cheerioWrapper.context<String>('key');
}
function test_props() {
@@ -512,8 +681,12 @@ namespace CheerioWrapperTest {
function test_prop() {
cheerioWrapper.prop('key');
const tmp: String = cheerioWrapper.prop<String>('key');
}
function test_key() {
stringVal = cheerioWrapper.key();
}
function test_simulate(...args: any[]) {
cheerioWrapper.simulate('click');
@@ -521,15 +694,15 @@ namespace CheerioWrapperTest {
}
function test_setState() {
cheerioWrapper = cheerioWrapper.setState({stateProperty: 'state'});
cheerioWrapper = cheerioWrapper.setState({ stateProperty: 'state' });
}
function test_setProps() {
cheerioWrapper = cheerioWrapper.setProps({propsProperty: 'foo'});
cheerioWrapper = cheerioWrapper.setProps({ propsProperty: 'foo' });
}
function test_setContext() {
cheerioWrapper = cheerioWrapper.setContext({name: 'baz'});
cheerioWrapper = cheerioWrapper.setContext({ name: 'baz' });
}
function test_instance() {
@@ -545,12 +718,16 @@ namespace CheerioWrapperTest {
}
function test_type() {
var stringOrFunction: String|Function = cheerioWrapper.type();
var stringOrFunction: String | Function = cheerioWrapper.type();
}
function test_name() {
var str: String = cheerioWrapper.name();
}
function test_forEach() {
cheerioWrapper =
cheerioWrapper.forEach((aCheerioWrapper: CheerioWrapper<MyComponentProps, MyComponentState>)=> {
cheerioWrapper.forEach((aCheerioWrapper: CheerioWrapper<MyComponentProps, MyComponentState>) => {
});
}
+150 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for Enzyme v1.2.0
// Type definitions for Enzyme v2.3.0
// Project: https://github.com/airbnb/enzyme
// Definitions by: Marian Palkus <https://github.com/MarianPalkus>, Cap3 <http://www.cap3.de>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -57,6 +57,34 @@ declare module "enzyme" {
*/
contains(node: ReactElement<any>): Boolean;
/**
* Returns whether or not a given react element exists in the shallow render tree.
* @param node
*/
containsMatchingElement(node: ReactElement<any>): Boolean;
/**
* Returns whether or not all the given react elements exists in the shallow render tree
* @param nodes
*/
containsAllMatchingElements(nodes: ReactElement<any>[]): Boolean;
/**
* Returns whether or not one of the given react elements exists in the shallow render tree.
* @param nodes
*/
containsAnyMatchingElements(nodes: ReactElement<any>[]): Boolean;
/**
* Returns whether or not the current render tree is equal to the given node, based on the expected value.
*/
equals(node: ReactElement<any>): Boolean;
/**
* Returns whether or not a given react element matches the shallow render tree.
*/
matchesElement(node: ReactElement<any>): Boolean;
/**
* Returns whether or not the current node has a className prop including the passed in class name.
* @param className
@@ -86,6 +114,13 @@ declare module "enzyme" {
children(selector: string): CommonWrapper<HTMLAttributes, any>;
children(): CommonWrapper<any, any>;
/**
* Returns a new wrapper with child at the specified index.
* @param index
*/
childAt(index: Number): CommonWrapper<any, any>;
childAt<P2, S2>(index: Number): CommonWrapper<P2, S2>;
/**
* Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the
* current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector.
@@ -157,6 +192,13 @@ declare module "enzyme" {
* @param [key]
*/
state(key?: String): any;
state<T>(key?: String): T;
/**
* Returns the context hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value.
*/
context(key?: String): any;
context<T>(key?: String): T;
/**
* Returns the props hash for the current node of the wrapper.
@@ -172,6 +214,13 @@ declare module "enzyme" {
* @param key
*/
prop(key: String): any;
prop<T>(key: String): T;
/**
* Returns the key value for the node of the current wrapper.
* NOTE: can only be called on a wrapper of a single node.
*/
key(): String;
/**
* Simulate events.
@@ -247,6 +296,11 @@ declare module "enzyme" {
*/
type(): String | Function;
/**
* Returns the name of the current node of the wrapper.
*/
name(): String;
/**
* Iterates through each node of the current wrapper and executes the provided function with a wrapper around
* the corresponding node passed in as the first argument.
@@ -313,6 +367,7 @@ declare module "enzyme" {
export interface ShallowWrapper<P, S> extends CommonWrapper<P, S> {
shallow(): ShallowWrapper<P, S>;
render(): CheerioWrapper<P, S>;
unmount(): ShallowWrapper<any, any>;
/**
* Find every node in the render tree that matches the provided selector.
@@ -346,6 +401,13 @@ declare module "enzyme" {
children(selector: string): ShallowWrapper<HTMLAttributes, any>;
children(): ShallowWrapper<any, any>;
/**
* Returns a new wrapper with child at the specified index.
* @param index
*/
childAt(index: Number): ShallowWrapper<any, any>;
childAt<P2, S2>(index: Number): ShallowWrapper<P2, S2>;
/**
* Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the
* current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector.
@@ -376,7 +438,94 @@ declare module "enzyme" {
}
export interface ReactWrapper<P, S> extends CommonWrapper<P, S> {
unmount(): ReactWrapper<any, any>;
mount(): ReactWrapper<any, any>;
/**
* Returns a wrapper of the node that matches the provided reference name.
*
* NOTE: can only be called on a wrapper instance that is also the root instance.
*/
ref(refName: String): ReactWrapper<any, any>;
ref<P2, S2>(refName: String): ReactWrapper<P2, S2>;
/**
* Detaches the react tree from the DOM. Runs ReactDOM.unmountComponentAtNode() under the hood.
*
* This method will most commonly be used as a "cleanup" method if you decide to use the attachTo option in mount(node, options).
*
* The method is intentionally not "fluent" (in that it doesn't return this) because you should not be doing anything with this wrapper after this method is called.
*
* Using the attachTo is not generally recommended unless it is absolutely necessary to test something. It is your responsibility to clean up after yourself at the end of the test if you do decide to use it, though.
*/
detach() : void;
/**
* Find every node in the render tree that matches the provided selector.
* @param selector The selector to match.
*/
find<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
find<P2>(statelessComponent: (props: P2) => JSX.Element): ReactWrapper<P2, {}>;
find(selector: string): ReactWrapper<HTMLAttributes, any>;
/**
* Finds every node in the render tree that returns true for the provided predicate function.
* @param predicate
*/
findWhere(predicate: (wrapper: CommonWrapper<any, any>) => Boolean): ReactWrapper<any, any>;
/**
* Removes nodes in the current wrapper that do not match the provided selector.
* @param selector The selector to match.
*/
filter<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
filter<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, {}>;
filter(selector: string): ReactWrapper<HTMLAttributes, any>;
/**
* Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector
* can be provided and it will filter the children by this selector.
* @param [selector]
*/
children<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
children<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, {}>;
children(selector: string): ReactWrapper<HTMLAttributes, any>;
children(): ReactWrapper<any, any>;
/**
* Returns a new wrapper with child at the specified index.
* @param index
*/
childAt(index: Number): ReactWrapper<any, any>;
childAt<P2, S2>(index: Number): ReactWrapper<P2, S2>;
/**
* Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the
* current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector.
*
* Note: can only be called on a wrapper of a single node.
* @param [selector]
*/
parents<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
parents<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, {}>;
parents(selector: string): ReactWrapper<HTMLAttributes, any>;
parents(): ReactWrapper<any, any>;
/**
* Returns a wrapper of the first element that matches the selector by traversing up through the current node's
* ancestors in the tree, starting with itself.
*
* Note: can only be called on a wrapper of a single node.
* @param selector
*/
closest<P2>(component: ComponentClass<P2>): ReactWrapper<P2, any>;
closest<P2>(statelessComponent: StatelessComponent<P2>): ReactWrapper<P2, {}>;
closest(selector: string): ReactWrapper<HTMLAttributes, any>;
/**
* Returns a wrapper with the direct parent of the node in the current wrapper.
*/
parent(): ReactWrapper<any, any>;
}
export interface CheerioWrapper<P, S> extends CommonWrapper<P, S> {
+56
View File
@@ -0,0 +1,56 @@
/// <reference path="escodegen.d.ts" />
import * as escodegen from 'escodegen';
let emptyIndentOptions: escodegen.IndentOptions = {};
let indentOptions: escodegen.IndentOptions = {
style: ' ',
base: 0,
adjustMultilineComment: true
};
let emptyFormatOptions: escodegen.FormatOptions = {};
let formatOptions: escodegen.FormatOptions = {
indent: indentOptions,
newline: '\n',
space: ' ',
json: true,
renumber: true,
hexadecimal: true,
quotes: 'single',
escapeless: true,
compact: true,
parentheses: true,
semicolons: true,
safeConcatenation: true,
preserveBlankLines: true
}
let emptyMozillaOptions: escodegen.MozillaOptions = {};
let mozillaOptions: escodegen.MozillaOptions = {
starlessGenerator: true,
parenthesizedComprehensionBlock: true,
comprehensionExpressionStartsWithAssignment: true
}
let emptyGenerateOptions: escodegen.GenerateOptions = {};
let generateOptions: escodegen.GenerateOptions = {
format: formatOptions,
moz: mozillaOptions,
parse: () => {},
comment: true,
sourceMap: " ",
sourceMapWithCode: true,
sourceContent: " ",
sourceCode: " ",
sourceMapRoot: " ",
directive: true,
file: " ",
verbatim: " "
};
let precedence: escodegen.Precedence = escodegen.Precedence.Primary;
let myCode: string = escodegen.generate({}, generateOptions);
let ast: any = escodegen.attachComments({}, {}, {});
+178
View File
@@ -0,0 +1,178 @@
// Type definitions for escodegen
// Project: https://github.com/estools/escodegen
// Definitions by: Simon de Lang <https://github.com/simondel>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'escodegen' {
export interface FormatOptions {
/**
* The indent options
*/
indent?: IndentOptions;
/**
* New line string. Default is '\n'.
*/
newline?: string;
/**
* White space string. Default is standard ' ' (\x20).
*/
space?: string;
/**
* Enforce JSON format of numeric and string literals. This option takes precedence over option.format.hexadecimal and option.format.quotes. Default is false.
*/
json?: boolean;
/**
* Try to generate shorter numeric literals than toString() (9.8.1). Default is false.
*/
renumber?: boolean;
/**
* Generate hexadecimal a numeric literal if it is shorter than its equivalents. Requires option.format.renumber. Default is false.
*/
hexadecimal?: boolean;
/**
* Delimiter to use for string literals. Accepted values are: 'single', 'double', and 'auto'. When 'auto' is specified, escodegen selects a delimiter that results in a shorter literal. Default is 'single'.
*/
quotes?: string;
/**
* Escape as few characters in string literals as necessary. Default is false.
*/
escapeless?: boolean;
/**
* Do not include superfluous whitespace characters and line terminators. Default is false.
*/
compact?: boolean;
/**
* Preserve parentheses in new expressions that have no arguments. Default is true.
*/
parentheses?: boolean;
/**
* Preserve semicolons at the end of blocks and programs. Default is true.
*/
semicolons?: boolean;
safeConcatenation?: boolean;
preserveBlankLines?: boolean;
}
export interface IndentOptions {
/**
* Indent string. Default is 4 spaces (' ').
*/
style?: string;
/**
* Base indent level. Default is 0.
*/
base?: number;
/**
* Adjust the indentation of multiline comments to keep asterisks vertically aligned. Default is false.
*/
adjustMultilineComment?: boolean;
}
export interface MozillaOptions {
/**
* Default: false
*/
starlessGenerator?: boolean;
/**
* Default: false
*/
parenthesizedComprehensionBlock?: boolean;
/**
* Default: false
*/
comprehensionExpressionStartsWithAssignment?: boolean;
}
export interface GenerateOptions {
/**
* The format options
*/
format?: FormatOptions;
moz?: MozillaOptions;
/**
* Mozilla Parser API compatible parse function, e.g., the parse function exported by esprima. If it is provided, generator tries to use the 'raw' representation. See esprima raw information. Default is null.
*/
parse?: Function;
/**
* If comments are attached to AST, escodegen is going to emit comments to output code. Default is false.
*/
comment?: boolean;
/**
* sourceMap is the source maps's source filename, that's a name that will show up in the browser debugger for the generated source (if source-maps is enabled).
* If a non-empty string value is provided, generate a source map.
*/
sourceMap?: string;
/**
* . If sourceMapWithCode is true generator returns output hash, where output.map is a source-map representation, which can be serialized as output.map.toString(). output.code is a string with generated JS code (note that it's not going to have //@ sourceMappingURL comment in it).
*/
sourceMapWithCode?: boolean;
/**
* Optionally option.sourceContent string can be passed (which represents original source of the file, for example it could be a source of coffeescript from which JS is being generated), if provided generated source map will have original source embedded in it.
*/
sourceContent?: string;
sourceCode?: string;
/**
* Optionally option.sourceMapRoot can be provided, in which case option.sourceMap will be treated as relative to it. For more information about source map itself, see source map library document, V3 draft and HTML5Rocks introduction. Default is undefined
* sourceMapRoot is the source root for the source map (see the Mozilla documentation). If sourceMapWithCode is truthy, an object is returned from generate() of the form: { code: .. , map: .. }. If file is provided, it will be used as file property of generated source map.
*/
sourceMapRoot?: string;
/**
* Recognize DirectiveStatement and distinguish it from ExpressionStatement. Default: false
*/
directive?: boolean;
/**
* If file is provided, it will be used as file property of generated source map.
*/
file?: string;
/**
* Providing verbatim code generation option to Expression nodes.
* verbatim option is provided by user as string. When generating Expression code,
* looking up node[option.verbatim] value and dump it instead of normal code generation.
*
* @example
*
*/
verbatim?: string;
}
/**
* https://github.com/estools/escodegen/commit/adf113333cd4888cf59bfc4f957df98bf7db82b6
*/
export enum Precedence {
Sequence,
Yield,
Await,
Assignment,
Conditional,
ArrowFunction,
LogicalOR,
LogicalAND,
BitwiseOR,
BitwiseXOR,
BitwiseAND,
Equality,
Relational,
BitwiseSHIFT,
Additive,
Multiplicative,
Unary,
Postfix,
Call,
New,
TaggedTemplate,
Member,
Primary
}
/**
* Produces given Abstract Syntax Tree as javascript code
* @param ast The Abstract Syntax Tree to generate code from
* @param options The generation options
*/
export function generate(ast: any, options?: GenerateOptions): string;
/**
* Attaching the comments is needed to keep the comments and to allow blank lines to be preserved.
*/
export function attachComments(ast: any, comments: any, tokens: any): any;
}
+59
View File
@@ -0,0 +1,59 @@
/// <reference path="estraverse.d.ts" />
import * as estraverse from 'estraverse';
let ast: any = {
"type": "Program",
"body": [
{
"type": "VariableDeclaration",
"declarations": [
{
"type": "VariableDeclarator",
"id": {
"type": "Identifier",
"name": "answer"
},
"init": {
"type": "BinaryExpression",
"operator": "*",
"left": {
"type": "Literal",
"value": 6,
"raw": "6"
},
"right": {
"type": "Literal",
"value": 7,
"raw": "7"
}
}
}
],
"kind": "var"
}
],
"sourceType": "script"
};
estraverse.traverse(ast, {
enter: (node: any, parentNode: any) => {
if (node.type === 'Identifier') {
return estraverse.VisitorOption.Skip;
}
},
leave: (node: any, parentNode: any) => {},
fallback: 'iteration',
keys: {
TestExpression: ['argument']
}
});
estraverse.replace(ast, {
enter: (node: any, parentNode: any) => {
return node;
},
leave: (node: any, parentNode: any) => {
return node;
}
});
+22
View File
@@ -0,0 +1,22 @@
// Type definitions for estraverse
// Project: https://github.com/estools/estraverse
// Definitions by: Sanex3339 <https://github.com/sanex3339>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'estraverse' {
export interface Visitor {
enter?: (node: any, parentNode: any) => any;
leave?: (node: any, parentNode: any) => any;
fallback?: string;
keys?: {};
}
export enum VisitorOption {
Skip, Break, Remove
}
export function traverse (ast: any, visitor: Visitor): any;
export function replace (ast: any, visitor: Visitor): any;
}
@@ -0,0 +1,2 @@
/// <reference path="express-domain-middleware.d.ts" />
import fn = require('express-domain-middleware');
@@ -0,0 +1,12 @@
// Type definitions for express-domain-middleware
// Project: https://www.npmjs.com/package/express-domain-middleware
// Definitions by: Hookclaw <https://github.com/hookclaw>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
declare module "express-domain-middleware" {
import express = require('express');
function e(req: express.Request, res: express.Response, next: express.NextFunction): any;
export = e;
}
+15
View File
@@ -0,0 +1,15 @@
// Type definitions for generic-functions
// Project: https://github.com/stpettersens/generic-functions
// Definitions by: Sam Saint-Pettersen <https://github.com/stpettersens>
// Definitions: https://github.com/definitelytyped/DefinitelyTyped
declare module "generic-functions" {
function strcmp(str1: string, str2: string): boolean;
function icstrcmp(str1: string, str2: string): boolean;
function strendswith(str: string, suffix: string): boolean;
function icstrendswith(str: string, suffix: string): boolean;
function endswithdot(str: string): string;
function println(message: string): void;
function printlns(message: string[]): void;
function objGetKeyByValue(object: Object, value: any): string;
}
@@ -0,0 +1,16 @@
/// <reference path="generic-functions.d.ts" />
import g = require('generic-functions');
var tvShow: Object = {
seasons: 2,
show: "Better Call Saul"
};
console.log(g.strcmp("foo", "foo")); // => true
console.log(g.icstrcmp("BAR", "bar")); // => true
console.log(g.strendswith("file.pdf", "pdf")); // => true
console.log(g.icstrendswith("file.PDF", "pdf")); // => true
console.log(g.endswithdot("file.pdf")); // => ".pdf"
console.log(g.objGetKeyByValue(tvShow, 2)); // => "seasons"
console.log(g.objGetKeyByValue(tvShow, "Better Call Saul")); // => "show"
+9
View File
@@ -36,6 +36,7 @@ declare namespace GeoJSON {
*/
export interface Point extends GeometryObject
{
type: 'Point'
coordinates: Position
}
@@ -44,6 +45,7 @@ declare namespace GeoJSON {
*/
export interface MultiPoint extends GeometryObject
{
type: 'MultiPoint'
coordinates: Position[]
}
@@ -52,6 +54,7 @@ declare namespace GeoJSON {
*/
export interface LineString extends GeometryObject
{
type: 'LineString'
coordinates: Position[]
}
@@ -60,6 +63,7 @@ declare namespace GeoJSON {
*/
export interface MultiLineString extends GeometryObject
{
type: 'MultiLineString'
coordinates: Position[][]
}
@@ -68,6 +72,7 @@ declare namespace GeoJSON {
*/
export interface Polygon extends GeometryObject
{
type: 'Polygon'
coordinates: Position[][]
}
@@ -76,6 +81,7 @@ declare namespace GeoJSON {
*/
export interface MultiPolygon extends GeometryObject
{
type: 'MultiPolygon'
coordinates: Position[][][]
}
@@ -84,6 +90,7 @@ declare namespace GeoJSON {
*/
export interface GeometryCollection extends GeoJsonObject
{
type: 'GeometryCollection'
geometries: GeometryObject[];
}
@@ -92,6 +99,7 @@ declare namespace GeoJSON {
*/
export interface Feature<T extends GeometryObject> extends GeoJsonObject
{
type: 'Feature'
geometry: T;
properties: any;
id?: string;
@@ -102,6 +110,7 @@ declare namespace GeoJSON {
*/
export interface FeatureCollection<T extends GeometryObject> extends GeoJsonObject
{
type: 'FeatureCollection'
features: Feature<T>[];
}
+184 -5
View File
@@ -1,4 +1,4 @@
// Type definitions for Electron v0.37.8
// Type definitions for Electron v1.0.2
// Project: http://electron.atom.io/
// Definitions by: jedmao <https://github.com/jedmao/>, rhysd <https://rhysd.github.io>, Milan Burda <https://github.com/miniak/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -96,6 +96,11 @@ declare namespace Electron {
* Note: This is only implemented on OS X.
*/
on(event: 'activate', listener: Function): this;
/**
* Emitted during Handoff when an activity from a different device wants to be resumed.
* You should call event.preventDefault() if you want to handle this event.
*/
on(event: 'continue-activity', listener: (event: Event, type: string, userInfo: Object) => void): this;
/**
* Emitted when a browserWindow gets blurred.
*/
@@ -251,8 +256,7 @@ declare namespace Electron {
/**
* Removes the current executable as the default handler for a protocol (aka URI scheme).
*
* Note: This is only implemented on Windows.
* On OS X, removing the app will automatically remove the app as the default protocol handler.
* Note: This is only implemented on OS X and Windows.
*/
removeAsDefaultProtocolClient(protocol: string): void;
/**
@@ -281,6 +285,22 @@ declare namespace Electron {
* of your app is running, and other instances signal this instance and exit.
*/
makeSingleInstance(callback: (args: string[], workingDirectory: string) => void): boolean;
/**
* Creates an NSUserActivity and sets it as the current activity.
* The activity is eligible for Handoff to another device afterward.
*
* @param type Uniquely identifies the activity. Maps to NSUserActivity.activityType.
* @param userInfo App-specific state to store for use by another device.
*
* Note: This API is only available on Mac.
*/
setUserActivity(type: string, userInfo: Object): void;
/**
* @returns The type of the currently running activity.
*
* Note: This API is only available on Mac.
*/
getCurrentActivityType(): string;
/**
* Changes the Application User Model ID to id.
*/
@@ -348,6 +368,12 @@ declare namespace Electron {
* Note: This API is only available on Mac.
*/
cancelBounce(id: number): void;
/**
* Bounces the Downloads stack if the filePath is inside the Downloads folder.
*
* Note: This API is only available on Mac.
*/
downloadFinished(filePath: string): void;
/**
* Sets the string to be displayed in the dock’s badging area.
*
@@ -1103,6 +1129,11 @@ declare namespace Electron {
* Default: true.
*/
directWrite?: boolean;
/**
* Enables scroll bounce (rubber banding) effect on OS X.
* Default: false.
*/
scrollBounce?: boolean;
/**
* A list of feature strings separated by ",".
*/
@@ -1239,7 +1270,7 @@ declare namespace Electron {
alwaysOnTop?: boolean;
/**
* Whether the window should show in fullscreen.
* When explicity set to false the fullscreen button will be hidden or disabled on OS X.
* When explicitly set to false the fullscreen button will be hidden or disabled on OS X.
* Default: false.
*/
fullscreen?: boolean;
@@ -1722,7 +1753,7 @@ declare namespace Electron {
*/
type?: 'none' | 'info' | 'error' | 'question' | 'warning';
/**
* Texts for buttons.
* Texts for buttons. On Windows, an empty array will result in one button labeled "OK".
*/
buttons?: string[];
/**
@@ -2023,6 +2054,7 @@ declare namespace Electron {
* Punctuations like ~, !, @, #, $, etc.
* Plus
* Space
* Tab
* Backspace
* Delete
* Insert
@@ -3284,6 +3316,10 @@ declare namespace Electron {
* in a NativeImage, and the scale will hold scaling information for the image.
*/
on(event: 'cursor-changed', listener: (event: Event, type: CursorType, image?: NativeImage, scale?: number) => void): this;
/**
* Emitted when there is a new context menu that needs to be handled.
*/
on(event: 'context-menu', listener: (event: Event, params: ContextMenuParams) => void): this;
on(event: string, listener: Function): this;
/**
* Loads the url in the window.
@@ -3574,6 +3610,144 @@ declare namespace Electron {
debugger: Debugger;
}
interface ContextMenuParams {
/**
* x coodinate
*/
x: number;
/**
* y coodinate
*/
y: number;
/**
* URL of the link that encloses the node the context menu was invoked on.
*/
linkURL: string;
/**
* Text associated with the link. May be an empty string if the contents of the link are an image.
*/
linkText: string;
/**
* URL of the top level page that the context menu was invoked on.
*/
pageURL: string;
/**
* URL of the subframe that the context menu was invoked on.
*/
frameURL: string;
/**
* Source URL for the element that the context menu was invoked on.
* Elements with source URLs are images, audio and video.
*/
srcURL: string;
/**
* Type of the node the context menu was invoked on.
*/
mediaType: 'none' | 'image' | 'audio' | 'video' | 'canvas' | 'file' | 'plugin';
/**
* Parameters for the media element the context menu was invoked on.
*/
mediaFlags: {
/**
* Wether the media element has crashed.
*/
inError: boolean;
/**
* Wether the media element is paused.
*/
isPaused: boolean;
/**
* Wether the media element is muted.
*/
isMuted: boolean;
/**
* Wether the media element has audio.
*/
hasAudio: boolean;
/**
* Wether the media element is looping.
*/
isLooping: boolean;
/**
* Wether the media element's controls are visible.
*/
isControlsVisible: boolean;
/**
* Wether the media element's controls are toggleable.
*/
canToggleControls: boolean;
/**
* Wether the media element can be rotated.
*/
canRotate: boolean;
}
/**
* Wether the context menu was invoked on an image which has non-empty contents.
*/
hasImageContents: boolean;
/**
* Wether the context is editable.
*/
isEditable: boolean;
/**
* These flags indicate wether the renderer believes it is able to perform the corresponding action.
*/
editFlags: {
/**
* Wether the renderer believes it can undo.
*/
canUndo: boolean;
/**
* Wether the renderer believes it can redo.
*/
canRedo: boolean;
/**
* Wether the renderer believes it can cut.
*/
canCut: boolean;
/**
* Wether the renderer believes it can copy
*/
canCopy: boolean;
/**
* Wether the renderer believes it can paste.
*/
canPaste: boolean;
/**
* Wether the renderer believes it can delete.
*/
canDelete: boolean;
/**
* Wether the renderer believes it can select all.
*/
canSelectAll: boolean;
}
/**
* Text of the selection that the context menu was invoked on.
*/
selectionText: string;
/**
* Title or alt text of the selection that the context was invoked on.
*/
titleText: string;
/**
* The misspelled word under the cursor, if any.
*/
misspelledWord: string;
/**
* The character encoding of the frame on which the menu was invoked.
*/
frameCharset: string;
/**
* If the context menu was invoked on an input field, the type of that field.
*/
inputFieldType: 'none' | 'plainText' | 'password' | 'other';
/**
* Input source that invoked the context menu.
*/
menuSourceType: 'none' | 'mouse' | 'keyboard' | 'touch' | 'touchMenu';
}
interface Headers {
[key: string]: string;
}
@@ -4511,6 +4685,11 @@ declare namespace NodeJS {
* If the app is running as a Windows Store app (appx), this value is true, for other builds it is undefined.
*/
windowsStore?: boolean;
/**
* When app is started by being passed as parameter to the default app,
* this value is true in the main process, otherwise it is undefined.
*/
defaultApp?: boolean;
/**
* Emitted when Electron has loaded its internal initialization script
* and is beginning to load the web page or the main script.
+6 -6
View File
@@ -12,9 +12,9 @@ var options = <IGridstackOptions> {
};
var gridstack:GridStack = $(document).gridstack(options);
gridstack.add_widget("test", 1, 2, 3, 4, true);
gridstack.batch_update();
gridstack.cell_height();;
gridstack.cell_height(2);
gridstack.cell_width();
gridstack.get_cell_from_pixel(<MousePosition>{ left:20, top: 20 });
gridstack.addWidget("test", 1, 2, 3, 4, true);
gridstack.batchUpdate();
gridstack.cellHeight();;
gridstack.cellHeight(2);
gridstack.cellWidth();
gridstack.getCellFromPixel(<MousePosition>{ left:20, top: 20 });
+26 -26
View File
@@ -11,35 +11,35 @@ interface GridStack {
/**
* Creates new widget and returns it.
*
* Widget will be always placed even if result height is more than actual grid height. You need to use will_it_fit method before calling add_widget for additional check.
* Widget will be always placed even if result height is more than actual grid height. You need to use willItFit method before calling addWidget for additional check.
*
* @param {string} el widget to add
* @param {number} x widget position x
* @param {number} y widget position y
* @param {number} width widget dimension width
* @param {number} height widget dimension height
* @param {boolean} auto_position if true then x, y parameters will be ignored and widget will be places on the first available position
* @param {boolean} autoPosition if true then x, y parameters will be ignored and widget will be places on the first available position
*/
add_widget(el: string, x: number, y: number, width: number, height: number, auto_position: boolean): JQuery
addWidget(el: string, x: number, y: number, width: number, height: number, autoPosition: boolean): JQuery
/**
* Initializes batch updates. You will see no changes until commit method is called.
*/
batch_update():void
batchUpdate():void
/**
* Gets current cell height.
*/
cell_height():number
cellHeight():number
/**
* Update current cell height. This method rebuilds an internal CSS style sheet. Note: You can expect performance issues if call this method too often.
* @param {number} val the cell height
*/
cell_height(val:number):void
cellHeight(val:number):void
/**
* Gets current cell width.
*/
cell_width():number
cellWidth():number
/**
* Finishes batch updates. Updates DOM nodes. You must call it after batch_update.
* Finishes batch updates. Updates DOM nodes. You must call it after batchUpdate.
*/
commit():void
/**
@@ -58,7 +58,7 @@ interface GridStack {
* Get the position of the cell under a pixel on screen.
* @param {MousePosition} position the position of the pixel to resolve in absolute coordinates, as an object with top and leftproperties
*/
get_cell_from_pixel(position: MousePosition): CellPosition,
getCellFromPixel(position: MousePosition): CellPosition,
/*
* Checks if specified area is empty.
* @param {number} x the position x.
@@ -66,7 +66,7 @@ interface GridStack {
* @param {number} width the width of to check
* @param {number} height the height of to check
*/
is_area_empty(x: number, y: number, width: number, height: number): void
isAreaEmpty(x: number, y: number, width: number, height: number): void
/*
* Locks/unlocks widget.
* @param {HTMLElement} el widget to modify.
@@ -78,13 +78,13 @@ interface GridStack {
* @param {HTMLElement} el widget to modify.
* @param {number} val A numeric value of the number of columns
*/
min_width(el: HTMLElement, val: number): void
minWidth(el: HTMLElement, val: number): void
/*
* Set the minHeight for a widget.
* @param {HTMLElement} el widget to modify.
* @param {number} val A numeric value of the number of rows
*/
min_height(el: HTMLElement, val: number): void
minHeight(el: HTMLElement, val: number): void
/*
* Enables/Disables moving.
* @param {HTMLElement} el widget to modify.
@@ -102,13 +102,13 @@ interface GridStack {
/**
* Removes widget from the grid.
* @param {HTMLElement} el widget to modify
* @param {boolean} detach_node if false DOM node won't be removed from the tree (Optional. Default true).
* @param {boolean} detachNode if false DOM node won't be removed from the tree (Optional. Default true).
*/
remove_widget(el: HTMLElement, detach_node?: boolean): void
removeWidget(el: HTMLElement, detachNode?: boolean): void
/**
* Removes all widgets from the grid.
*/
remove_all(): void
removeAll(): void
/**
* Changes widget size
* @param {HTMLElement} el widget to modify
@@ -124,9 +124,9 @@ interface GridStack {
resizable(el: HTMLElement, val: boolean): void
/**
* Toggle the grid static state. Also toggle the grid-stack-static class.
* @param {boolean} static_value if true the grid become static.
* @param {boolean} staticValue if true the grid become static.
*/
set_static(static_value: boolean): void
setStatic(staticValue: boolean): void
/**
* Updates widget position/size.
* @param {HTMLElement} el widget to modify
@@ -142,9 +142,9 @@ interface GridStack {
* @param {number} y new position y. If value is null or undefined it will be ignored.
* @param {number} width new dimensions width. If value is null or undefined it will be ignored.
* @param {number} height new dimensions height. If value is null or undefined it will be ignored.
* @param {boolean} auto_position if true then x, y parameters will be ignored and widget will be places on the first available position
* @param {boolean} autoPosition if true then x, y parameters will be ignored and widget will be places on the first available position
*/
will_it_fit(x: number, y: number, width: number, height: number, auto_position:boolean):boolean
willItFit(x: number, y: number, width: number, height: number, autoPosition:boolean):boolean
}
@@ -181,7 +181,7 @@ interface IGridstackOptions {
/**
* if true the resizing handles are shown even if the user is not hovering over the widget (default: false)
*/
always_show_resize_handle: boolean;
alwaysShowResizeHandle: boolean;
/**
* turns animation on (default: true)
*/
@@ -193,7 +193,7 @@ interface IGridstackOptions {
/**
* one cell height (default: 60)
*/
cell_height: number;
cellHeight: number;
/**
* allows to override jQuery UI draggable options. (default: { handle: '.grid-stack-item-content', scroll: true, appendTo: 'body' })
*/
@@ -213,15 +213,15 @@ interface IGridstackOptions {
/**
* widget class (default: 'grid-stack-item')
*/
item_class: string;
itemClass: string;
/**
* minimal width.If window width is less, grid will be shown in one - column mode (default: 768)
*/
min_width: number;
minWidth: number;
/**
* class for placeholder (default: 'grid-stack-placeholder')
*/
placeholder_class: string;
placeholderClass: string;
/**
* allows to override jQuery UI resizable options. (default: { autoHide: true, handles: 'se' })
*/
@@ -229,11 +229,11 @@ interface IGridstackOptions {
/**
* makes grid static (default false).If true widgets are not movable/ resizable.You don't even need jQueryUI draggable/resizable. A CSS class grid-stack-static is also added to the container.
*/
static_grid: boolean;
staticGrid: boolean;
/**
* vertical gap size (default: 20)
*/
vertical_margin: number;
verticalMargin: number;
/**
* amount of columns (default: 12)
*/
+82
View File
@@ -120,6 +120,88 @@ function test_HandsontableInit() {
visibleRows: 123,
width: 1232,
wordWrap: true,
// Hooks
afterAutofillApplyValues: function() {},
afterCellMetaReset: function() {},
afterChange: function() {},
afterChangesObserved: function() {},
afterColumnMove: function() {},
afterColumnResize: function() {},
afterColumnSort: function() {},
afterContextMenuDefaultOptions: function() {},
afterContextMenuHide: function() {},
afterContextMenuShow: function() {},
afterCopyLimit: function() {},
afterCreateCol: function() {},
afterCreateRow: function() {},
afterDeselect: function() {},
afterDestroy: function() {},
afterDocumentKeyDown: function() {},
afterFilter: function() {},
afterGetCellMeta: function() {},
afterGetColHeader: function() {},
afterGetColumnHeaderRenderers: function() {},
afterGetRowHeader: function() {},
afterGetRowHeaderRenderers: function() {},
afterInit: function() {},
afterLoadData: function() {},
afterMomentumScroll: function() {},
afterOnCellCornerMouseDown: function() {},
afterOnCellMouseDown: function() {},
afterOnCellMouseOver: function() {},
afterRemoveCol: function() {},
afterRemoveRow: function() {},
afterRender: function() {},
afterRenderer: function() {},
afterRowMove: function() {},
afterRowResize: function() {},
afterScrollHorizontally: function() {},
afterScrollVertically: function() {},
afterSelection: function() {},
afterSelectionByProp: function() {},
afterSelectionEnd: function() {},
afterSelectionEndByProp: function() {},
afterSetCellMeta: function() {},
afterUpdateSettings: function() {},
afterValidate: function() {},
beforeAutofill: function() {},
beforeCellAlignment: function() {},
beforeChange: function() {},
beforeChangeRender: function() {},
beforeColumnMove: function() {},
beforeColumnResize: function() {},
beforeColumnSort: function() {},
beforeDrawBorders: function() {},
beforeFilter: function() {},
beforeGetCellMeta: function() {},
beforeInit: function() {},
beforeInitWalkontable: function() {},
beforeKeyDown: function() {},
beforeOnCellMouseDown: function() {},
beforeRemoveCol: function() {},
beforeRemoveRow: function() {},
beforeRender: function() {},
beforeRenderer: function() {},
beforeRowMove: function() {},
beforeRowResize: function() {},
beforeSetRangeEnd: function() {},
beforeStretchingColumnWidth: function() {},
beforeTouchScroll: function() {},
beforeValidate: function() {},
construct: function() {},
init: function() {},
modifyCol: function() {},
modifyColHeader: function() {},
modifyColWidth: function() {},
modifyCopyableRange: function() {},
modifyRow: function() {},
modifyRowHeader: function() {},
modifyRowHeight: function() {},
persistentStateLoad: function() {},
persistentStateReset: function() {},
persistentStateSave: function() {},
unmodifyCol: function() {}
});
}
+85 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for Handsontable 0.24.1
// Type definitions for Handsontable 0.24.3
// Project: https://handsontable.com/
// Definitions by: Handsoncode sp. z o.o. <http://handsoncode.net/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\
@@ -124,6 +124,88 @@ declare namespace ht {
wordWrap?: boolean;
isEmptyCol?: (col: number) => boolean;
isEmptyRow?: (row: number) => boolean;
// hooks
afterAutofillApplyValues?: (startArea: any[], entireArea: any[]) => void;
afterCellMetaReset?: () => void;
afterChange?: (changes: any[], source: string) => void;
afterChangesObserved?: () => void;
afterColumnMove?: (startColumn: number, endColumn: number) => void;
afterColumnResize?: (currentColumn: number, newSize: number, isDoubleClick: boolean) => void;
afterColumnSort?: (column: number, order: boolean) => void;
afterContextMenuDefaultOptions?: (predefinedItems: any[]) => void;
afterContextMenuHide?: (context: Object) => void;
afterContextMenuShow?: (context: Object) => void;
afterCopyLimit?: (selectedRows: number, selectedColumnds: number, copyRowsLimit: number, copyColumnsLimit: number) => void;
afterCreateCol?: (index: number, amount: number) => void;
afterCreateRow?: (index: number, amount: number) => void;
afterDeselect?: () => void;
afterDestroy?: () => void;
afterDocumentKeyDown?: (event: Event) => void;
afterFilter?: (formulasStack: any[]) => void;
afterGetCellMeta?: (row: number, col: number, cellProperties: Object) => void;
afterGetColHeader?: (col: number, TH: Element) => void;
afterGetColumnHeaderRenderers?: (array: any[]) => void;
afterGetRowHeader?: (row: number, TH: Element) => void;
afterGetRowHeaderRenderers?: (array: any[]) => void;
afterInit?: () => void;
afterLoadData?: (firstTime: boolean) => void;
afterMomentumScroll?: () => void;
afterOnCellCornerMouseDown?: (event: Object) => void;
afterOnCellMouseDown?: (event: Object, coords: Object, TD: Element) => void;
afterOnCellMouseOver?: (event: Object, coords: Object, TD: Element) => void;
afterRemoveCol?: (index: number, amount: number) => void;
afterRemoveRow?: (index: number, amount: number) => void;
afterRender?: (isForced: boolean) => void;
afterRenderer?: (TD: Element, row: number, col: number, prop: string|number, value: string, cellProperties: Object) => void;
afterRowMove?: (startRow: number, endRow: number) => void;
afterRowResize?: (currentRow: number, newSize: number, isDoubleClick: boolean) => void;
afterScrollHorizontally?: () => void;
afterScrollVertically?: () => void;
afterSelection?: (r: number, c: number, r2: number, c2: number) => void;
afterSelectionByProp?: (r: number, p: string, r2: number, p2: string) => void;
afterSelectionEnd?: (r: number, c: number, r2: number, c2: number) => void;
afterSelectionEndByProp?: (r: number, p: string, r2: number, p2: string) => void;
afterSetCellMeta?: (row: number, col: number, key: string, value: any) => void;
afterUpdateSettings?: () => void;
afterValidate?: (isValid: boolean, value: any, row: number, prop: string|number, source: string) => void|boolean;
beforeAutofill?: (start: Object, end: Object, data: any[]) => void;
beforeCellAlignment?: (stateBefore: any, range: any, type: string, alignmentClass: string) => void;
beforeChange?: (changes: any[], source: string) => void;
beforeChangeRender?: (changes: any[], source: string) => void;
beforeColumnMove?: (startColumn: number, endColumn: number) => void;
beforeColumnResize?: (currentColumn: number, newSize: number, isDoubleClick: boolean) => void;
beforeColumnSort?: (column: number, order: boolean) => void;
beforeDrawBorders?: (corners: any[], borderClassName: string) => void;
beforeFilter?: (formulasStack: any[]) => void;
beforeGetCellMeta?: (row: number, col: number, cellProperties: Object) => void;
beforeInit?: () => void;
beforeInitWalkontable?: (walkontableConfig: Object) => void;
beforeKeyDown?: (event: Event) => void;
beforeOnCellMouseDown?: (event: Event, coords: Object, TD: Element) => void;
beforeRemoveCol?: (index: number, amount: number, logicalCols?: any[]) => void;
beforeRemoveRow?: (index: number, amount: number, logicalRows?: any[]) => void;
beforeRender?: (isForced: boolean) => void;
beforeRenderer?: (TD: Element, row: number, col: number, prop: string|number, value: string, cellProperties: Object) => void;
beforeRowMove?: (startRow: number, endRow: number) => void;
beforeRowResize?: (currentRow: number, newSize: number, isDoubleClick: boolean) => any;
beforeSetRangeEnd?: (coords: any[]) => void;
beforeStretchingColumnWidth?: (stretchedWidth: number, column: number) => void;
beforeTouchScroll?: () => void;
beforeValidate?: (value: any, row: number, prop: string|number, source: string) => void;
construct?: () => void;
init?: () => void;
modifyCol?: (col: number) => void;
modifyColHeader?: (column: number) => void;
modifyColWidth?: (width: number, col: number) => void;
modifyCopyableRange?: (copyableRanges: any[]) => void;
modifyRow?: (row: number) => void;
modifyRowHeader?: (row: number) => void;
modifyRowHeight?: (height: number, row: number) => void;
persistentStateLoad?: (key: string, valuePlaceholder: Object) => void;
persistentStateReset?: (key: string) => void;
persistentStateSave?: (key: string, value: any) => void;
unmodifyCol?: (col: number) => void;
}
interface Methods {
addHook(key: string, callback: Function|any[]): void;
@@ -203,6 +285,8 @@ declare namespace ht {
validateCells(callback: Function): void;
}
}
declare var Handsontable: {
new (element: Element, options: ht.Options): ht.Methods;
};
+1
View File
@@ -79,6 +79,7 @@ server.route({
method: 'GET',
path: '/hello',
handler: function (request: Hapi.Request, reply: Function) {
request.log('info', { route: '/hello' }, Date.now());
reply('hello world');
}
});
+1 -1
View File
@@ -1301,7 +1301,7 @@ declare module "hapi" {
log(/** a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events.*/
tags: string | string[],
/** an optional message string or object with the application data being logged.*/
data?: string,
data?: any,
/** an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).*/
timestamp?: number): void;
+1 -1
View File
@@ -1,6 +1,6 @@
// Type definitions for helmet
// Project: https://github.com/helmetjs/helmet
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>, Evan Hahn <https://github.com/EvanHahn>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
+22 -16
View File
@@ -1,6 +1,6 @@
// Type definitions for html2canvas.js v0.4.1
// Type definitions for html2canvas.js v0.5.0-bata.4
// Project: https://github.com/niklasvh/html2canvas
// Definitions by: Richard Hepburn <https://github.com/rwhepburn/>
// Definitions by: Richard Hepburn <https://github.com/rwhepburn/>, Pei-Tang Huang <https://github.com/tan9/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
@@ -36,26 +36,14 @@ declare namespace Html2Canvas {
/** Whether to attempt to load cross-origin images as CORS served, before reverting back to proxy. */
useCORS?: boolean;
/** Use svg powered rendering where available (FF11+). */
svgRendering?: boolean;
/** Callback providing the rendered canvas element after rendering */
onrendered?(canvas: HTMLCanvasElement): void;
}
}
interface Html2CanvasStatic {
/**
* Renders an HTML element to a canvas so that a screenshot can be generated.
*
* The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot,
* but builds the screenshot based on the information available on the page.
*
* @param {HTMLElement} element The HTML element which will be rendered to the canvas. Use the root element to render the entire window.
*/
(element: HTMLElement): void;
/**
* Renders an HTML element to a canvas so that a screenshot can be generated.
*
@@ -65,7 +53,25 @@ interface Html2CanvasStatic {
* @param {HTMLElement} element The HTML element which will be rendered to the canvas. Use the root element to render the entire window.
* @param {Html2CanvasOptions} options The options object that controls how the element will be rendered.
*/
(element: HTMLElement, options: Html2Canvas.Html2CanvasOptions): void;
(element: HTMLElement, options?: Html2Canvas.Html2CanvasOptions): Html2CanvasPromise<HTMLCanvasElement>;
}
// FIXME:
// Find out a way to dependent on real Promise interface.
// And remove following custome Promise interface.
interface Html2CanvasThenable<R> {
then<U>(onFulfilled?: (value: R) => U | Html2CanvasThenable<U>, onRejected?: (error: any) => U | Html2CanvasThenable<U>): Html2CanvasThenable<U>;
then<U>(onFulfilled?: (value: R) => U | Html2CanvasThenable<U>, onRejected?: (error: any) => void): Html2CanvasThenable<U>;
}
interface Html2CanvasPromise<R> extends Html2CanvasThenable<R> {
then<U>(onFulfilled?: (value: R) => U | Html2CanvasThenable<U>, onRejected?: (error: any) => U | Html2CanvasThenable<U>): Html2CanvasPromise<U>;
then<U>(onFulfilled?: (value: R) => U | Html2CanvasThenable<U>, onRejected?: (error: any) => void): Html2CanvasPromise<U>;
catch<U>(onRejected?: (error: any) => U | Html2CanvasThenable<U>): Html2CanvasPromise<U>;
}
declare module 'html2canvas' {
export = html2canvas;
}
declare var html2canvas: Html2CanvasStatic;
+5
View File
@@ -50,6 +50,11 @@ declare namespace i18n {
* json files prefix
*/
prefix?: string;
/**
* object or [obj1, obj2] to bind the i18n api and current locale to - defaults to null
*/
register?: any;
}
export interface TranslateOptions {
phrase: string;
+2
View File
@@ -62,3 +62,5 @@ i18n.t('helloWorld', <I18next.TranslationOptions> {
defaultValue: 'default',
count: 10
});
const currentLanguage:string = i18n.language;
const userLanguageCodes:string[] = i18n.languages;
+4
View File
@@ -94,6 +94,10 @@ declare namespace I18next {
loadResources(callback?:(err:any) => void):void;
language:string;
languages:string[];
use(module:any):I18n;
changeLanguage(lng:string, callback?:(err:any, t:TranslationFunction) => void):void;
+4
View File
@@ -678,6 +678,10 @@ declare module IORedis {
* default: false.
*/
readOnly?: boolean;
/**
* If you are using the hiredis parser, it's highly recommended to enable this option. Create another instance with dropBufferSupport disabled for other commands that you want to return binary instead of string:
*/
dropBufferSupport?: boolean;
}
interface ScanStreamOption {
+69 -39
View File
@@ -3,52 +3,82 @@
import irc = require('irc');
var bot = new irc.Client('irc.dollyfish.net.nz', 'nodebot', {
debug: true,
channels: ['#blah', '#test']
});
function test_bot() {
var bot = new irc.Client('irc.dollyfish.net.nz', 'nodebot', {
debug: true,
channels: ['#blah', '#test']
});
bot.addListener('error', <irc.handlers.IError> ((message: irc.IMessage) => {
console.error('ERROR: %s: %s', message.command, message.args.join(' '));
}));
bot.connect(function() {
console.log("Connected");
});
bot.addListener('message#blah', <irc.handlers.IMessageChannel> ((from: string, message: string) => {
console.log('<%s> %s', from, message);
}));
bot.addListener('error', <irc.handlers.IError> ((message: irc.IMessage) => {
console.error('ERROR: %s: %s', message.command, message.args.join(' '));
}));
bot.addListener('message', <irc.handlers.IRecievedMessage> ((from: string, to: string, message: string) => {
console.log('%s => %s: %s', from, to, message);
bot.addListener('message#blah', <irc.handlers.IMessageChannel> ((from: string, message: string) => {
console.log('<%s> %s', from, message);
}));
if (to.match(/^[#&]/)) {
// channel message
if (message.match(/hello/i)) {
bot.say(to, 'Hello there ' + from);
bot.addListener('message', <irc.handlers.IRecievedMessage> ((from: string, to: string, message: string) => {
console.log('%s => %s: %s', from, to, message);
if (to.match(/^[#&]/)) {
// channel message
if (message.match(/hello/i)) {
bot.say(to, 'Hello there ' + from);
}
if (message.match(/dance/)) {
setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D\\-<\u0001'); }, 1000);
setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D|-<\u0001'); }, 2000);
setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D/-<\u0001'); }, 3000);
setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D|-<\u0001'); }, 4000);
}
}
if (message.match(/dance/)) {
setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D\\-<\u0001'); }, 1000);
setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D|-<\u0001'); }, 2000);
setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D/-<\u0001'); }, 3000);
setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D|-<\u0001'); }, 4000);
else {
// private message
console.log('private message');
}
}
else {
// private message
console.log('private message');
}
}));
}));
bot.addListener('pm', <irc.handlers.IPm> ((nick: string, message: string) => {
console.log('Got private message from %s: %s', nick, message);
}));
bot.addListener('pm', <irc.handlers.IPm> ((nick: string, message: string) => {
console.log('Got private message from %s: %s', nick, message);
}));
bot.addListener('join', <irc.handlers.IJoin> ((channel: string, who: string) => {
console.log('%s has joined %s', who, channel);
}));
bot.addListener('join', <irc.handlers.IJoin> ((channel: string, who: string) => {
console.log('%s has joined %s', who, channel);
}));
bot.addListener('part', <irc.handlers.IPart> ((channel: string, who: string, reason: string) => {
console.log('%s has left %s: %s', who, channel, reason);
}));
bot.addListener('part', <irc.handlers.IPart> ((channel: string, who: string, reason: string) => {
console.log('%s has left %s: %s', who, channel, reason);
}));
bot.addListener('kick', <irc.handlers.IKick> ((channel: string, who: string, by: string, reason: string) => {
console.log('%s was kicked from %s by %s: %s', who, channel, by, reason);
}));
bot.addListener('kick', <irc.handlers.IKick> ((channel: string, who: string, by: string, reason: string) => {
console.log('%s was kicked from %s by %s: %s', who, channel, by, reason);
}));
}
function test_secure() {
var options = true;
var bot = new irc.Client('chat.us.freenode.net', 'nodebot', {
port: 6697,
debug: true,
secure: options,
channels: ['#botwar']
});
}
function test_connect() {
var bot = new irc.Client('chat.us.freenode.net', 'nodebot', {
port: 6697,
autoConnect: false
});
bot.connect(5);
bot.connect(5, function() {});
bot.connect(function() {});
}
+7 -1
View File
@@ -194,7 +194,7 @@ declare module 'irc' {
* @param callback
*/
public connect(
retryCount?: number,
retryCount?: number | handlers.IRaw,
callback?: handlers.IRaw
): void;
@@ -228,6 +228,12 @@ declare module 'irc' {
*/
userName?: string;
/**
* IRC username
* @default ''
*/
password?: string;
/**
* IRC "real name"
* @default 'nodeJS IRC client'
+7 -7
View File
@@ -4,23 +4,23 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare enum RequestContext {
"audio", "beacon", "cspreport", "download", "embed", "eventsource",
"favicon", "fetch", "font", "form", "frame", "hyperlink", "iframe",
"image", "imageset", "import", "internal", "location", "manifest",
"object", "ping", "plugin", "prefetch", "script", "serviceworker",
"audio", "beacon", "cspreport", "download", "embed", "eventsource",
"favicon", "fetch", "font", "form", "frame", "hyperlink", "iframe",
"image", "imageset", "import", "internal", "location", "manifest",
"object", "ping", "plugin", "prefetch", "script", "serviceworker",
"sharedworker", "subresource", "style", "track", "video", "worker",
"xmlhttprequest", "xslt"
}
declare enum RequestMode { "same-origin", "no-cors", "cors" }
declare enum RequestCredentials { "omit", "same-origin", "include" }
declare enum RequestCache {
"default", "no-store", "reload", "no-cache", "force-cache",
declare enum RequestCache {
"default", "no-store", "reload", "no-cache", "force-cache",
"only-if-cached"
}
declare enum ResponseType { "basic", "cors", "default", "error", "opaque" }
declare type HeaderInit = Headers | Array<string>;
declare type BodyInit = Blob | FormData | string;
declare type BodyInit = ArrayBuffer | ArrayBufferView | Blob | FormData | string;
declare type RequestInfo = Request | string;
interface RequestInit {
@@ -0,0 +1,2 @@
/// <reference path="istanbul-middleware.d.ts" />
import i = require('istanbul-middleware');
+33
View File
@@ -0,0 +1,33 @@
// Type definitions for istanbul-middleware
// Project: https://www.npmjs.com/package/istanbul-middleware
// Definitions by: Hookclaw <https://github.com/hookclaw>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
declare module "istanbul-middleware" {
import * as express from "express";
type Matcher = (file:string)=> boolean;
type PostLoadHookFn = (file:any)=> {};
type PostLoadHook = (matcherfn:Matcher,transformer:any,verbose:boolean)=>PostLoadHookFn;
export function hookLoader(matcherOrRoot:Matcher|string, opts?:{
postLoadHook?:PostLoadHook,
verbose?:boolean
//and istanbul.Instrumenter(...opts)
}): void;
export function createHandler(opts?:{
resetOnGet?:boolean
}): any;
type ClientMatcher = (req:express.Request)=> boolean;
type PathTransformer = (req:express.Request)=> string;
export function createClientHandler(root:string,opts?:{
matcher?:ClientMatcher,
pathTransformer?:PathTransformer,
verbose?:boolean
}): any;
}
+774
View File
@@ -0,0 +1,774 @@
/// <reference path="joi.d.ts" />
/// <reference path="../node/node.d.ts" />
import Joi = require('joi');
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
var x: any = null;
var value: any = null;
var num: number = 0;
var str: string = '';
var bool: boolean = false;
var exp: RegExp = null;
var obj: Object = null;
var date: Date = null;
var bin: NodeBuffer = null;
var err: Error = null;
var func: Function = null;
var anyArr: any[] = [];
var numArr: number[] = [];
var strArr: string[] = [];
var boolArr: boolean[] = [];
var expArr: RegExp[] = [];
var objArr: Object[] = [];
var bufArr: NodeBuffer[] = [];
var errArr: Error[] = [];
var funcArr: Function[] = [];
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
var schema: Joi.Schema = null;
var anySchema: Joi.AnySchema<Joi.Schema> = null;
var numSchema: Joi.NumberSchema = null;
var strSchema: Joi.StringSchema = null;
var arrSchema: Joi.ArraySchema = null;
var boolSchema: Joi.BooleanSchema = null;
var binSchema: Joi.BinarySchema = null;
var dateSchema: Joi.DateSchema = null;
var funcSchema: Joi.FunctionSchema = null;
var objSchema: Joi.ObjectSchema = null;
var altSchema: Joi.AlternativesSchema = null;
var schemaArr: Joi.Schema[] = [];
var ref: Joi.Reference = null;
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
var validOpts: Joi.ValidationOptions = null;
validOpts = {abortEarly: bool};
validOpts = {convert: bool};
validOpts = {allowUnknown: bool};
validOpts = {skipFunctions: bool};
validOpts = {stripUnknown: bool};
validOpts = {language: bool};
validOpts = {presence: str};
validOpts = {context: obj};
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
var renOpts: Joi.RenameOptions = null;
renOpts = {alias: bool};
renOpts = {multiple: bool};
renOpts = {override: bool};
renOpts = {ignoreUndefined: bool};
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
var emailOpts: Joi.EmailOptions = null;
emailOpts = {errorLevel: num};
emailOpts = {errorLevel: bool};
emailOpts = {tldWhitelist: strArr};
emailOpts = {tldWhitelist: obj};
emailOpts = {minDomainAtoms: num};
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
var ipOpts: Joi.IpOptions = null;
ipOpts = {version: str};
ipOpts = {version: strArr};
ipOpts = {cidr: str};
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
var uriOpts: Joi.UriOptions = null;
uriOpts = {scheme: str};
uriOpts = {scheme: exp};
uriOpts = {scheme: strArr};
uriOpts = {scheme: expArr};
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
var whenOpts: Joi.WhenOptions<any> = null;
whenOpts = {is: x};
whenOpts = {is: schema, then: schema};
whenOpts = {is: schema, otherwise: schema};
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
var refOpts: Joi.ReferenceOptions = null;
refOpts = {separator: str};
refOpts = {contextPrefix: str};
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
var validErr: Joi.ValidationError = null;
var validErrItem: Joi.ValidationErrorItem;
validErrItem= {
message: str,
type: str,
path: str
};
validErrItem = {
message: str,
type: str,
path: str,
options: validOpts
};
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
schema = anySchema;
schema = numSchema;
schema = strSchema;
schema = arrSchema;
schema = boolSchema;
schema = binSchema;
schema = dateSchema;
schema = funcSchema;
schema = objSchema;
schema = ref;
anySchema = anySchema;
anySchema = numSchema;
anySchema = strSchema;
anySchema = arrSchema;
anySchema = boolSchema;
anySchema = binSchema;
anySchema = dateSchema;
anySchema = funcSchema;
anySchema = objSchema;
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
var schemaMap: Joi.SchemaMap = null;
schemaMap = {
a: numSchema,
b: strSchema
};
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
anySchema = Joi.any();
namespace common {
anySchema = anySchema.allow(x);
anySchema = anySchema.allow(x, x);
anySchema = anySchema.allow([x, x, x]);
anySchema = anySchema.valid(x);
anySchema = anySchema.valid(x, x);
anySchema = anySchema.valid([x, x, x]);
anySchema = anySchema.only(x);
anySchema = anySchema.only(x, x);
anySchema = anySchema.only([x, x, x]);
anySchema = anySchema.equal(x);
anySchema = anySchema.equal(x, x);
anySchema = anySchema.equal([x, x, x]);
anySchema = anySchema.invalid(x);
anySchema = anySchema.invalid(x, x);
anySchema = anySchema.invalid([x, x, x]);
anySchema = anySchema.disallow(x);
anySchema = anySchema.disallow(x, x);
anySchema = anySchema.disallow([x, x, x]);
anySchema = anySchema.not(x);
anySchema = anySchema.not(x, x);
anySchema = anySchema.not([x, x, x]);
anySchema = anySchema.default();
anySchema = anySchema.default(x);
anySchema = anySchema.default(x, str);
anySchema = anySchema.required();
anySchema = anySchema.optional();
anySchema = anySchema.forbidden();
anySchema = anySchema.strip();
anySchema = anySchema.description(str);
anySchema = anySchema.notes(str);
anySchema = anySchema.notes(strArr);
anySchema = anySchema.tags(str);
anySchema = anySchema.tags(strArr);
anySchema = anySchema.meta(obj);
anySchema = anySchema.example(obj);
anySchema = anySchema.unit(str);
anySchema = anySchema.options(validOpts);
anySchema = anySchema.strict();
anySchema = anySchema.strict(bool);
anySchema = anySchema.concat(x);
altSchema = anySchema.when(str, whenOpts);
altSchema = anySchema.when(ref, whenOpts);
anySchema = anySchema.label(str);
anySchema = anySchema.raw();
anySchema = anySchema.raw(bool);
anySchema = anySchema.empty();
anySchema = anySchema.empty(str);
anySchema = anySchema.empty(anySchema);
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
arrSchema = Joi.array();
arrSchema = arrSchema.sparse();
arrSchema = arrSchema.sparse(bool);
arrSchema = arrSchema.single();
arrSchema = arrSchema.single(bool);
arrSchema = arrSchema.min(num);
arrSchema = arrSchema.max(num);
arrSchema = arrSchema.length(num);
arrSchema = arrSchema.unique();
arrSchema = arrSchema.items(numSchema);
arrSchema = arrSchema.items(numSchema, strSchema);
arrSchema = arrSchema.items([numSchema, strSchema]);
// - - - - - - - -
namespace common_copy_paste {
// use search & replace from any
arrSchema = arrSchema.allow(x);
arrSchema = arrSchema.allow(x, x);
arrSchema = arrSchema.allow([x, x, x]);
arrSchema = arrSchema.valid(x);
arrSchema = arrSchema.valid(x, x);
arrSchema = arrSchema.valid([x, x, x]);
arrSchema = arrSchema.only(x);
arrSchema = arrSchema.only(x, x);
arrSchema = arrSchema.only([x, x, x]);
arrSchema = arrSchema.equal(x);
arrSchema = arrSchema.equal(x, x);
arrSchema = arrSchema.equal([x, x, x]);
arrSchema = arrSchema.invalid(x);
arrSchema = arrSchema.invalid(x, x);
arrSchema = arrSchema.invalid([x, x, x]);
arrSchema = arrSchema.disallow(x);
arrSchema = arrSchema.disallow(x, x);
arrSchema = arrSchema.disallow([x, x, x]);
arrSchema = arrSchema.not(x);
arrSchema = arrSchema.not(x, x);
arrSchema = arrSchema.not([x, x, x]);
arrSchema = arrSchema.default(x);
arrSchema = arrSchema.required();
arrSchema = arrSchema.optional();
arrSchema = arrSchema.forbidden();
arrSchema = arrSchema.description(str);
arrSchema = arrSchema.notes(str);
arrSchema = arrSchema.notes(strArr);
arrSchema = arrSchema.tags(str);
arrSchema = arrSchema.tags(strArr);
arrSchema = arrSchema.meta(obj);
arrSchema = arrSchema.example(obj);
arrSchema = arrSchema.unit(str);
arrSchema = arrSchema.options(validOpts);
arrSchema = arrSchema.strict();
arrSchema = arrSchema.concat(x);
altSchema = arrSchema.when(str, whenOpts);
altSchema = arrSchema.when(ref, whenOpts);
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
boolSchema = Joi.bool();
boolSchema = Joi.boolean();
namespace common_copy_paste {
boolSchema = boolSchema.allow(x);
boolSchema = boolSchema.allow(x, x);
boolSchema = boolSchema.allow([x, x, x]);
boolSchema = boolSchema.valid(x);
boolSchema = boolSchema.valid(x, x);
boolSchema = boolSchema.valid([x, x, x]);
boolSchema = boolSchema.only(x);
boolSchema = boolSchema.only(x, x);
boolSchema = boolSchema.only([x, x, x]);
boolSchema = boolSchema.equal(x);
boolSchema = boolSchema.equal(x, x);
boolSchema = boolSchema.equal([x, x, x]);
boolSchema = boolSchema.invalid(x);
boolSchema = boolSchema.invalid(x, x);
boolSchema = boolSchema.invalid([x, x, x]);
boolSchema = boolSchema.disallow(x);
boolSchema = boolSchema.disallow(x, x);
boolSchema = boolSchema.disallow([x, x, x]);
boolSchema = boolSchema.not(x);
boolSchema = boolSchema.not(x, x);
boolSchema = boolSchema.not([x, x, x]);
boolSchema = boolSchema.default(x);
boolSchema = boolSchema.required();
boolSchema = boolSchema.optional();
boolSchema = boolSchema.forbidden();
boolSchema = boolSchema.description(str);
boolSchema = boolSchema.notes(str);
boolSchema = boolSchema.notes(strArr);
boolSchema = boolSchema.tags(str);
boolSchema = boolSchema.tags(strArr);
boolSchema = boolSchema.meta(obj);
boolSchema = boolSchema.example(obj);
boolSchema = boolSchema.unit(str);
boolSchema = boolSchema.options(validOpts);
boolSchema = boolSchema.strict();
boolSchema = boolSchema.concat(x);
altSchema = boolSchema.when(str, whenOpts);
altSchema = boolSchema.when(ref, whenOpts);
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
binSchema = Joi.binary();
binSchema = binSchema.encoding(str);
binSchema = binSchema.min(num);
binSchema = binSchema.max(num);
binSchema = binSchema.length(num);
namespace common {
binSchema = binSchema.allow(x);
binSchema = binSchema.allow(x, x);
binSchema = binSchema.allow([x, x, x]);
binSchema = binSchema.valid(x);
binSchema = binSchema.valid(x, x);
binSchema = binSchema.valid([x, x, x]);
binSchema = binSchema.only(x);
binSchema = binSchema.only(x, x);
binSchema = binSchema.only([x, x, x]);
binSchema = binSchema.equal(x);
binSchema = binSchema.equal(x, x);
binSchema = binSchema.equal([x, x, x]);
binSchema = binSchema.invalid(x);
binSchema = binSchema.invalid(x, x);
binSchema = binSchema.invalid([x, x, x]);
binSchema = binSchema.disallow(x);
binSchema = binSchema.disallow(x, x);
binSchema = binSchema.disallow([x, x, x]);
binSchema = binSchema.not(x);
binSchema = binSchema.not(x, x);
binSchema = binSchema.not([x, x, x]);
binSchema = binSchema.default(x);
binSchema = binSchema.required();
binSchema = binSchema.optional();
binSchema = binSchema.forbidden();
binSchema = binSchema.description(str);
binSchema = binSchema.notes(str);
binSchema = binSchema.notes(strArr);
binSchema = binSchema.tags(str);
binSchema = binSchema.tags(strArr);
binSchema = binSchema.meta(obj);
binSchema = binSchema.example(obj);
binSchema = binSchema.unit(str);
binSchema = binSchema.options(validOpts);
binSchema = binSchema.strict();
binSchema = binSchema.concat(x);
altSchema = binSchema.when(str, whenOpts);
altSchema = binSchema.when(ref, whenOpts);
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
dateSchema = Joi.date();
dateSchema = dateSchema.min(date);
dateSchema = dateSchema.max(date);
dateSchema = dateSchema.min(str);
dateSchema = dateSchema.max(str);
dateSchema = dateSchema.min(num);
dateSchema = dateSchema.max(num);
dateSchema = dateSchema.min(ref);
dateSchema = dateSchema.max(ref);
dateSchema = dateSchema.format(str);
dateSchema = dateSchema.format(strArr);
dateSchema = dateSchema.iso();
namespace common {
dateSchema = dateSchema.allow(x);
dateSchema = dateSchema.allow(x, x);
dateSchema = dateSchema.allow([x, x, x]);
dateSchema = dateSchema.valid(x);
dateSchema = dateSchema.valid(x, x);
dateSchema = dateSchema.valid([x, x, x]);
dateSchema = dateSchema.only(x);
dateSchema = dateSchema.only(x, x);
dateSchema = dateSchema.only([x, x, x]);
dateSchema = dateSchema.equal(x);
dateSchema = dateSchema.equal(x, x);
dateSchema = dateSchema.equal([x, x, x]);
dateSchema = dateSchema.invalid(x);
dateSchema = dateSchema.invalid(x, x);
dateSchema = dateSchema.invalid([x, x, x]);
dateSchema = dateSchema.disallow(x);
dateSchema = dateSchema.disallow(x, x);
dateSchema = dateSchema.disallow([x, x, x]);
dateSchema = dateSchema.not(x);
dateSchema = dateSchema.not(x, x);
dateSchema = dateSchema.not([x, x, x]);
dateSchema = dateSchema.default(x);
dateSchema = dateSchema.required();
dateSchema = dateSchema.optional();
dateSchema = dateSchema.forbidden();
dateSchema = dateSchema.description(str);
dateSchema = dateSchema.notes(str);
dateSchema = dateSchema.notes(strArr);
dateSchema = dateSchema.tags(str);
dateSchema = dateSchema.tags(strArr);
dateSchema = dateSchema.meta(obj);
dateSchema = dateSchema.example(obj);
dateSchema = dateSchema.unit(str);
dateSchema = dateSchema.options(validOpts);
dateSchema = dateSchema.strict();
dateSchema = dateSchema.concat(x);
altSchema = dateSchema.when(str, whenOpts);
altSchema = dateSchema.when(ref, whenOpts);
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
funcSchema = Joi.func();
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
numSchema = Joi.number();
numSchema = numSchema.min(num);
numSchema = numSchema.min(ref);
numSchema = numSchema.max(num);
numSchema = numSchema.max(ref);
numSchema = numSchema.greater(num);
numSchema = numSchema.greater(ref);
numSchema = numSchema.less(num);
numSchema = numSchema.less(ref);
numSchema = numSchema.integer();
numSchema = numSchema.precision(num);
numSchema = numSchema.multiple(num);
numSchema = numSchema.positive();
numSchema = numSchema.negative();
namespace common {
numSchema = numSchema.allow(x);
numSchema = numSchema.allow(x, x);
numSchema = numSchema.allow([x, x, x]);
numSchema = numSchema.valid(x);
numSchema = numSchema.valid(x, x);
numSchema = numSchema.valid([x, x, x]);
numSchema = numSchema.only(x);
numSchema = numSchema.only(x, x);
numSchema = numSchema.only([x, x, x]);
numSchema = numSchema.equal(x);
numSchema = numSchema.equal(x, x);
numSchema = numSchema.equal([x, x, x]);
numSchema = numSchema.invalid(x);
numSchema = numSchema.invalid(x, x);
numSchema = numSchema.invalid([x, x, x]);
numSchema = numSchema.disallow(x);
numSchema = numSchema.disallow(x, x);
numSchema = numSchema.disallow([x, x, x]);
numSchema = numSchema.not(x);
numSchema = numSchema.not(x, x);
numSchema = numSchema.not([x, x, x]);
numSchema = numSchema.default(x);
numSchema = numSchema.required();
numSchema = numSchema.optional();
numSchema = numSchema.forbidden();
numSchema = numSchema.description(str);
numSchema = numSchema.notes(str);
numSchema = numSchema.notes(strArr);
numSchema = numSchema.tags(str);
numSchema = numSchema.tags(strArr);
numSchema = numSchema.meta(obj);
numSchema = numSchema.example(obj);
numSchema = numSchema.unit(str);
numSchema = numSchema.options(validOpts);
numSchema = numSchema.strict();
numSchema = numSchema.concat(x);
altSchema = numSchema.when(str, whenOpts);
altSchema = numSchema.when(ref, whenOpts);
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
objSchema = Joi.object();
objSchema = Joi.object(schemaMap);
objSchema = objSchema.keys();
objSchema = objSchema.keys(schemaMap);
objSchema = objSchema.min(num);
objSchema = objSchema.max(num);
objSchema = objSchema.length(num);
objSchema = objSchema.pattern(exp, schema);
objSchema = objSchema.and(str);
objSchema = objSchema.and(str, str);
objSchema = objSchema.and(str, str, str);
objSchema = objSchema.and(strArr);
objSchema = objSchema.nand(str);
objSchema = objSchema.nand(str, str);
objSchema = objSchema.nand(str, str, str);
objSchema = objSchema.nand(strArr);
objSchema = objSchema.or(str);
objSchema = objSchema.or(str, str);
objSchema = objSchema.or(str, str, str);
objSchema = objSchema.or(strArr);
objSchema = objSchema.xor(str);
objSchema = objSchema.xor(str, str);
objSchema = objSchema.xor(str, str, str);
objSchema = objSchema.xor(strArr);
objSchema = objSchema.with(str, str);
objSchema = objSchema.with(str, strArr);
objSchema = objSchema.without(str, str);
objSchema = objSchema.without(str, strArr);
objSchema = objSchema.rename(str, str);
objSchema = objSchema.rename(str, str, renOpts);
objSchema = objSchema.assert(str, schema);
objSchema = objSchema.assert(str, schema, str);
objSchema = objSchema.assert(ref, schema);
objSchema = objSchema.assert(ref, schema, str);
objSchema = objSchema.unknown();
objSchema = objSchema.unknown(bool);
objSchema = objSchema.type(func);
objSchema = objSchema.type(func, str);
objSchema = objSchema.requiredKeys(str);
objSchema = objSchema.requiredKeys(str, str);
objSchema = objSchema.requiredKeys(strArr);
objSchema = objSchema.optionalKeys(str);
objSchema = objSchema.optionalKeys(str, str);
objSchema = objSchema.optionalKeys(strArr);
namespace common {
objSchema = objSchema.allow(x);
objSchema = objSchema.allow(x, x);
objSchema = objSchema.allow([x, x, x]);
objSchema = objSchema.valid(x);
objSchema = objSchema.valid(x, x);
objSchema = objSchema.valid([x, x, x]);
objSchema = objSchema.only(x);
objSchema = objSchema.only(x, x);
objSchema = objSchema.only([x, x, x]);
objSchema = objSchema.equal(x);
objSchema = objSchema.equal(x, x);
objSchema = objSchema.equal([x, x, x]);
objSchema = objSchema.invalid(x);
objSchema = objSchema.invalid(x, x);
objSchema = objSchema.invalid([x, x, x]);
objSchema = objSchema.disallow(x);
objSchema = objSchema.disallow(x, x);
objSchema = objSchema.disallow([x, x, x]);
objSchema = objSchema.not(x);
objSchema = objSchema.not(x, x);
objSchema = objSchema.not([x, x, x]);
objSchema = objSchema.default(x);
objSchema = objSchema.required();
objSchema = objSchema.optional();
objSchema = objSchema.forbidden();
objSchema = objSchema.description(str);
objSchema = objSchema.notes(str);
objSchema = objSchema.notes(strArr);
objSchema = objSchema.tags(str);
objSchema = objSchema.tags(strArr);
objSchema = objSchema.meta(obj);
objSchema = objSchema.example(obj);
objSchema = objSchema.unit(str);
objSchema = objSchema.options(validOpts);
objSchema = objSchema.strict();
objSchema = objSchema.concat(x);
altSchema = objSchema.when(str, whenOpts);
altSchema = objSchema.when(ref, whenOpts);
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
strSchema = Joi.string();
strSchema = strSchema.insensitive();
strSchema = strSchema.min(num);
strSchema = strSchema.min(num, str);
strSchema = strSchema.min(ref);
strSchema = strSchema.min(ref, str);
strSchema = strSchema.max(num);
strSchema = strSchema.max(num, str);
strSchema = strSchema.max(ref);
strSchema = strSchema.max(ref, str);
strSchema = strSchema.creditCard();
strSchema = strSchema.length(num);
strSchema = strSchema.length(num, str);
strSchema = strSchema.length(ref);
strSchema = strSchema.length(ref, str);
strSchema = strSchema.regex(exp);
strSchema = strSchema.regex(exp, str);
strSchema = strSchema.replace(exp, str);
strSchema = strSchema.replace(str, str);
strSchema = strSchema.alphanum();
strSchema = strSchema.token();
strSchema = strSchema.email();
strSchema = strSchema.email(emailOpts);
strSchema = strSchema.ip();
strSchema = strSchema.ip(ipOpts);
strSchema = strSchema.uri();
strSchema = strSchema.uri(uriOpts);
strSchema = strSchema.guid();
strSchema = strSchema.hex();
strSchema = strSchema.hostname();
strSchema = strSchema.isoDate();
strSchema = strSchema.lowercase();
strSchema = strSchema.uppercase();
strSchema = strSchema.trim();
namespace common {
strSchema = strSchema.allow(x);
strSchema = strSchema.allow(x, x);
strSchema = strSchema.allow([x, x, x]);
strSchema = strSchema.valid(x);
strSchema = strSchema.valid(x, x);
strSchema = strSchema.valid([x, x, x]);
strSchema = strSchema.only(x);
strSchema = strSchema.only(x, x);
strSchema = strSchema.only([x, x, x]);
strSchema = strSchema.equal(x);
strSchema = strSchema.equal(x, x);
strSchema = strSchema.equal([x, x, x]);
strSchema = strSchema.invalid(x);
strSchema = strSchema.invalid(x, x);
strSchema = strSchema.invalid([x, x, x]);
strSchema = strSchema.disallow(x);
strSchema = strSchema.disallow(x, x);
strSchema = strSchema.disallow([x, x, x]);
strSchema = strSchema.not(x);
strSchema = strSchema.not(x, x);
strSchema = strSchema.not([x, x, x]);
strSchema = strSchema.default(x);
strSchema = strSchema.required();
strSchema = strSchema.optional();
strSchema = strSchema.forbidden();
strSchema = strSchema.description(str);
strSchema = strSchema.notes(str);
strSchema = strSchema.notes(strArr);
strSchema = strSchema.tags(str);
strSchema = strSchema.tags(strArr);
strSchema = strSchema.meta(obj);
strSchema = strSchema.example(obj);
strSchema = strSchema.unit(str);
strSchema = strSchema.options(validOpts);
strSchema = strSchema.strict();
strSchema = strSchema.concat(x);
altSchema = strSchema.when(str, whenOpts);
altSchema = strSchema.when(ref, whenOpts);
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
schema = Joi.alternatives(schemaArr);
schema = Joi.alternatives(schema, anySchema, boolSchema);
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
Joi.validate(value, obj);
Joi.validate(value, schema);
Joi.validate(value, schema, validOpts);
Joi.validate(value, schema, validOpts, (err, value) => {
x = value;
str = err.message;
str = err.details[0].path;
str = err.details[0].message;
str = err.details[0].type;
});
Joi.validate(value, schema, (err, value) => {
x = value;
str = err.message;
str = err.details[0].path;
str = err.details[0].message;
str = err.details[0].type;
});
// variant
Joi.validate(num, schema, validOpts, (err, value) => {
num = value;
});
// plain opts
Joi.validate(value, {});
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
schema = Joi.compile(obj);
Joi.assert(obj, schema);
Joi.assert(obj, schema, str);
Joi.assert(obj, schema, err);
ref = Joi.ref(str, refOpts);
ref = Joi.ref(str);
+778
View File
@@ -0,0 +1,778 @@
// Type definitions for joi v6.5.0
// Project: https://github.com/spumko/joi
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>, Laurence Dougal Myers <https://github.com/laurence-myers>, Christopher Glantschnig <https://github.com/cglantschnig>, David Broder-Rodgers <https://github.com/DavidBR-SW>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TODO express type of Schema in a type-parameter (.default, .valid, .example etc)
declare module 'joi' {
export interface ValidationOptions {
/**
* when true, stops validation on the first error, otherwise returns all the errors found. Defaults to true.
*/
abortEarly?: boolean;
/**
* when true, attempts to cast values to the required types (e.g. a string to a number). Defaults to true.
*/
convert?: boolean;
/**
* when true, allows object to contain unknown keys which are ignored. Defaults to false.
*/
allowUnknown?: boolean;
/**
* when true, ignores unknown keys with a function value. Defaults to false.
*/
skipFunctions?: boolean;
/**
* when true, unknown keys are deleted (only when value is an object). Defaults to false.
*/
stripUnknown?: boolean;
/**
* overrides individual error messages. Defaults to no override ({}).
*/
language?: Object;
/**
* sets the default presence requirements. Supported modes: 'optional', 'required', and 'forbidden'. Defaults to 'optional'.
*/
presence?: string;
/**
* provides an external data set to be used in references
*/
context?: Object;
}
export interface RenameOptions {
/**
* if true, does not delete the old key name, keeping both the new and old keys in place. Defaults to false.
*/
alias?: boolean;
/**
* if true, allows renaming multiple keys to the same destination where the last rename wins. Defaults to false.
*/
multiple?: boolean;
/**
* if true, allows renaming a key over an existing key. Defaults to false.
*/
override?: boolean;
/**
* if true, skip renaming of a key if it's undefined. Defaults to false.
*/
ignoreUndefined?: boolean;
}
export interface EmailOptions {
/**
* Numerical threshold at which an email address is considered invalid
*/
errorLevel?: number | boolean;
/**
* Specifies a list of acceptable TLDs.
*/
tldWhitelist?: string[] | Object;
/**
* Number of atoms required for the domain. Be careful since some domains, such as io, directly allow email.
*/
minDomainAtoms?: number;
}
export interface IpOptions {
/**
* One or more IP address versions to validate against. Valid values: ipv4, ipv6, ipvfuture
*/
version ?: string | string[];
/**
* Used to determine if a CIDR is allowed or not. Valid values: optional, required, forbidden
*/
cidr?: string;
}
export interface UriOptions {
/**
* Specifies one or more acceptable Schemes, should only include the scheme name.
* Can be an Array or String (strings are automatically escaped for use in a Regular Expression).
*/
scheme ?: string | RegExp | Array<string | RegExp>;
}
export interface WhenOptions<T> {
/**
* the required condition joi type.
*/
is: T;
/**
* the alternative schema type if the condition is true. Required if otherwise is missing.
*/
then?: Schema;
/**
* the alternative schema type if the condition is false. Required if then is missing
*/
otherwise?: Schema;
}
export interface ReferenceOptions {
separator?: string;
contextPrefix?: string;
}
export interface IPOptions {
version?: Array<string>;
cidr?: string
}
export interface ValidationError extends Error {
message: string;
details: ValidationErrorItem[];
simple(): string;
annotated(): string;
}
export interface ValidationErrorItem {
message: string;
type: string;
path: string;
options?: ValidationOptions;
}
export interface ValidationResult<T> {
error: ValidationError;
value: T;
}
export interface SchemaMap {
[key: string]: Schema;
}
export interface Schema extends AnySchema<Schema> {
}
export interface Reference extends Schema {
}
export interface AnySchema<T extends AnySchema<Schema>> {
/**
* Whitelists a value
*/
allow(value: any, ...values: any[]): T;
allow(values: any[]): T;
/**
* Adds the provided values into the allowed whitelist and marks them as the only valid values allowed.
*/
valid(value: any, ...values: any[]): T;
valid(values: any[]): T;
only(value: any, ...values : any[]): T;
only(values: any[]): T;
equal(value: any, ...values : any[]): T;
equal(values: any[]): T;
/**
* Blacklists a value
*/
invalid(value: any, ...values: any[]): T;
invalid(values: any[]): T;
disallow(value: any, ...values : any[]): T;
disallow(values: any[]): T;
not(value: any, ...values : any[]): T;
not(values: any[]): T;
/**
* Marks a key as required which will not allow undefined as value. All keys are optional by default.
*/
required(): T;
/**
* Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default.
*/
optional(): T;
/**
* Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys.
*/
forbidden(): T;
/**
* Marks a key to be removed from a resulting object or array after validation. Used to sanitize output.
*/
strip(): T;
/**
* Annotates the key
*/
description(desc: string): T;
/**
* Annotates the key
*/
notes(notes: string): T;
notes(notes: string[]): T;
/**
* Annotates the key
*/
tags(notes: string): T;
tags(notes: string[]): T;
/**
* Attaches metadata to the key.
*/
meta(meta: Object): T;
/**
* Annotates the key with an example value, must be valid.
*/
example(value: any): T;
/**
* Annotates the key with an unit name.
*/
unit(name: string): T;
/**
* Overrides the global validate() options for the current key and any sub-key.
*/
options(options: ValidationOptions): T;
/**
* Sets the options.convert options to false which prevent type casting for the current key and any child keys.
*/
strict(isStrict?: boolean): T;
/**
* Sets a default value if the original value is undefined.
* @param value - the value.
* value supports references.
* value may also be a function which returns the default value.
* If value is specified as a function that accepts a single parameter, that parameter will be a context
* object that can be used to derive the resulting value. This clones the object however, which incurs some
* overhead so if you don't need access to the context define your method so that it does not accept any
* parameters.
* Without any value, default has no effect, except for object that will then create nested defaults
* (applying inner defaults of that object).
*
* Note that if value is an object, any changes to the object after default() is called will change the
* reference and any future assignment.
*
* Additionally, when specifying a method you must either have a description property on your method or the
* second parameter is required.
*/
default(value: any, description?: string): T;
default(): T;
/**
* Returns a new type that is the result of adding the rules of one type to another.
*/
concat(schema: T): T;
/**
* Converts the type into an alternatives type where the conditions are merged into the type definition where:
*/
when<U>(ref: string, options: WhenOptions<U>): AlternativesSchema;
when<U>(ref: Reference, options: WhenOptions<U>): AlternativesSchema;
/**
* Overrides the key name in error messages.
*/
label(name: string): T;
/**
* Outputs the original untouched value instead of the casted value.
*/
raw(isRaw?: boolean): T;
/**
* Considers anything that matches the schema to be empty (undefined).
* @param schema - any object or joi schema to match. An undefined schema unsets that rule.
*/
empty(schema?: any) : T;
}
export interface BooleanSchema extends AnySchema<BooleanSchema> {
}
export interface NumberSchema extends AnySchema<NumberSchema> {
/**
* Specifies the minimum value.
* It can also be a reference to another field.
*/
min(limit: number): NumberSchema;
min(limit: Reference): NumberSchema;
/**
* Specifies the maximum value.
* It can also be a reference to another field.
*/
max(limit: number): NumberSchema;
max(limit: Reference): NumberSchema;
/**
* Specifies that the value must be greater than limit.
* It can also be a reference to another field.
*/
greater(limit: number): NumberSchema;
greater(limit: Reference): NumberSchema;
/**
* Specifies that the value must be less than limit.
* It can also be a reference to another field.
*/
less(limit: number): NumberSchema;
less(limit: Reference): NumberSchema;
/**
* Requires the number to be an integer (no floating point).
*/
integer(): NumberSchema;
/**
* Specifies the maximum number of decimal places where:
* limit - the maximum number of decimal places allowed.
*/
precision(limit: number): NumberSchema;
/**
* Specifies that the value must be a multiple of base.
*/
multiple(base: number): NumberSchema;
/**
* Requires the number to be positive.
*/
positive(): NumberSchema;
/**
* Requires the number to be negative.
*/
negative(): NumberSchema;
}
export interface StringSchema extends AnySchema<StringSchema> {
/**
* Allows the value to match any whitelist of blacklist item in a case insensitive comparison.
*/
insensitive(): StringSchema;
/**
* Specifies the minimum number string characters.
* @param limit - the minimum number of string characters required. It can also be a reference to another field.
* @param encoding - if specified, the string length is calculated in bytes using the provided encoding.
*/
min(limit: number, encoding?: string): StringSchema;
min(limit: Reference, encoding?: string): StringSchema;
/**
* Specifies the maximum number of string characters.
* @param limit - the maximum number of string characters allowed. It can also be a reference to another field.
* @param encoding - if specified, the string length is calculated in bytes using the provided encoding.
*/
max(limit: number, encoding?: string): StringSchema;
max(limit: Reference, encoding?: string): StringSchema;
/**
* Requires the number to be a credit card number (Using Lunh Algorithm).
*/
creditCard(): StringSchema;
/**
* Specifies the exact string length required
* @param limit - the required string length. It can also be a reference to another field.
* @param encoding - if specified, the string length is calculated in bytes using the provided encoding.
*/
length(limit: number, encoding?: string): StringSchema;
length(limit: Reference, encoding?: string): StringSchema;
/**
* Defines a regular expression rule.
* @param pattern - a regular expression object the string value must match against.
* @param name - optional name for patterns (useful with multiple patterns). Defaults to 'required'.
*/
regex(pattern: RegExp, name?: string): StringSchema;
/**
* Replace characters matching the given pattern with the specified replacement string where:
* @param pattern - a regular expression object to match against, or a string of which all occurrences will be replaced.
* @param replacement - the string that will replace the pattern.
*/
replace(pattern: RegExp, replacement: string): StringSchema;
replace(pattern: string, replacement: string): StringSchema;
/**
* Requires the string value to only contain a-z, A-Z, and 0-9.
*/
alphanum(): StringSchema;
/**
* Requires the string value to only contain a-z, A-Z, 0-9, and underscore _.
*/
token(): StringSchema;
/**
* Requires the string value to be a valid email address.
*/
email(options?: EmailOptions): StringSchema;
/**
* Requires the string value to be a valid ip address.
*/
ip(options?: IpOptions): StringSchema;
/**
* Requires the string value to be a valid RFC 3986 URI.
*/
uri(options?: UriOptions): StringSchema;
/**
* Requires the string value to be a valid GUID.
*/
guid(): StringSchema;
/**
* Requires the string value to be a valid hexadecimal string.
*/
hex(): StringSchema;
/**
* Requires the string value to be a valid hostname as per RFC1123.
*/
hostname(): StringSchema;
/**
* Requires the string value to be in valid ISO 8601 date format.
*/
isoDate(): StringSchema;
/**
* Requires the string value to be all lowercase. If the validation convert option is on (enabled by default), the string will be forced to lowercase.
*/
lowercase(): StringSchema;
/**
* Requires the string value to be all uppercase. If the validation convert option is on (enabled by default), the string will be forced to uppercase.
*/
uppercase(): StringSchema;
/**
* Requires the string value to contain no whitespace before or after. If the validation convert option is on (enabled by default), the string will be trimmed.
*/
trim(): StringSchema;
}
export interface ArraySchema extends AnySchema<ArraySchema> {
/**
* Allow this array to be sparse.
* enabled can be used with a falsy value to go back to the default behavior.
*/
sparse(enabled?: any): ArraySchema;
/**
* Allow single values to be checked against rules as if it were provided as an array.
* enabled can be used with a falsy value to go back to the default behavior.
*/
single(enabled?: any): ArraySchema;
/**
* List the types allowed for the array values.
* type can be an array of values, or multiple values can be passed as individual arguments.
* If a given type is .required() then there must be a matching item in the array.
* If a type is .forbidden() then it cannot appear in the array.
* Required items can be added multiple times to signify that multiple items must be found.
* Errors will contain the number of items that didn't match.
* Any unmatched item having a label will be mentioned explicitly.
*
* @param type - a joi schema object to validate each array item against.
*/
items(type: Schema, ...types: Schema[]): ArraySchema;
items(types: Schema[]): ArraySchema;
/**
* Specifies the minimum number of items in the array.
*/
min(limit: number): ArraySchema;
/**
* Specifies the maximum number of items in the array.
*/
max(limit: number): ArraySchema;
/**
* Specifies the exact number of items in the array.
*/
length(limit: number): ArraySchema;
/**
* Requires the array values to be unique.
* Be aware that a deep equality is performed on elements of the array having a type of object,
* a performance penalty is to be expected for this kind of operation.
*/
unique(): ArraySchema;
}
export interface ObjectSchema extends AnySchema<ObjectSchema> {
/**
* Sets the allowed object keys.
*/
keys(schema?: SchemaMap): ObjectSchema;
/**
* Specifies the minimum number of keys in the object.
*/
min(limit: number): ObjectSchema;
/**
* Specifies the maximum number of keys in the object.
*/
max(limit: number): ObjectSchema;
/**
* Specifies the exact number of keys in the object.
*/
length(limit: number): ObjectSchema;
/**
* Specify validation rules for unknown keys matching a pattern.
*/
pattern(regex: RegExp, schema: Schema): ObjectSchema;
/**
* Defines an all-or-nothing relationship between keys where if one of the peers is present, all of them are required as well.
* @param peers - the key names of which if one present, all are required. peers can be a single string value,
* an array of string values, or each peer provided as an argument.
*/
and(peer1: string, ...peers: string[]): ObjectSchema;
and(peers: string[]): ObjectSchema;
/**
* Defines a relationship between keys where not all peers can be present at the same time.
* @param peers - the key names of which if one present, the others may not all be present.
* peers can be a single string value, an array of string values, or each peer provided as an argument.
*/
nand(peer1: string, ...peers: string[]): ObjectSchema;
nand(peers: string[]): ObjectSchema;
/**
* Defines a relationship between keys where one of the peers is required (and more than one is allowed).
*/
or(peer1: string, ...peers: string[]): ObjectSchema;
or(peers: string[]): ObjectSchema;
/**
* Defines an exclusive relationship between a set of keys. one of them is required but not at the same time where:
*/
xor(peer1: string, ...peers: string[]): ObjectSchema;
xor(peers: string[]): ObjectSchema;
/**
* Requires the presence of other keys whenever the specified key is present.
*/
with(key: string, peers: string): ObjectSchema;
with(key: string, peers: string[]): ObjectSchema;
/**
* Forbids the presence of other keys whenever the specified is present.
*/
without(key: string, peers: string): ObjectSchema;
without(key: string, peers: string[]): ObjectSchema;
/**
* Renames a key to another name (deletes the renamed key).
*/
rename(from: string, to: string, options?: RenameOptions): ObjectSchema;
/**
* Verifies an assertion where.
*/
assert(ref: string, schema: Schema, message?: string): ObjectSchema;
assert(ref: Reference, schema: Schema, message?: string): ObjectSchema;
/**
* Overrides the handling of unknown keys for the scope of the current object only (does not apply to children).
*/
unknown(allow?: boolean): ObjectSchema;
/**
* Requires the object to be an instance of a given constructor.
*
* @param constructor - the constructor function that the object must be an instance of.
* @param name - an alternate name to use in validation errors. This is useful when the constructor function does not have a name.
*/
type(constructor: Function, name?: string): ObjectSchema;
/**
* Sets the specified children to required.
*
* @param children - can be a single string value, an array of string values, or each child provided as an argument.
*
* var schema = Joi.object().keys({ a: { b: Joi.number() }, c: { d: Joi.string() } });
* var requiredSchema = schema.requiredKeys('', 'a.b', 'c', 'c.d');
*
* Note that in this example '' means the current object, a is not required but b is, as well as c and d.
*/
requiredKeys(children: string): ObjectSchema;
requiredKeys(children: string[]): ObjectSchema;
requiredKeys(child:string, ...children: string[]): ObjectSchema;
/**
* Sets the specified children to optional.
*
* @param children - can be a single string value, an array of string values, or each child provided as an argument.
*
* The behavior is exactly the same as requiredKeys.
*/
optionalKeys(children: string): ObjectSchema;
optionalKeys(children: string[]): ObjectSchema;
optionalKeys(child:string, ...children: string[]): ObjectSchema;
}
export interface BinarySchema extends AnySchema<BinarySchema> {
/**
* Sets the string encoding format if a string input is converted to a buffer.
*/
encoding(encoding: string): BinarySchema;
/**
* Specifies the minimum length of the buffer.
*/
min(limit: number): BinarySchema;
/**
* Specifies the maximum length of the buffer.
*/
max(limit: number): BinarySchema;
/**
* Specifies the exact length of the buffer:
*/
length(limit: number): BinarySchema;
}
export interface DateSchema extends AnySchema<DateSchema> {
/**
* Specifies the oldest date allowed.
* Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date,
* allowing to explicitly ensure a date is either in the past or in the future.
* It can also be a reference to another field.
*/
min(date: Date): DateSchema;
min(date: number): DateSchema;
min(date: string): DateSchema;
min(date: Reference): DateSchema;
/**
* Specifies the latest date allowed.
* Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date,
* allowing to explicitly ensure a date is either in the past or in the future.
* It can also be a reference to another field.
*/
max(date: Date): DateSchema;
max(date: number): DateSchema;
max(date: string): DateSchema;
max(date: Reference): DateSchema;
/**
* Specifies the allowed date format:
* @param format - string or array of strings that follow the moment.js format.
*/
format(format: string): DateSchema;
format(format: string[]): DateSchema;
/**
* Requires the string value to be in valid ISO 8601 date format.
*/
iso(): DateSchema;
}
export interface FunctionSchema extends AnySchema<FunctionSchema> {
}
export interface AlternativesSchema extends AnySchema<FunctionSchema> {
try(schemas: Schema[]): AlternativesSchema;
when<T>(ref: string, options: WhenOptions<T>): AlternativesSchema;
when<T>(ref: Reference, options: WhenOptions<T>): AlternativesSchema;
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
/**
* Generates a schema object that matches any data type.
*/
export function any(): Schema;
/**
* Generates a schema object that matches an array data type.
*/
export function array(): ArraySchema;
/**
* Generates a schema object that matches a boolean data type (as well as the strings 'true', 'false', 'yes', and 'no'). Can also be called via bool().
*/
export function bool(): BooleanSchema;
export function boolean(): BooleanSchema;
/**
* Generates a schema object that matches a Buffer data type (as well as the strings which will be converted to Buffers).
*/
export function binary(): BinarySchema;
/**
* Generates a schema object that matches a date type (as well as a JavaScript date string or number of milliseconds).
*/
export function date(): DateSchema;
/**
* Generates a schema object that matches a function type.
*/
export function func(): FunctionSchema;
/**
* Generates a schema object that matches a number data type (as well as strings that can be converted to numbers).
*/
export function number(): NumberSchema;
/**
* Generates a schema object that matches an object data type (as well as JSON strings that parsed into objects).
*/
export function object(schema?: SchemaMap): ObjectSchema;
/**
* Generates a schema object that matches a string data type. Note that empty strings are not allowed by default and must be enabled with allow('').
*/
export function string(): StringSchema;
/**
* Generates a type that will match one of the provided alternative schemas
*/
export function alternatives(types: Schema[]): Schema;
export function alternatives(type1: Schema, type2: Schema, ...types: Schema[]): Schema;
/**
* Validates a value using the given schema and options.
*/
export function validate<T>(value: T, schema: Schema, callback: (err: ValidationError, value: T) => void): void;
export function validate<T>(value: T, schema: Object, callback: (err: ValidationError, value: T) => void): void;
export function validate<T>(value: T, schema: Object, options?: ValidationOptions, callback?: (err: ValidationError, value: T) => void): ValidationResult<T>;
/**
* Converts literal schema definition to joi schema object (or returns the same back if already a joi schema object).
*/
export function compile(schema: Object): Schema;
/**
* Validates a value against a schema and throws if validation fails.
*
* @param value - the value to validate.
* @param schema - the schema object.
* @param message - optional message string prefix added in front of the error message. may also be an Error object.
*/
export function assert(value: any, schema: Schema, message?: string | Error): void;
/**
* Generates a reference to the value of the named key.
*/
export function ref(key: string, options?: ReferenceOptions): Reference;
}
+22 -1
View File
@@ -231,16 +231,18 @@ arrSchema = arrSchema.sparse();
arrSchema = arrSchema.sparse(bool);
arrSchema = arrSchema.single();
arrSchema = arrSchema.single(bool);
arrSchema = arrSchema.ordered(anySchema);
arrSchema = arrSchema.ordered(anySchema, numSchema, strSchema, arrSchema, boolSchema, binSchema, dateSchema, funcSchema, objSchema);
arrSchema = arrSchema.min(num);
arrSchema = arrSchema.max(num);
arrSchema = arrSchema.length(num);
arrSchema = arrSchema.unique();
arrSchema = arrSchema.items(numSchema);
arrSchema = arrSchema.items(numSchema, strSchema);
arrSchema = arrSchema.items([numSchema, strSchema]);
// - - - - - - - -
namespace common_copy_paste {
@@ -420,6 +422,10 @@ dateSchema = dateSchema.format(strArr);
dateSchema = dateSchema.iso();
dateSchema = dateSchema.timestamp();
dateSchema = dateSchema.timestamp('javascript');
dateSchema = dateSchema.timestamp('unix');
namespace common {
dateSchema = dateSchema.allow(x);
dateSchema = dateSchema.allow(x, x);
@@ -471,6 +477,11 @@ namespace common {
funcSchema = Joi.func();
funcSchema = funcSchema.arity(num);
funcSchema = funcSchema.minArity(num);
funcSchema = funcSchema.maxArity(num);
funcSchema = funcSchema.ref();
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
numSchema = Joi.number();
@@ -770,5 +781,15 @@ Joi.assert(obj, schema);
Joi.assert(obj, schema, str);
Joi.assert(obj, schema, err);
Joi.attempt(obj, schema);
Joi.attempt(obj, schema, str);
Joi.attempt(obj, schema, err);
ref = Joi.ref(str, refOpts);
ref = Joi.ref(str);
Joi.isRef(ref);
schema = Joi.reach(schema, '');
const Joi2 = Joi.extend({ name: '', base: schema });
+98 -3
View File
@@ -1,6 +1,6 @@
// Type definitions for joi v6.5.0
// Project: https://github.com/spumko/joi
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>, Laurence Dougal Myers <https://github.com/laurence-myers>, Christopher Glantschnig <https://github.com/cglantschnig>, David Broder-Rodgers <https://github.com/DavidBR-SW>
// Type definitions for joi v9.0.0
// Project: https://github.com/hapijs/joi
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>, Laurence Dougal Myers <https://github.com/laurence-myers>, Christopher Glantschnig <https://github.com/cglantschnig>, David Broder-Rodgers <https://github.com/DavidBR-SW>, Gael Magnan de Bornier <hhttps://github.com/GaelMagnan>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TODO express type of Schema in a type-parameter (.default, .valid, .example etc)
@@ -487,6 +487,13 @@ declare module 'joi' {
items(type: Schema, ...types: Schema[]): ArraySchema;
items(types: Schema[]): ArraySchema;
/**
* Lists the types in sequence order for the array values where:
* @param type - a joi schema object to validate against each array item in sequence order. type can be an array of values, or multiple values can be passed as individual arguments.
* If a given type is .required() then there must be a matching item with the same index position in the array. Errors will contain the number of items that didn't match. Any unmatched item having a label will be mentioned explicitly.
*/
ordered(type: Schema, ...types: Schema[]): ArraySchema;
/**
* Specifies the minimum number of items in the array.
*/
@@ -683,10 +690,41 @@ declare module 'joi' {
* Requires the string value to be in valid ISO 8601 date format.
*/
iso(): DateSchema;
/**
* Requires the value to be a timestamp interval from Unix Time.
* @param type - the type of timestamp (allowed values are unix or javascript [default])
*/
timestamp(type?: 'javascript' | 'unix'): DateSchema;
}
export interface FunctionSchema extends AnySchema<FunctionSchema> {
/**
* Specifies the arity of the function where:
* @param n - the arity expected.
*/
arity(n: number): FunctionSchema;
/**
* Specifies the minimal arity of the function where:
* @param n - the minimal arity expected.
*/
minArity(n: number): FunctionSchema;
/**
* Specifies the minimal arity of the function where:
* @param n - the minimal arity expected.
*/
maxArity(n: number): FunctionSchema;
/**
* Requires the function to be a Joi reference.
*/
ref(): FunctionSchema;
}
export interface AlternativesSchema extends AnySchema<FunctionSchema> {
@@ -695,6 +733,33 @@ declare module 'joi' {
when<T>(ref: Reference, options: WhenOptions<T>): AlternativesSchema;
}
export interface Terms {
value: any;
state: {
key: string,
path: string,
parent: any
};
options: ValidationOptions;
}
export interface Rules {
name: string;
params?: ObjectSchema | { [key: string]: Schema };
setup?: Function;
validate?: Function;
description: string | Function;
}
export interface Extension {
name: string;
base?: Schema;
pre?: Function;
language?: {};
describe?: Function;
rules?: Rules[];
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
/**
@@ -771,8 +836,38 @@ declare module 'joi' {
*/
export function assert(value: any, schema: Schema, message?: string | Error): void;
/**
* Validates a value against a schema, returns valid object, and throws if validation fails where:
*
* @param value - the value to validate.
* @param schema - the schema object.
* @param message - optional message string prefix added in front of the error message. may also be an Error object.
*/
export function attempt(value: any, schema: Schema, message?: string | Error): void;
/**
* Generates a reference to the value of the named key.
*/
export function ref(key: string, options?: ReferenceOptions): Reference;
/**
* Checks whether or not the provided argument is a reference. It's especially useful if you want to post-process error messages.
*/
export function isRef(ref: any): boolean;
/**
* Get a sub-schema of an existing schema based on a path. Path separator is a dot (.).
*/
export function reach(schema: Schema, path: string): Schema;
/**
* Creates a new Joi instance customized with the extension(s) you provide included.
*/
export function extend(extention: Extension): any;
}
+101
View File
@@ -0,0 +1,101 @@
/// <reference path="../jquery/jquery.d.ts" />
/// <reference path="jquery-steps.d.ts" />
var labels: JQuerySteps.LabelSettings = {
cancel: 'Cancel',
current: 'Current:',
pagination: 'Paging',
finish: 'Done',
next: 'Next >',
previous: '< Previous',
loading: 'Loading...'
}
var onStepChangingFunc: JQuerySteps.FunctionOnStepChanging = (event, currentIndex, newIndex): boolean => true;
var onStepChangedFunc: JQuerySteps.FunctionOnStepChanged = (event, currentIndex, priorIndex) => {};
var onCancelledFunc: JQuerySteps.FunctionOnCancelled = (event) => {};
var onFinishingFunc: JQuerySteps.FunctionOnFinishing= (event, currentIndex): boolean => true;
var onFinishedFunc: JQuerySteps.FunctionOnFinished = (event, currentIndex) => {};
var onInitFunc: JQuerySteps.FunctionOnInit = (event, currentIndex) => {};
var onContentLoadedFunc: JQuerySteps.FunctionOnContentLoaded = (event, currentIndex) => {};
var settings: JQuerySteps.Settings = {
headerTag: 'h3',
bodyTag: 'section',
contentContainerTag: 'div',
actionContainerTag: 'div',
stepsContainerTag: 'div',
cssClass: 'wizard',
stepsOrientation: 'vertical',
titleTemplate: '#title#',
loadingTemplate: '<span class="spinner"></span> #text#',
autoFocus: true,
enableAllSteps: true,
enableKeyNavigation: false,
enablePagination: false,
suppressPaginationOnFocus: false,
enableContentCache: false,
enableCancelButton: true,
enableFinishButton: false,
showFinishButtonAlways: true,
forceMoveForward: true,
saveState: true,
startIndex: 1,
transitionEffect: 'slideLeft',
transitionEffectSpeed: 400,
labels: labels,
onCanceled: onCancelledFunc,
onContentLoaded: onContentLoadedFunc,
onFinished: onFinishedFunc,
onFinishing: onFinishingFunc,
onInit: onInitFunc,
onStepChanged: onStepChangedFunc,
onStepChanging: onStepChangingFunc
}
var wizard = $('.wizard').JQuerySteps(settings);
var newStep1: JQuerySteps.Step = {
content: '<div>Content</div>',
title: 'Step 1'
}
var test1 = wizard.add(newStep1);
var newStep2: JQuerySteps.Step = {
content: '<div>Content</div>',
title: 'Step 2',
contentMode: 'async',
contentUrl: 'data.xml'
}
var test2 = wizard.insert(0, newStep2);
var test3 = wizard.remove(1);
var test4 = wizard.getCurrentStep();
var test5 = wizard.getCurrentIndex();
var test6 = wizard.getStep(0);
var newStep3: JQuerySteps.Step = {
content: '<div>Content</div>',
title: 'Step 1'
}
var test7 = wizard.insert(0, newStep3);
var test8 = wizard.next();
var test9 = wizard.previous();
wizard.finish();
wizard.destroy();
+357
View File
@@ -0,0 +1,357 @@
// Type definitions for jQuery Steps v1.1.0
// Project: http://www.jquery-steps.com/
// Definitions by: Joseph Blank <https://github.com/jblank/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface JQuery {
JQuerySteps(param?: JQuerySteps.Settings): JQuerySteps.JQuerySteps;
}
declare module JQuerySteps {
//#region "JQuerySteps"
export interface JQuerySteps {
/**
* Adds a new step. (chainable)
*/
add(step: Step): JQuerySteps;
/**
* Inserts a new step to a specific position. (chainable)
*/
insert(index: number, step: Step): JQuerySteps;
/**
* Removes a specific step by an given index.
*/
remove(index: number): boolean;
/**
* Gets the current step object.
*/
getCurrentStep(): Step;
/**
* Gets the current step index.
*/
getCurrentIndex(): number;
/**
* Gets a specific step object by index.
*/
getStep(index: number): Step;
/**
* Routes to the previous step.
*/
next(): boolean;
/**
* Routes to the next step.
*/
previous(): boolean;
/**
* Triggers the onFinishing and onFinished event.
*/
finish(): void;
/**
* Removes the control functionality completely and transforms the current state to the initial HTML structure.
*/
destroy(): void;
/**
* Skips a certain amount of steps. Not yet implemented!
*/
skip(count: number): boolean;
}
//#endregion "JQuerySteps"
//#region "Settings"
export interface Settings {
//#region "Appearance"
/**
* The header tag is used to find the step button text within the declared wizard area. Default value is h1.
*/
headerTag?: string;
/**
* The body tag is used to find the step content within the declared wizard area. Default value is div.
*/
bodyTag?: string;
/**
* The content container tag which will be used to wrap all step contents. Default value is div.
*/
contentContainerTag?: string;
/**
* The action container tag which will be used to wrap the pagination navigation. Default value is div.
*/
actionContainerTag?: string;
/**
* The steps container tag which will be used to wrap the steps navigation. Default value is div.
*/
stepsContainerTag?: string;
/**
* The css class which will be added to the outer component wrapper. Default value is wizard.
*/
cssClass?: string;
/**
* Determines whether the steps are vertically or horizontally oriented. Default value is horizontal or 0.
* This can be horizontal (0) or vertical (1).
*/
stepsOrientation?: string|number;
//#endregion "Appearance"
//#region "Templates"
/**
* The title template which will be used to create a step button. Default value is span class="number">#index#.</span> #title#.
*/
titleTemplate?: string;
/**
* The loading template which will be used to create the loading animation. Default value is <span class="spinner"></span> #text#.
*/
loadingTemplate?: string;
//#endregion "Templates"
//#region "Behavior"
/**
* Sets the focus to the first wizard instance in order to enable the key navigation from the begining if true. Default value is false.
*/
autoFocus?: boolean;
/**
* Enables all steps from the begining if true (all steps are clickable). Default value is false.
*/
enableAllSteps?: boolean;
/**
* Enables keyboard navigation if true (arrow left and arrow right). Default value is true.
*/
enableKeyNavigation?: boolean;
/**
* Enables pagination (next, previous and finish button) if true. Default value is true.
*/
enablePagination?: boolean;
/**
* Suppresses pagination if a form field is focused. Default value is true.
*/
suppressPaginationOnFocus?: boolean;
/**
* Enables cache for async loaded or iframe embedded content. Default value is true.
*/
enableContentCache?: boolean;
/**
* Shows the cancel button if enabled. Default value is false.
*/
enableCancelButton?: boolean;
/**
* Shows the finish button if enabled. Default value is true.
*/
enableFinishButton?: boolean;
/**
* Shows the finish button always (on each step; right beside the next button) if true. Otherwise the next button will be replaced by the finish button if the last step becomes active. Default value is false.
*/
showFinishButtonAlways?: boolean;
/**
* Prevents jumping to a previous step. Default value is false.
*/
forceMoveForward?: boolean;
/**
* Saves the current state (step position) to a cookie. By coming next time the last active step becomes activated. Default value is false.
*/
saveState?: boolean;
/**
* The position to start on (zero-based). Default value is 0.
*/
startIndex?: number;
//#endregion "Behavior"
//#region "Transition Effects"
/**
* The animation effect which will be used for step transitions. Default value is none or 0.
* This can be none (0), fade (1), slide (2) or slideLeft (3).
*/
transitionEffect?: string|number;
/**
* Animation speed for step transitions (in milliseconds). Default value is 200.
*/
transitionEffectSpeed?: number;
//#endregion "Transition Effects"
//#region "Events"
/**
* Fires before the step changes and can be used to prevent step changing by returning false.
*/
onStepChanging?: FunctionOnStepChanging;
/**
* Fires after the step has changed.
*/
onStepChanged?: FunctionOnStepChanged;
/**
* Fires after cancellation.
*/
onCanceled?: FunctionOnCancelled;
/**
* Fires before finishing and can be used to prevent completion by returning false. Very useful for form validation.
*/
onFinishing?: FunctionOnFinishing;
/**
* Fires after completion.
*/
onFinished?: FunctionOnFinished;
/**
* Fires when the wizard is initialized.
*/
onInit?: FunctionOnInit;
/**
* Fires after async content is loaded.
*/
onContentLoaded?: FunctionOnContentLoaded;
//#endregion "Events"
//#region "Labels"
labels?: LabelSettings;
//#endregion "Labels"
}
//#endregion "Settings"
//#region "Label Settings"
interface LabelSettings {
/**
* Label for the cancel button. Default value is Cancel.
*/
cancel?: string;
/**
* This label is important for accessability reasons. Indicates which step is activated. Default value is current step:.
*/
current?: string;
/**
* This label is important for accessability reasons and describes the kind of navigation. Default value is Pagination.
*/
pagination?: string;
/**
* Label for the finish button. Default value is Finish.
*/
finish?: string;
/**
* Label for the next button. Default value is Next.
*/
next?: string;
/**
* Label for the previous button. Default value is Previous.
*/
previous?: string;
/**
* Label for the loading animation. Default value is Loading ... .
*/
loading?: string;
}
//#endregion "Label Settings"
//#region "Callback Functions"
interface FunctionOnStepChanging {
(event: string, currentIndex: number, newIndex: number): boolean;
}
interface FunctionOnStepChanged {
(event: string, currentIndex: number, priorIndex: number): void;
}
interface FunctionOnCancelled {
(event: string): void;
}
interface FunctionOnFinishing {
(event: string, currentIndex: number): boolean;
}
interface FunctionOnFinished {
(event: string, currentIndex: number): void;
}
interface FunctionOnInit {
(event: string, currentIndex: number): void;
}
interface FunctionOnContentLoaded {
(event: string, currentIndex: number): void;
}
//#endregion "Callback Functions"
//#region "Step Object"
interface Step {
/**
* The step title (HTML).
*/
title?: string;
/**
* The step content (HTML).
*/
content?: string;
/**
* Indicates how the content will be loaded.
* This can be html (0), iframe (1), or async (2).
*/
contentMode?: string|number;
/**
* The URI that refers to the content.
*/
contentUrl?: string;
}
//#endregion "Step Object"
}
+123 -10
View File
@@ -1,10 +1,15 @@
// Type definitions for jquery.pnotify 2.x
// Type definitions for jquery.pnotify 3.x
// Project: https://github.com/sciactive/pnotify
// Definitions by: David Sichau <https://github.com/DavidSichau>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
// could not pass the Travis Test if enabled
//type NoticeTypeOptions = "notice" | "info" | "success" | "error";
//type StylingOptions = "brighttheme" | "jqueryui" | "bootstrap2" | "bootstrap3" | "fontawesome";
//type StateOptions = "initializing" | "opening" | "open" | "closing" | "closed";
interface PNotifyStack {
dir1?: string;
dir2?: string;
@@ -24,11 +29,98 @@ interface PNotifyLabel {
stick?: string;
}
interface PNotifyconfirmButton {
text?: string;
addClass?: string;
/**
* Whether to trigger this button when the user hits enter in a single line prompt.
*/
promptTrigger?: boolean;
click: (notice: PNotify, value: any) => void
}
interface PNotifyconfirm {
/**
* Make a confirmation box.
*/
confirm?: boolean;
/**
* Make a prompt.
*/
prompt?: boolean;
/**
* Classes to add to the input element of the prompt.
*/
prompt_class?: string
/**
* The default value of the prompt.
*/
prompt_default?: string
/**
* Whether the prompt should accept multiple lines of text.
*/
prompt_multi_line?: boolean;
/**
* Where to align the buttons. (right, center, left, justify)
*/
align?: string;
/**
* The buttons to display, and their callbacks.
*/
buttons?: PNotifyconfirmButton[];
}
interface PNotifyButtons {
/**
* Provide a button for the user to manually close the notice.
*/
closer?: boolean;
/**
* Only show the closer button on hover.
*/
closer_hover?: boolean;
/**
* Provide a button for the user to manually stick the notice.
*/
sticker?: boolean;
/**
* Only show the sticker button on hover.
*/
sticker_hover?: boolean;
/**
* Show the buttons even when the nonblock module is in use.
*/
show_on_nonblock?: boolean;
/**
* The various displayed text, helps facilitating internationalization.
*/
labels?: {
close?: string;
stick?: string;
unstick?: string;
};
/**
* The classes to use for button icons. Leave them null to use the classes from the styling you're using.
*/
classes?: {
closer?: string;
pin_up?: string;
pin_down?: string;
};
}
interface PNotifyOptions {
/**
* The notice's title. Either boolean false or string
*/
title?: any;
title?: string | boolean;
/**
* Whether to escape the content of the title. (Not allow HTML.)
*/
@@ -36,13 +128,13 @@ interface PNotifyOptions {
/**
* The notice's text. Either boolean false or string
*/
text?: any;
text?: string | boolean;
/**
* Whether to escape the content of the text. (Not allow HTML.)
*/
text_escape?: boolean;
/**
* What styling classes to use. (Can be either jqueryui or bootstrap.)
* What styling classes to use. (Can be either "brighttheme", "jqueryui", "bootstrap2", "bootstrap3", or "fontawesome".)
*/
styling?: string;
/**
@@ -58,7 +150,7 @@ interface PNotifyOptions {
/**
* Create a non-blocking notice. It lets the user click elements underneath it.
*/
nonblock: boolean;
nonblock?: boolean;
/**
* The opacity of the notice (if it's non-blocking) when the mouse is over it.
@@ -166,17 +258,38 @@ interface PNotifyOptions {
}
interface PNotify {
elem: JQuery;
update(options?: PNotifyOptions): void;
/**
* The state can be "initializing", "opening", "open", "closing", and "closed"
*/
state?: string;
/**
* This function is for updating the notice.
*/
update(options?: PNotifyOptions): PNotify;
/**
* Remove the notice.
*/
remove(): void;
/**
* Display the notice.
*/
open(): void;
/**
* Get the DOM element.
*/
get(): JQuery;
}
interface PNotifyConstructor {
new (options?: PNotifyOptions): PNotify;
removeAll(): void;
}
declare var PNotify: PNotifyConstructor;
@@ -1,8 +1,8 @@
/// <reference path="jquery.tooltipster.d.ts" />
// Type definition tests for jQuery Tooltipster 3.0.5
// Type definition tests for jQuery Tooltipster 3.3.0
// Project: https://github.com/iamceege/tooltipster
// Definitions by: Patrick Magee <https://github.com/pjmagee/>
// Definitions by: Patrick Magee <https://github.com/pjmagee/>, Dmitry Pesterev <https://github.com/VorobeY1326/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Tests taken from the getting started section of the Tooltipster website
@@ -13,6 +13,10 @@ $(document).ready(function () {
$('#my-tooltip').tooltipster({
content: $('<span><img src="my-image.png" /> <strong>This text is in bold case !</strong></span>')
});
$('#my-tooltip').tooltipster({
content: 'string test'
});
});
@@ -191,4 +195,4 @@ $(document).ready(function () {
});
});
$('#my-special-tooltip').tooltipster('content', 'My new content');
$('#my-special-tooltip').tooltipster('content', 'My new content');
+30 -11
View File
@@ -1,6 +1,6 @@
// Type definitions for jQuery Tooltipster 3.0.5
// Type definitions for jQuery Tooltipster 3.3.0
// Project: https://github.com/iamceege/tooltipster
// Definitions by: Patrick Magee <https://github.com/pjmagee/>
// Definitions by: Patrick Magee <https://github.com/pjmagee/>, Dmitry Pesterev <https://github.com/VorobeY1326/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
@@ -21,14 +21,13 @@ interface JQueryTooltipsterOptions {
*/
arrowColor?: any;
/**
* If autoClose is set to false, the tooltip will never close unless you call the 'close' method yourself. Default: true
* If autoClose is set to false, the tooltip will never close unless you call the 'hide' method yourself. Default: true
*/
autoClose?: boolean;
/**
* If set, this will override the content of the tooltip. Default: null
* @type string, jQuery object
*/
content?: any;
content?: string | JQuery;
/**
* If the content of the tooltip is provided as a string, it is displayed as plain text by default. If this content should actually be interpreted as HTML, set this option to true. Default: false
*/
@@ -38,15 +37,19 @@ interface JQueryTooltipsterOptions {
*/
contentCloning?: boolean;
/**
* Tooltipster logs notices into the console when you're doing something you ideally shouldn't be doing. Set to false to disable logging. Default: true
*/
debug?: boolean;
/**
* Delay how long it takes (in milliseconds) for the tooltip to start animating in. Default: 200
*/
delay?: number;
/**
* Set a fixed width for the tooltip. The tooltip will always be a consistent width - no matter your content size. Default: 0 (auto width)
* Set a minimum width for the tooltip. Default: 0 (auto width)
*/
fixedWidth?: number;
minWidth?: number;
/**
* Set a max width for the tooltip. If the tooltip ends up being smaller than the set max width, the tooltip's width will be set automatically. Default: 0 (no max width)
* Set a maximum width for the tooltip. Default: null (no max width)
*/
maxWidth?: number;
/**
@@ -66,10 +69,13 @@ interface JQueryTooltipsterOptions {
*/
functionAfter?: (origin) => void;
/**
* If using the iconDesktop or iconTouch options, this sets the content for your icon. Default: '(?)'
* @type string, jQuery object
* If true, the tooltip will close if its origin is clicked. This option only applies when 'trigger' is 'hover' and 'autoClose' is false. Default: false
*/
icon?: any;
hideOnClick?: boolean;
/**
* If using the iconDesktop or iconTouch options, this sets the content for your icon. Default: '(?)'
*/
icon?: string | JQuery;
/**
* If you provide a jQuery object to the 'icon' option, this sets if it is a clone of this object that should actually be used. Default: true
*/
@@ -95,6 +101,10 @@ interface JQueryTooltipsterOptions {
*/
interactiveTolerance?: number;
/**
* Allows you to put multiple tooltips on a single element. Read further instructions down this page. Default: false
*/
multiple?: boolean;
/**
* Offsets the tooltip (in pixels) farther left/right from the origin. Default: 0
*/
offsetX?: number;
@@ -116,6 +126,15 @@ interface JQueryTooltipsterOptions {
*/
positionTracker?: boolean;
/**
* Called after the tooltip has been repositioned by the position tracker (if enabled). Default: A function that will close the tooltip if the trigger is 'hover' and autoClose is false.
*/
positionTrackerCallback?: (origin) => void;
/**
* Specify if a TITLE attribute should be restored on the HTML element after a call to the 'destroy' method. This attribute may be omitted, or be restored with the value that existed before Tooltipster was initialized, or be restored with the stringified value of the current content. Note: in case of multiple tooltips on a single element, only the last destroyed tooltip may trigger a restoration. Default: 'current'
* 'none', 'previous' or 'current'
*/
restoration?: string;
/**
* Set the speed of the animation. Default: 350
*/
speed?: number;
+1 -1
View File
@@ -1794,7 +1794,7 @@ interface JQuery {
uniqueId(): JQuery;
removeUniqueId(): JQuery;
scrollParent(): JQuery;
zIndex(): JQuery;
zIndex(): number;
zIndex(zIndex: number): JQuery;
widget: JQueryUI.Widget;
+9
View File
@@ -0,0 +1,9 @@
/// <reference path="js-quantities.d.ts" />
var Val1 = Qty('1 m')
var Val2 = Qty(1);
var Val3 = Qty(1, 'm');
var Val4 = Qty(Val1);
+79
View File
@@ -0,0 +1,79 @@
// Type definitions for JS-quantities
// Project: http://gentooboontoo.github.io/js-quantities/
// Definitions by: William Comartin <https://github.com/wcomartin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare var Qty: QtyModule.QtyStatic;
declare namespace QtyModule {
interface QtyStatic {
(value: string): Qty;
(value: number): Qty;
(value: number, unit: string): Qty;
(value: Qty): Qty;
}
interface Qty {
version: string;
scalar: number;
baseScalar: number;
parse(value: string): Qty;
swiftConverter(srcUnits:string, dstUnits:string): (value:number) => number;
getkinds(): string[];
getUnits(kind:string): string[];
getAliases(unitName:string): string[];
formatter(scalar:number, units:string):string;
toFloat(): number;
isUnitless(): boolean;
isCompatible(other:string|Qty): boolean;
isInverse(other:string|Qty): boolean
kind(): string;
isBase(): boolean;
toBase(): Qty;
units(): string;
eq(other:Qty): boolean;
lt(other:Qty): boolean;
lte(other:Qty): boolean;
gt(other:Qty): boolean;
gte(other:Qty): boolean;
toPrec(precQuantity: Qty|string|number): Qty;
toString(targetUnitsOrMaxDecimalsOrPrec?:number|string|Qty, maxDecimals?: number): string;
format(targetUnits?:string, formatter?:(scalar:number, units:string) => string): string;
compareTo(other:Qty|string): number;
same(other: Qty): boolean;
inverse(): Qty;
isDegrees(): boolean;
isTemperature(): boolean;
to(other:string|Qty): Qty;
add(other:string|Qty): Qty;
sub(other:string|Qty): Qty;
mul(other:number|string|Qty): Qty;
div(other:number|string|Qty): Qty;
}
}
+6
View File
@@ -0,0 +1,6 @@
/// <reference path="jsonnet.d.ts" />
import Jsonnet = require('jsonnet');
var jsonnet = new Jsonnet();
var code = '{a:1}';
var result = jsonnet.eval(code);
console.log(result);
+13
View File
@@ -0,0 +1,13 @@
// Type definitions for jsonnet
// Project: https://github.com/yosuke-furukawa/node-jsonnet
// Definitions by: Hookclaw <https://github.com/hookclaw>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "jsonnet" {
class Jsonnet {
constructor();
eval(code: string): any;
evalFile(): any;
destroy(): void;
}
export = Jsonnet;
}
+1 -1
View File
@@ -23,7 +23,7 @@ declare module "jsonwebtoken" {
*/
algorithm?: string;
/** @member {string} - Lifetime for the token expressed in a string describing a time span [rauchg/ms](https://github.com/rauchg/ms.js). Eg: `60`, `"2 days"`, `"10h"`, `"7d"` */
expiresIn?: string;
expiresIn?: string | number;
notBefore?: string;
audience?: string;
subject?: string;
+442 -97
View File
File diff suppressed because it is too large Load Diff
+37 -3
View File
@@ -1,4 +1,4 @@
// Type definitions for Kii Cloud SDK v2.4.3
// Type definitions for Kii Cloud SDK v2.4.4
// Project: http://en.kii.com/
// Definitions by: Kii Consortium <http://jp.kii.com/consortium/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -6059,6 +6059,18 @@ declare namespace KiiCloud {
*/
getEmailAddress(): string;
/**
* Get the email of this user that has not been verified.
* When the user's email has been changed and email verification is required in you app configuration,
* New email is stored as pending email.
* After the new email has been verified, the address can be obtained by {@link KiiUser.getEmailAddress}
*
* @return User's new email address has not been verified.
* null if no pending email field is included in refresh
* response or undefined when no refresh operation has been done before.
*/
getPendingEmailAddress(): string;
/**
* Get the phone number associated with this user
*
@@ -6066,6 +6078,18 @@ declare namespace KiiCloud {
*/
getPhoneNumber(): string;
/**
* Get the phone of this user that has not been verified.
* When the user's phone has been changed and phone verification is required in you app configuration,
* New phone is stored as pending phone.
* After the new phone has been verified, the address can be obtained by {@link KiiUser.getPhoneNumber}
*
* @return User's new phone number has not been verified.
* null if no pending phone field is included in refresh
* response or undefined when no refresh operation has been done before.
*/
getPendingPhoneNumber(): string;
/**
* Get the country code associated with this user
*
@@ -7126,7 +7150,12 @@ declare namespace KiiCloud {
ownerOfGroups(callbacks?: { success(theUser: KiiUser, groupList: KiiGroup[]): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise<[KiiUser, KiiGroup[]]>;
/**
* Updates the user's phone number on the server
* Change phone number of logged in user.
* If the phone number verification is required by your app configuration,
* User's phone number would not changed to new one until the new phone number verification has been done.
* In this case, new phone can be obtained by {@link KiiUser#getPendingPhoneNumber()}.
* This API does not refresh the KiiUser automatically.
* Please execute {@link KiiUser#refresh()} before checking the value of {@link KiiUser#getPhoneNumber()} or {@link KiiUser#getPendingPhoneNumber()}.
*
* @param newPhoneNumber The new phone number to change to
* @param callbacks An object with callback methods defined
@@ -7169,7 +7198,12 @@ declare namespace KiiCloud {
changePhone(newPhoneNumber: string, callbacks?: { success(theUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise<KiiUser>;
/**
* Updates the user's email address on the server
* Change email of logged in user.
* If the email address verification is required by your app configuration,
* User's email would not changed to new one until the new email verification has been done.
* In this case, new mail address can be obtained by {@link KiiUser#getPendingEmailAddress()}.
* This API does not refresh the KiiUser automatically.
* Please execute {@link KiiUser#refresh()} before checking the value of {@link KiiUser#getEmailAddress()} or {@link KiiUser#getPendingEmailAddress()}
*
* @param newEmail The new email address to change to
* @param callbacks An object with callback methods defined
+7 -5
View File
@@ -1,8 +1,10 @@
/// <reference path='knex.d.ts' />
/// <reference path='../lodash/lodash-3.10.d.ts' />
import Knex = require('knex');
import _ = require('lodash');
'use strict';
import * as Knex from 'knex';
import * as _ from 'lodash';
// Initializing the Library
var knex = Knex({
client: 'sqlite3',
@@ -594,8 +596,8 @@ knex.migrate.latest();
knex.migrate.rollback(config);
knex.migrate.rollback();
knex.migrate.currentversion(config);
knex.migrate.currentversion();
knex.migrate.currentVersion(config);
knex.migrate.currentVersion();
knex.seed.make(name, config);
knex.seed.make(name);
+16 -8
View File
@@ -12,7 +12,7 @@ declare module "knex" {
type Callback = Function;
type Client = Function;
type Value = string|number|boolean|Date;
type Value = string|number|boolean|Date|Array<string>|Array<number>|Array<Date>|Array<boolean>;
type ColumnName = string|Knex.Raw|Knex.QueryBuilder;
interface Knex extends Knex.QueryInterface {
@@ -28,7 +28,7 @@ declare module "knex" {
schema: Knex.SchemaBuilder;
client: any;
migrate: any;
migrate: Knex.Migrator;
seed: any;
fn: any;
}
@@ -302,7 +302,7 @@ declare module "knex" {
interface SchemaBuilder extends Promise<any> {
createTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder;
renameTable(oldTableName: string, newTableName: string): Promise<void>;
dropTable(tableName: string): Promise<void>;
dropTable(tableName: string): SchemaBuilder;
hasTable(tableName: string): Promise<boolean>;
hasColumn(tableName: string, columnName: string): Promise<boolean>;
table(tableName: string, callback: (tableBuilder: AlterTableBuilder) => any): Promise<void>;
@@ -370,15 +370,15 @@ declare module "knex" {
nullable(): ColumnBuilder;
comment(value: string): ColumnBuilder;
}
interface ForeignConstraintBuilder {
references(columnName: string): ReferencingColumnBuilder;
}
interface MultikeyForeignConstraintBuilder {
references(columnNames: string[]): ReferencingColumnBuilder;
}
interface PostgreSqlColumnBuilder extends ColumnBuilder {
index(indexName?: string, indexType?: string): ColumnBuilder;
}
@@ -413,7 +413,7 @@ declare module "knex" {
connection?: string|ConnectionConfig|MariaSqlConnectionConfig|
Sqlite3ConnectionConfig|SocketConnectionConfig;
pool?: PoolConfig;
migrations?: MigrationConfig;
migrations?: MigratorConfig;
}
interface ConnectionConfig {
@@ -487,12 +487,20 @@ declare module "knex" {
log?: boolean;
}
interface MigrationConfig {
interface MigratorConfig {
database?: string;
directory?: string;
extension?: string;
tableName?: string;
}
interface Migrator {
make(name:string, config?: MigratorConfig):Promise<string>;
latest(config?: MigratorConfig):Promise<any>;
rollback(config?: MigratorConfig):Promise<any>;
status(config?: MigratorConfig):Promise<number>;
currentVersion(config?: MigratorConfig):Promise<string>;
}
}
export = Knex;
+353
View File
@@ -0,0 +1,353 @@
/// <reference path="locutus.d.ts" />
import locutus_c_math_abs = require('locutus/c/math/abs');
import locutus_golang_strings_Contains = require('locutus/golang/strings/Contains');
import locutus_golang_strings_Count = require('locutus/golang/strings/Count');
import locutus_golang_strings_Index = require('locutus/golang/strings/Index');
import locutus_golang_strings_LastIndex = require('locutus/golang/strings/LastIndex');
import locutus_php_array_array_change_key_case = require('locutus/php/array/array_change_key_case');
import locutus_php_array_array_chunk = require('locutus/php/array/array_chunk');
import locutus_php_array_array_combine = require('locutus/php/array/array_combine');
import locutus_php_array_array_count_values = require('locutus/php/array/array_count_values');
import locutus_php_array_array_diff = require('locutus/php/array/array_diff');
import locutus_php_array_array_diff_assoc = require('locutus/php/array/array_diff_assoc');
import locutus_php_array_array_diff_key = require('locutus/php/array/array_diff_key');
import locutus_php_array_array_diff_uassoc = require('locutus/php/array/array_diff_uassoc');
import locutus_php_array_array_diff_ukey = require('locutus/php/array/array_diff_ukey');
import locutus_php_array_array_fill = require('locutus/php/array/array_fill');
import locutus_php_array_array_fill_keys = require('locutus/php/array/array_fill_keys');
import locutus_php_array_array_filter = require('locutus/php/array/array_filter');
import locutus_php_array_array_flip = require('locutus/php/array/array_flip');
import locutus_php_array_array_intersect = require('locutus/php/array/array_intersect');
import locutus_php_array_array_intersect_assoc = require('locutus/php/array/array_intersect_assoc');
import locutus_php_array_array_intersect_key = require('locutus/php/array/array_intersect_key');
import locutus_php_array_array_intersect_uassoc = require('locutus/php/array/array_intersect_uassoc');
import locutus_php_array_array_intersect_ukey = require('locutus/php/array/array_intersect_ukey');
import locutus_php_array_array_key_exists = require('locutus/php/array/array_key_exists');
import locutus_php_array_array_keys = require('locutus/php/array/array_keys');
import locutus_php_array_array_map = require('locutus/php/array/array_map');
import locutus_php_array_array_merge = require('locutus/php/array/array_merge');
import locutus_php_array_array_merge_recursive = require('locutus/php/array/array_merge_recursive');
import locutus_php_array_array_multisort = require('locutus/php/array/array_multisort');
import locutus_php_array_array_pad = require('locutus/php/array/array_pad');
import locutus_php_array_array_pop = require('locutus/php/array/array_pop');
import locutus_php_array_array_product = require('locutus/php/array/array_product');
import locutus_php_array_array_push = require('locutus/php/array/array_push');
import locutus_php_array_array_rand = require('locutus/php/array/array_rand');
import locutus_php_array_array_reduce = require('locutus/php/array/array_reduce');
import locutus_php_array_array_replace = require('locutus/php/array/array_replace');
import locutus_php_array_array_replace_recursive = require('locutus/php/array/array_replace_recursive');
import locutus_php_array_array_reverse = require('locutus/php/array/array_reverse');
import locutus_php_array_array_search = require('locutus/php/array/array_search');
import locutus_php_array_array_shift = require('locutus/php/array/array_shift');
import locutus_php_array_array_slice = require('locutus/php/array/array_slice');
import locutus_php_array_array_splice = require('locutus/php/array/array_splice');
import locutus_php_array_array_sum = require('locutus/php/array/array_sum');
import locutus_php_array_array_udiff = require('locutus/php/array/array_udiff');
import locutus_php_array_array_udiff_assoc = require('locutus/php/array/array_udiff_assoc');
import locutus_php_array_array_udiff_uassoc = require('locutus/php/array/array_udiff_uassoc');
import locutus_php_array_array_uintersect = require('locutus/php/array/array_uintersect');
import locutus_php_array_array_uintersect_uassoc = require('locutus/php/array/array_uintersect_uassoc');
import locutus_php_array_array_unique = require('locutus/php/array/array_unique');
import locutus_php_array_array_unshift = require('locutus/php/array/array_unshift');
import locutus_php_array_array_values = require('locutus/php/array/array_values');
import locutus_php_array_array_walk = require('locutus/php/array/array_walk');
import locutus_php_array_arsort = require('locutus/php/array/arsort');
import locutus_php_array_asort = require('locutus/php/array/asort');
import locutus_php_array_count = require('locutus/php/array/count');
import locutus_php_array_current = require('locutus/php/array/current');
import locutus_php_array_each = require('locutus/php/array/each');
import locutus_php_array_end = require('locutus/php/array/end');
import locutus_php_array_in_array = require('locutus/php/array/in_array');
import locutus_php_array_key = require('locutus/php/array/key');
import locutus_php_array_krsort = require('locutus/php/array/krsort');
import locutus_php_array_ksort = require('locutus/php/array/ksort');
import locutus_php_array_natcasesort = require('locutus/php/array/natcasesort');
import locutus_php_array_natsort = require('locutus/php/array/natsort');
import locutus_php_array_next = require('locutus/php/array/next');
import locutus_php_array_pos = require('locutus/php/array/pos');
import locutus_php_array_prev = require('locutus/php/array/prev');
import locutus_php_array_range = require('locutus/php/array/range');
import locutus_php_array_reset = require('locutus/php/array/reset');
import locutus_php_array_rsort = require('locutus/php/array/rsort');
import locutus_php_array_shuffle = require('locutus/php/array/shuffle');
import locutus_php_array_sizeof = require('locutus/php/array/sizeof');
import locutus_php_array_sort = require('locutus/php/array/sort');
import locutus_php_array_uasort = require('locutus/php/array/uasort');
import locutus_php_array_uksort = require('locutus/php/array/uksort');
import locutus_php_array_usort = require('locutus/php/array/usort');
import locutus_php_bc_bcadd = require('locutus/php/bc/bcadd');
import locutus_php_bc_bccomp = require('locutus/php/bc/bccomp');
import locutus_php_bc_bcdiv = require('locutus/php/bc/bcdiv');
import locutus_php_bc_bcmul = require('locutus/php/bc/bcmul');
import locutus_php_bc_bcround = require('locutus/php/bc/bcround');
import locutus_php_bc_bcscale = require('locutus/php/bc/bcscale');
import locutus_php_bc_bcsub = require('locutus/php/bc/bcsub');
import locutus_php_ctype_ctype_alnum = require('locutus/php/ctype/ctype_alnum');
import locutus_php_ctype_ctype_alpha = require('locutus/php/ctype/ctype_alpha');
import locutus_php_ctype_ctype_cntrl = require('locutus/php/ctype/ctype_cntrl');
import locutus_php_ctype_ctype_digit = require('locutus/php/ctype/ctype_digit');
import locutus_php_ctype_ctype_graph = require('locutus/php/ctype/ctype_graph');
import locutus_php_ctype_ctype_lower = require('locutus/php/ctype/ctype_lower');
import locutus_php_ctype_ctype_print = require('locutus/php/ctype/ctype_print');
import locutus_php_ctype_ctype_punct = require('locutus/php/ctype/ctype_punct');
import locutus_php_ctype_ctype_space = require('locutus/php/ctype/ctype_space');
import locutus_php_ctype_ctype_upper = require('locutus/php/ctype/ctype_upper');
import locutus_php_ctype_ctype_xdigit = require('locutus/php/ctype/ctype_xdigit');
import locutus_php_datetime_checkdate = require('locutus/php/datetime/checkdate');
import locutus_php_datetime_date = require('locutus/php/datetime/date');
import locutus_php_datetime_date_parse = require('locutus/php/datetime/date_parse');
import locutus_php_datetime_getdate = require('locutus/php/datetime/getdate');
import locutus_php_datetime_gettimeofday = require('locutus/php/datetime/gettimeofday');
import locutus_php_datetime_gmdate = require('locutus/php/datetime/gmdate');
import locutus_php_datetime_gmmktime = require('locutus/php/datetime/gmmktime');
import locutus_php_datetime_gmstrftime = require('locutus/php/datetime/gmstrftime');
import locutus_php_datetime_idate = require('locutus/php/datetime/idate');
import locutus_php_datetime_microtime = require('locutus/php/datetime/microtime');
import locutus_php_datetime_mktime = require('locutus/php/datetime/mktime');
import locutus_php_datetime_strftime = require('locutus/php/datetime/strftime');
import locutus_php_datetime_strptime = require('locutus/php/datetime/strptime');
import locutus_php_datetime_strtotime = require('locutus/php/datetime/strtotime');
import locutus_php_datetime_time = require('locutus/php/datetime/time');
import locutus_php_exec_escapeshellarg = require('locutus/php/exec/escapeshellarg');
import locutus_php_filesystem_basename = require('locutus/php/filesystem/basename');
import locutus_php_filesystem_dirname = require('locutus/php/filesystem/dirname');
import locutus_php_filesystem_file_get_contents = require('locutus/php/filesystem/file_get_contents');
import locutus_php_filesystem_pathinfo = require('locutus/php/filesystem/pathinfo');
import locutus_php_filesystem_realpath = require('locutus/php/filesystem/realpath');
import locutus_php_funchand_call_user_func = require('locutus/php/funchand/call_user_func');
import locutus_php_funchand_call_user_func_array = require('locutus/php/funchand/call_user_func_array');
import locutus_php_funchand_create_function = require('locutus/php/funchand/create_function');
import locutus_php_funchand_function_exists = require('locutus/php/funchand/function_exists');
import locutus_php_funchand_get_defined_functions = require('locutus/php/funchand/get_defined_functions');
import locutus_php_i18n_i18n_loc_get_default = require('locutus/php/i18n/i18n_loc_get_default');
import locutus_php_i18n_i18n_loc_set_default = require('locutus/php/i18n/i18n_loc_set_default');
import locutus_php_info_assert_options = require('locutus/php/info/assert_options');
import locutus_php_info_getenv = require('locutus/php/info/getenv');
import locutus_php_info_ini_get = require('locutus/php/info/ini_get');
import locutus_php_info_ini_set = require('locutus/php/info/ini_set');
import locutus_php_info_set_time_limit = require('locutus/php/info/set_time_limit');
import locutus_php_info_version_compare = require('locutus/php/info/version_compare');
import locutus_php_json_json_decode = require('locutus/php/json/json_decode');
import locutus_php_json_json_encode = require('locutus/php/json/json_encode');
import locutus_php_json_json_last_error = require('locutus/php/json/json_last_error');
import locutus_php_math_abs = require('locutus/php/math/abs');
import locutus_php_math_acos = require('locutus/php/math/acos');
import locutus_php_math_acosh = require('locutus/php/math/acosh');
import locutus_php_math_asin = require('locutus/php/math/asin');
import locutus_php_math_asinh = require('locutus/php/math/asinh');
import locutus_php_math_atan = require('locutus/php/math/atan');
import locutus_php_math_atan2 = require('locutus/php/math/atan2');
import locutus_php_math_atanh = require('locutus/php/math/atanh');
import locutus_php_math_base_convert = require('locutus/php/math/base_convert');
import locutus_php_math_bindec = require('locutus/php/math/bindec');
import locutus_php_math_ceil = require('locutus/php/math/ceil');
import locutus_php_math_cos = require('locutus/php/math/cos');
import locutus_php_math_cosh = require('locutus/php/math/cosh');
import locutus_php_math_decbin = require('locutus/php/math/decbin');
import locutus_php_math_dechex = require('locutus/php/math/dechex');
import locutus_php_math_decoct = require('locutus/php/math/decoct');
import locutus_php_math_deg2rad = require('locutus/php/math/deg2rad');
import locutus_php_math_exp = require('locutus/php/math/exp');
import locutus_php_math_expm1 = require('locutus/php/math/expm1');
import locutus_php_math_floor = require('locutus/php/math/floor');
import locutus_php_math_fmod = require('locutus/php/math/fmod');
import locutus_php_math_getrandmax = require('locutus/php/math/getrandmax');
import locutus_php_math_hexdec = require('locutus/php/math/hexdec');
import locutus_php_math_hypot = require('locutus/php/math/hypot');
import locutus_php_math_is_finite = require('locutus/php/math/is_finite');
import locutus_php_math_is_infinite = require('locutus/php/math/is_infinite');
import locutus_php_math_is_nan = require('locutus/php/math/is_nan');
import locutus_php_math_lcg_value = require('locutus/php/math/lcg_value');
import locutus_php_math_log = require('locutus/php/math/log');
import locutus_php_math_log10 = require('locutus/php/math/log10');
import locutus_php_math_log1p = require('locutus/php/math/log1p');
import locutus_php_math_max = require('locutus/php/math/max');
import locutus_php_math_min = require('locutus/php/math/min');
import locutus_php_math_mt_getrandmax = require('locutus/php/math/mt_getrandmax');
import locutus_php_math_mt_rand = require('locutus/php/math/mt_rand');
import locutus_php_math_octdec = require('locutus/php/math/octdec');
import locutus_php_math_pi = require('locutus/php/math/pi');
import locutus_php_math_pow = require('locutus/php/math/pow');
import locutus_php_math_rad2deg = require('locutus/php/math/rad2deg');
import locutus_php_math_rand = require('locutus/php/math/rand');
import locutus_php_math_round = require('locutus/php/math/round');
import locutus_php_math_sin = require('locutus/php/math/sin');
import locutus_php_math_sinh = require('locutus/php/math/sinh');
import locutus_php_math_sqrt = require('locutus/php/math/sqrt');
import locutus_php_math_tan = require('locutus/php/math/tan');
import locutus_php_math_tanh = require('locutus/php/math/tanh');
import locutus_php_misc_pack = require('locutus/php/misc/pack');
import locutus_php_misc_uniqid = require('locutus/php/misc/uniqid');
import locutus_php_net_gopher_gopher_parsedir = require('locutus/php/net-gopher/gopher_parsedir');
import locutus_php_network_inet_ntop = require('locutus/php/network/inet_ntop');
import locutus_php_network_inet_pton = require('locutus/php/network/inet_pton');
import locutus_php_network_ip2long = require('locutus/php/network/ip2long');
import locutus_php_network_long2ip = require('locutus/php/network/long2ip');
import locutus_php_network_setcookie = require('locutus/php/network/setcookie');
import locutus_php_network_setrawcookie = require('locutus/php/network/setrawcookie');
import locutus_php_pcre_preg_quote = require('locutus/php/pcre/preg_quote');
import locutus_php_pcre_sql_regcase = require('locutus/php/pcre/sql_regcase');
import locutus_php_strings_addcslashes = require('locutus/php/strings/addcslashes');
import locutus_php_strings_addslashes = require('locutus/php/strings/addslashes');
import locutus_php_strings_bin2hex = require('locutus/php/strings/bin2hex');
import locutus_php_strings_chop = require('locutus/php/strings/chop');
import locutus_php_strings_chr = require('locutus/php/strings/chr');
import locutus_php_strings_chunk_split = require('locutus/php/strings/chunk_split');
import locutus_php_strings_convert_cyr_string = require('locutus/php/strings/convert_cyr_string');
import locutus_php_strings_convert_uuencode = require('locutus/php/strings/convert_uuencode');
import locutus_php_strings_count_chars = require('locutus/php/strings/count_chars');
import locutus_php_strings_crc32 = require('locutus/php/strings/crc32');
import locutus_php_strings_echo = require('locutus/php/strings/echo');
import locutus_php_strings_explode = require('locutus/php/strings/explode');
import locutus_php_strings_get_html_translation_table = require('locutus/php/strings/get_html_translation_table');
import locutus_php_strings_hex2bin = require('locutus/php/strings/hex2bin');
import locutus_php_strings_html_entity_decode = require('locutus/php/strings/html_entity_decode');
import locutus_php_strings_htmlentities = require('locutus/php/strings/htmlentities');
import locutus_php_strings_htmlspecialchars = require('locutus/php/strings/htmlspecialchars');
import locutus_php_strings_htmlspecialchars_decode = require('locutus/php/strings/htmlspecialchars_decode');
import locutus_php_strings_implode = require('locutus/php/strings/implode');
import locutus_php_strings_join = require('locutus/php/strings/join');
import locutus_php_strings_lcfirst = require('locutus/php/strings/lcfirst');
import locutus_php_strings_levenshtein = require('locutus/php/strings/levenshtein');
import locutus_php_strings_localeconv = require('locutus/php/strings/localeconv');
import locutus_php_strings_ltrim = require('locutus/php/strings/ltrim');
import locutus_php_strings_md5 = require('locutus/php/strings/md5');
import locutus_php_strings_md5_file = require('locutus/php/strings/md5_file');
import locutus_php_strings_metaphone = require('locutus/php/strings/metaphone');
import locutus_php_strings_money_format = require('locutus/php/strings/money_format');
import locutus_php_strings_nl2br = require('locutus/php/strings/nl2br');
import locutus_php_strings_nl_langinfo = require('locutus/php/strings/nl_langinfo');
import locutus_php_strings_number_format = require('locutus/php/strings/number_format');
import locutus_php_strings_ord = require('locutus/php/strings/ord');
import locutus_php_strings_parse_str = require('locutus/php/strings/parse_str');
import locutus_php_strings_printf = require('locutus/php/strings/printf');
import locutus_php_strings_quoted_printable_decode = require('locutus/php/strings/quoted_printable_decode');
import locutus_php_strings_quoted_printable_encode = require('locutus/php/strings/quoted_printable_encode');
import locutus_php_strings_quotemeta = require('locutus/php/strings/quotemeta');
import locutus_php_strings_rtrim = require('locutus/php/strings/rtrim');
import locutus_php_strings_setlocale = require('locutus/php/strings/setlocale');
import locutus_php_strings_sha1 = require('locutus/php/strings/sha1');
import locutus_php_strings_sha1_file = require('locutus/php/strings/sha1_file');
import locutus_php_strings_similar_text = require('locutus/php/strings/similar_text');
import locutus_php_strings_soundex = require('locutus/php/strings/soundex');
import locutus_php_strings_split = require('locutus/php/strings/split');
import locutus_php_strings_sprintf = require('locutus/php/strings/sprintf');
import locutus_php_strings_sscanf = require('locutus/php/strings/sscanf');
import locutus_php_strings_str_getcsv = require('locutus/php/strings/str_getcsv');
import locutus_php_strings_str_ireplace = require('locutus/php/strings/str_ireplace');
import locutus_php_strings_str_pad = require('locutus/php/strings/str_pad');
import locutus_php_strings_str_repeat = require('locutus/php/strings/str_repeat');
import locutus_php_strings_str_replace = require('locutus/php/strings/str_replace');
import locutus_php_strings_str_rot13 = require('locutus/php/strings/str_rot13');
import locutus_php_strings_str_shuffle = require('locutus/php/strings/str_shuffle');
import locutus_php_strings_str_split = require('locutus/php/strings/str_split');
import locutus_php_strings_str_word_count = require('locutus/php/strings/str_word_count');
import locutus_php_strings_strcasecmp = require('locutus/php/strings/strcasecmp');
import locutus_php_strings_strchr = require('locutus/php/strings/strchr');
import locutus_php_strings_strcmp = require('locutus/php/strings/strcmp');
import locutus_php_strings_strcoll = require('locutus/php/strings/strcoll');
import locutus_php_strings_strcspn = require('locutus/php/strings/strcspn');
import locutus_php_strings_strip_tags = require('locutus/php/strings/strip_tags');
import locutus_php_strings_stripos = require('locutus/php/strings/stripos');
import locutus_php_strings_stripslashes = require('locutus/php/strings/stripslashes');
import locutus_php_strings_stristr = require('locutus/php/strings/stristr');
import locutus_php_strings_strlen = require('locutus/php/strings/strlen');
import locutus_php_strings_strnatcasecmp = require('locutus/php/strings/strnatcasecmp');
import locutus_php_strings_strnatcmp = require('locutus/php/strings/strnatcmp');
import locutus_php_strings_strncasecmp = require('locutus/php/strings/strncasecmp');
import locutus_php_strings_strncmp = require('locutus/php/strings/strncmp');
import locutus_php_strings_strpbrk = require('locutus/php/strings/strpbrk');
import locutus_php_strings_strpos = require('locutus/php/strings/strpos');
import locutus_php_strings_strrchr = require('locutus/php/strings/strrchr');
import locutus_php_strings_strrev = require('locutus/php/strings/strrev');
import locutus_php_strings_strripos = require('locutus/php/strings/strripos');
import locutus_php_strings_strrpos = require('locutus/php/strings/strrpos');
import locutus_php_strings_strspn = require('locutus/php/strings/strspn');
import locutus_php_strings_strstr = require('locutus/php/strings/strstr');
import locutus_php_strings_strtok = require('locutus/php/strings/strtok');
import locutus_php_strings_strtolower = require('locutus/php/strings/strtolower');
import locutus_php_strings_strtoupper = require('locutus/php/strings/strtoupper');
import locutus_php_strings_strtr = require('locutus/php/strings/strtr');
import locutus_php_strings_substr = require('locutus/php/strings/substr');
import locutus_php_strings_substr_compare = require('locutus/php/strings/substr_compare');
import locutus_php_strings_substr_count = require('locutus/php/strings/substr_count');
import locutus_php_strings_substr_replace = require('locutus/php/strings/substr_replace');
import locutus_php_strings_trim = require('locutus/php/strings/trim');
import locutus_php_strings_ucfirst = require('locutus/php/strings/ucfirst');
import locutus_php_strings_ucwords = require('locutus/php/strings/ucwords');
import locutus_php_strings_vprintf = require('locutus/php/strings/vprintf');
import locutus_php_strings_vsprintf = require('locutus/php/strings/vsprintf');
import locutus_php_strings_wordwrap = require('locutus/php/strings/wordwrap');
import locutus_php_url_base64_decode = require('locutus/php/url/base64_decode');
import locutus_php_url_base64_encode = require('locutus/php/url/base64_encode');
import locutus_php_url_http_build_query = require('locutus/php/url/http_build_query');
import locutus_php_url_parse_url = require('locutus/php/url/parse_url');
import locutus_php_url_rawurldecode = require('locutus/php/url/rawurldecode');
import locutus_php_url_rawurlencode = require('locutus/php/url/rawurlencode');
import locutus_php_url_urldecode = require('locutus/php/url/urldecode');
import locutus_php_url_urlencode = require('locutus/php/url/urlencode');
import locutus_php_var_doubleval = require('locutus/php/var/doubleval');
import locutus_php_var_empty = require('locutus/php/var/empty');
import locutus_php_var_floatval = require('locutus/php/var/floatval');
import locutus_php_var_gettype = require('locutus/php/var/gettype');
import locutus_php_var_intval = require('locutus/php/var/intval');
import locutus_php_var_is_array = require('locutus/php/var/is_array');
import locutus_php_var_is_binary = require('locutus/php/var/is_binary');
import locutus_php_var_is_bool = require('locutus/php/var/is_bool');
import locutus_php_var_is_buffer = require('locutus/php/var/is_buffer');
import locutus_php_var_is_callable = require('locutus/php/var/is_callable');
import locutus_php_var_is_double = require('locutus/php/var/is_double');
import locutus_php_var_is_float = require('locutus/php/var/is_float');
import locutus_php_var_is_int = require('locutus/php/var/is_int');
import locutus_php_var_is_integer = require('locutus/php/var/is_integer');
import locutus_php_var_is_long = require('locutus/php/var/is_long');
import locutus_php_var_is_null = require('locutus/php/var/is_null');
import locutus_php_var_is_numeric = require('locutus/php/var/is_numeric');
import locutus_php_var_is_object = require('locutus/php/var/is_object');
import locutus_php_var_is_real = require('locutus/php/var/is_real');
import locutus_php_var_is_scalar = require('locutus/php/var/is_scalar');
import locutus_php_var_is_string = require('locutus/php/var/is_string');
import locutus_php_var_is_unicode = require('locutus/php/var/is_unicode');
import locutus_php_var_isset = require('locutus/php/var/isset');
import locutus_php_var_print_r = require('locutus/php/var/print_r');
import locutus_php_var_serialize = require('locutus/php/var/serialize');
import locutus_php_var_strval = require('locutus/php/var/strval');
import locutus_php_var_unserialize = require('locutus/php/var/unserialize');
import locutus_php_var_var_dump = require('locutus/php/var/var_dump');
import locutus_php_var_var_export = require('locutus/php/var/var_export');
import locutus_php_xdiff_xdiff_string_diff = require('locutus/php/xdiff/xdiff_string_diff');
import locutus_php_xdiff_xdiff_string_patch = require('locutus/php/xdiff/xdiff_string_patch');
import locutus_php_xml_utf8_decode = require('locutus/php/xml/utf8_decode');
import locutus_php_xml_utf8_encode = require('locutus/php/xml/utf8_encode');
import locutus_python_string_capwords = require('locutus/python/string/capwords');
import locutus_ruby_Math_acos = require('locutus/ruby/Math/acos');
import locutus_c_math = require('locutus/c/math');
import locutus_golang_strings = require('locutus/golang/strings');
import locutus_php_array = require('locutus/php/array');
import locutus_php_bc = require('locutus/php/bc');
import locutus_php_ctype = require('locutus/php/ctype');
import locutus_php_datetime = require('locutus/php/datetime');
import locutus_php_exec = require('locutus/php/exec');
import locutus_php_filesystem = require('locutus/php/filesystem');
import locutus_php_funchand = require('locutus/php/funchand');
import locutus_php_i18n = require('locutus/php/i18n');
import locutus_php_info = require('locutus/php/info');
import locutus_php_json = require('locutus/php/json');
import locutus_php_math = require('locutus/php/math');
import locutus_php_misc = require('locutus/php/misc');
import locutus_php_net_gopher = require('locutus/php/net-gopher');
import locutus_php_network = require('locutus/php/network');
import locutus_php_pcre = require('locutus/php/pcre');
import locutus_php_strings = require('locutus/php/strings');
import locutus_php_url = require('locutus/php/url');
import locutus_php_var = require('locutus/php/var');
import locutus_php_xdiff = require('locutus/php/xdiff');
import locutus_php_xml = require('locutus/php/xml');
import locutus_python_string = require('locutus/python/string');
import locutus_ruby_Math = require('locutus/ruby/Math');
import locutus_c = require('locutus/c');
import locutus_golang = require('locutus/golang');
import locutus_php = require('locutus/php');
import locutus_python = require('locutus/python');
import locutus_ruby = require('locutus/ruby');
import locutus = require('locutus');
+1734
View File
File diff suppressed because it is too large Load Diff
+188
View File
@@ -0,0 +1,188 @@
// Automatically generate script for locutus
// Written by: Hookclaw <https://github.com/hookclaw>
/* Usage
tsc locutus_print.ts
node locutus_print.js define
*/
/// <reference path="../node/node.d.ts" />
/// <reference path="./locutus.d.ts" />
var locutus = require('locutus');
type f = (...args:any[]) => any;
type e = {[key:string]:f};
type d = {[key:string]:e};
type c = {[key:string]:d};
let loc:c = locutus;
let run = ():void => {
if(process.argv.length > 1) {
switch(process.argv[2]) {
case 'define':
define();
return;
case 'test':
test();
return;
case 'settings':
settings();
return;
}
}
console.log('settings,list,define');
};
let define = ():void => {
console.log('// Type definitions for locutus');
console.log('// Project: http://locutusjs.io');
console.log('// Definitions by: Hookclaw <https://github.com/hookclaw>');
console.log('// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped');
console.log('');
for(let key1 in loc) {
for(let key2 in loc[key1]) {
for(let key3 in loc[key1][key2]) {
printSingle(loc,key1,key2,key3);
}
}
}
for(let key1 in loc) {
for(let key2 in loc[key1]) {
let modulename = 'locutus/' + key1 + '/' + key2;
printGroup(modulename, loc[key1][key2]);
}
}
for(let key1 in loc) {
let modulename = 'locutus/' + key1;
printGroup(modulename, loc[key1]);
}
let modulename = 'locutus';
printGroup(modulename, loc);
}
let printSingle = (loc:c,key1:string,key2:string,key3:string):void => {
console.log('declare module "locutus/' + key1 + '/' + key2 + '/' + key3 + '" {');
console.log('\tfunction ' + key3 + arg(loc,key1,key2,key3) + ':any;');
console.log('\texport = ' + key3 + ';');
console.log('}');
}
let printGroup = (modulename:string,loc:{}):void => {
let s:string[] = [];
let c = '';
console.log('declare module "' + modulename + '" {');
for(let key in loc) {
let com = '';
let tmp = replace(key);
if(tmp == key) {
s.push(key);
} else {
com = '// ';
// s.push('"' + key + '":' + tmp);
c += ' /* ,"' + key + '":' + tmp + ' */';
}
console.log('\t' + com + 'import ' + tmp + ' = require("' + modulename + '/' + key + '");');
}
console.log('\texport {' + s.join(',') + c + '};');
console.log('}');
}
let replace = (name:string):string => {
if(name == 'var') {
return 'Var';
}
// if(name == 'string') {
// return 'String';
// }
return name.replace('-','_');
}
let func = (loc:c,key1:string,key2:string,key3:string):string => {
return '"' + key3 + '":' + arg(loc,key1,key2,key3) + ' => any';
}
const ARG1 = "(...args:any[])";
let arg = (loc:c,key1:string,key2:string,key3:string):string => {
let src = loc[key1][key2][key3].toString();
let mArguments = /[^a-zA-Z0-9_]arguments[^a-zA-Z0-9_]/;
if(mArguments.test(src)) {
return ARG1;
}
let mFunction = /^function [a-zA-Z0-9_]+\(/g;
let result1 = mFunction.exec(src);
if(result1 == null) {
return ARG1;
}
let mFunction2 = /(\s*[,]?\s*[a-zA-Z0-9_]+)*\)/g;
mFunction2.lastIndex = mFunction.lastIndex;
let result12 = mFunction2.exec(src);
let mParameter = /\s*[,]?\s*[a-zA-Z0-9_]+/g;
let args:string[] = [];
let i = 0;
let result2:any;
while((result2 = mParameter.exec(result12[0])) != null) {
args.push(result2[0]+'?:any');
i++;
}
return '('+args.join('')+')';
}
let test = ():void => {
console.log('/// <reference path="locutus.d.ts" />');
for(let key1 in loc) {
for(let key2 in loc[key1]) {
for(let key3 in loc[key1][key2]) {
let modulename = 'locutus/' + key1 + '/' + key2 + '/' + key3;
testsub(modulename);
}
}
}
for(let key1 in loc) {
for(let key2 in loc[key1]) {
let modulename = 'locutus/' + key1 + '/' + key2;
testsub(modulename);
}
}
for(let key1 in loc) {
let modulename = 'locutus/' + key1;
testsub(modulename);
}
let modulename = 'locutus';
testsub(modulename);
}
let testsub = (modulename:string):void => {
let varname = modulename.replace(/[-/]/g,'_');
console.log("import " + varname + " = require('" + modulename + "');");
}
let settings = ():void => {
let s = '';
for(let key1 in loc) {
if(key1 != 'php') {
continue;
}
for(let key2 in loc[key1]) {
for(let key3 in loc[key1][key2]) {
if(s != '') {
s += ',\n';
}
let len = 21 - key3.length;
let tab = '';
while(len > 0) {
tab += '\t';
len -= 4;
}
//"var_dump": {"cod":"var_dump", "mod":["var_dump","locutus/php/var/var_dump"]}
s += '\t\t\t\t"' + key3 + '":' + tab + '{"cod":"' + key3 + '","mod":["' + key3 + '","locutus/' + key1 + '/' + key2 + '/' + key3 + '"]}';
}
}
}
console.log(s);
}
run();
+405 -290
View File
File diff suppressed because it is too large Load Diff
+418 -295
View File
File diff suppressed because it is too large Load Diff
+6 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for log4javascript v1.4.10
// Type definitions for log4javascript v1.4.13
// Project: http://log4javascript.org/
// Definitions by: Markus Wagner <https://github.com/Ritzlgrmft/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -126,6 +126,11 @@ declare namespace log4javascript {
*/
removeAllAppenders(): void;
/**
* Returns all appenders which will log a message.
*/
getEffectiveAppenders(): Appender[];
/**
* Sets the level. Log messages of a lower level than level will not be logged. Default value is DEBUG.
*/
+4 -7
View File
@@ -25,11 +25,11 @@ function test() {
}
function testAngle() {
makerjs.angle.areEqual(12, 13);
makerjs.angle.mirror(45, true, false);
makerjs.angle.noRevolutions(90);
makerjs.angle.ofArcEnd(paths.arc);
makerjs.angle.ofArcMiddle(paths.arc);
makerjs.angle.ofArcSpan(paths.arc);
makerjs.angle.ofLineInDegrees(paths.line);
makerjs.angle.ofPointInDegrees([0,0], [1,1]);
makerjs.angle.ofPointInRadians([0,0], [1,1]);
@@ -67,7 +67,9 @@ function test() {
}
function testMeasure() {
makerjs.measure.arcAngle(paths.arc);
makerjs.measure.isPointEqual(p1, p2);
makerjs.measure.isPathEqual(paths.line, paths.circle, 4);
makerjs.measure.isAngleEqual(12, 13);
makerjs.measure.isArcConcaveTowardsPoint(paths.arc, [0,0]);
makerjs.measure.isBetween(7, 8, 9, false);
makerjs.measure.isBetweenArcAngles(7, paths.arc, false);
@@ -119,7 +121,6 @@ function test() {
}
function testPath() {
makerjs.path.areEqual(paths.line, paths.circle, 4);
makerjs.path.breakAtPoint(paths.arc, [0,0]).type;
makerjs.path.dogbone(paths.line, paths.line, 7);
makerjs.path.fillet(paths.arc, paths.line, 4);
@@ -129,7 +130,6 @@ function test() {
makerjs.path.moveRelative(paths.circle, [0,0]);
makerjs.path.rotate(paths.line, 5, [0,0]);
makerjs.path.scale(paths.arc, 8);
makerjs.path.slopeIntersectionPoint(paths.line, paths.line);
}
function testPaths() {
@@ -156,8 +156,6 @@ function test() {
function testPoint() {
makerjs.point.add(p1, p2);
makerjs.point.areEqual(p1, p2);
makerjs.point.areEqualRounded(p1, p2);
makerjs.point.average(p1, p2);
makerjs.point.clone(p1);
makerjs.point.closest([0,0], [p1, p2]);
@@ -170,7 +168,6 @@ function test() {
makerjs.point.rotate(p1, 5, p2);
makerjs.point.rounded(p1);
makerjs.point.scale(p2, 8);
makerjs.point.serialize(p1);
makerjs.point.subtract(p2, p1);
makerjs.point.zero();
}
+553 -108
View File
@@ -2,6 +2,7 @@
// Project: https://github.com/Microsoft/maker.js
// Definitions by: Dan Marshall <https://github.com/danmarshall>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../pdfkit/pdfkit.d.ts" />
/**
* Root module for Maker.js.
*
@@ -37,6 +38,13 @@ declare namespace MakerJs {
* @param accuracy Optional exemplar of number of decimal places.
*/
function round(n: number, accuracy?: number): number;
/**
* Create a string representation of a route array.
*
* @param route Array of strings which are segments of a route.
* @returns String of the flattened array.
*/
function createRouteKey(route: string[]): string;
/**
* Clone an object.
*
@@ -89,6 +97,12 @@ declare namespace MakerJs {
*/
high: IPoint;
}
/**
* A map of measurements.
*/
interface IMeasureMap {
[key: string]: IMeasure;
}
/**
* A line, curved line or other simple two dimensional shape.
*/
@@ -181,7 +195,6 @@ declare namespace MakerJs {
function isPathArc(item: any): boolean;
/**
* A map of functions which accept a path as a parameter.
* @private
*/
interface IPathFunctionMap {
/**
@@ -191,7 +204,6 @@ declare namespace MakerJs {
}
/**
* A map of functions which accept a path and an origin point as parameters.
* @private
*/
interface IPathOriginFunctionMap {
/**
@@ -213,10 +225,31 @@ declare namespace MakerJs {
Circle: string;
Arc: string;
};
/**
* Slope and y-intercept of a line.
*/
interface ISlope {
/**
* Boolean to see if line has slope or is vertical.
*/
hasSlope: boolean;
/**
* Optional value of non-vertical slope.
*/
slope?: number;
/**
* Line used to calculate this slope.
*/
line: IPathLine;
/**
* Optional value of y when x = 0.
*/
yIntercept?: number;
}
/**
* Options to pass to path.intersection()
*/
interface IPathIntersectionOptions {
interface IPathIntersectionBaseOptions {
/**
* Optional boolean to only return deep intersections, i.e. not on an end point or tangent.
*/
@@ -226,6 +259,19 @@ declare namespace MakerJs {
*/
out_AreOverlapped?: boolean;
}
/**
* Options to pass to path.intersection()
*/
interface IPathIntersectionOptions extends IPathIntersectionBaseOptions {
/**
* Optional boolean to only return deep intersections, i.e. not on an end point or tangent.
*/
path1Offset?: IPoint;
/**
* Optional output variable which will be set to true if the paths are overlapped.
*/
path2Offset?: IPoint;
}
/**
* An intersection of two paths.
*/
@@ -268,6 +314,14 @@ declare namespace MakerJs {
* Point which is known to be outside of the model.
*/
farPoint?: IPoint;
/**
* Cached measurements for model A.
*/
measureA?: measure.Atlas;
/**
* Cached measurements for model B.
*/
measureB?: measure.Atlas;
}
/**
* Options to pass to model.findLoops.
@@ -278,6 +332,19 @@ declare namespace MakerJs {
*/
removeFromOriginal?: boolean;
}
/**
* Options to pass to model.simplify()
*/
interface ISimplifyOptions {
/**
* Optional
*/
pointMatchingDistance?: number;
/**
* Optional
*/
scalarMatchingDistance?: number;
}
/**
* A path that may be indicated to "flow" in either direction between its endpoints.
*/
@@ -370,11 +437,104 @@ declare namespace MakerJs {
pathId: string;
}
/**
* Path and its reference id within a model
* A route to either a path or a model, and the absolute offset of it.
*/
interface IRefPathInModel extends IRefPathIdInModel {
interface IRouteOffset {
layer: string;
offset: IPoint;
route: string[];
routeKey: string;
}
/**
* A path reference in a walk.
*/
interface IWalkPath extends IRefPathIdInModel, IRouteOffset {
pathContext: IPath;
}
/**
* Callback signature for path in model.walk().
*/
interface IWalkPathCallback {
(context: IWalkPath): void;
}
/**
* A link in a chain, with direction of flow.
*/
interface IChainLink {
/**
* Reference to the path.
*/
walkedPath: IWalkPath;
/**
* Path flows forwards or reverse.
*/
reversed: boolean;
/**
* The endpoints of the path, in absolute coords.
*/
endPoints: IPoint[];
}
/**
* A chain of paths which connect end to end.
*/
interface IChain {
/**
* The links in this chain.
*/
links: IChainLink[];
/**
* Flag if this chain forms a loop end to end.
*/
endless?: boolean;
}
/**
* Callback to model.findChains() with resulting array of chains and unchained paths.
*/
interface IChainCallback {
(chains: IChain[], loose: IWalkPath[], layer: string): void;
}
/**
* Options to pass to model.findLoops.
*/
interface IFindChainsOptions extends IPointMatchOptions {
/**
* Flag to separate chains by layers.
*/
byLayers?: boolean;
}
/**
* Reference to a model within a model.
*/
interface IRefModelInModel {
parentModel: IModel;
childId: string;
childModel: IModel;
}
/**
* A model reference in a walk.
*/
interface IWalkModel extends IRefModelInModel, IRouteOffset {
}
/**
* Callback signature for model.walk().
*/
interface IWalkModelCallback {
(context: IWalkModel): void;
}
/**
* Callback signature for model.walk(), which may return false to halt any further walking.
*/
interface IWalkModelCancellableCallback {
(context: IWalkModel): boolean;
}
/**
* Options to pass to model.walk().
*/
interface IWalkOptions {
onPath?: IWalkPathCallback;
beforeChildWalk?: IWalkModelCancellableCallback;
afterChildWalk?: IWalkModelCallback;
}
/**
* Describes a parameter and its limits.
*/
@@ -425,14 +585,6 @@ declare namespace MakerJs {
}
}
declare namespace MakerJs.angle {
/**
* Find out if two angles are equal.
*
* @param a First angle.
* @param b Second angle.
* @returns true if angles are the same, false if they are not
*/
function areEqual(angle1: number, angle2: number, accuracy?: number): boolean;
/**
* Ensures an angle is not greater than 360
*
@@ -469,6 +621,13 @@ declare namespace MakerJs.angle {
* @returns Middle angle of arc.
*/
function ofArcMiddle(arc: IPathArc, ratio?: number): number;
/**
* Total angle of an arc between its start and end angles.
*
* @param arc The arc to measure.
* @returns Angle of arc.
*/
function ofArcSpan(arc: IPathArc): number;
/**
* Angle of a line path.
*
@@ -512,23 +671,6 @@ declare namespace MakerJs.point {
* @returns A new point object.
*/
function add(a: IPoint, b: IPoint, subtract?: boolean): IPoint;
/**
* Find out if two points are equal.
*
* @param a First point.
* @param b Second point.
* @returns true if points are the same, false if they are not
*/
function areEqual(a: IPoint, b: IPoint, withinDistance?: number): boolean;
/**
* Find out if two points are equal after rounding.
*
* @param a First point.
* @param b Second point.
* @param accuracy Optional exemplar of number of decimal places.
* @returns true if points are the same, false if they are not
*/
function areEqualRounded(a: IPoint, b: IPoint, accuracy?: number): boolean;
/**
* Get the average of two points.
*
@@ -580,7 +722,16 @@ declare namespace MakerJs.point {
* @param pathContext The path object.
* @returns Array with 2 elements: [0] is the point object corresponding to the origin, [1] is the point object corresponding to the end.
*/
function fromPathEnds(pathContext: IPath): IPoint[];
function fromPathEnds(pathContext: IPath, pathOffset?: IPoint): IPoint[];
/**
* Calculates the intersection of slopes of two lines.
*
* @param lineA First line to use for slope.
* @param lineB Second line to use for slope.
* @param options Optional IPathIntersectionOptions.
* @returns point of intersection of the two slopes, or null if the slopes did not intersect.
*/
function fromSlopeIntersection(lineA: IPathLine, lineB: IPathLine, options?: IPathIntersectionBaseOptions): IPoint;
/**
* Get the middle point of a path.
*
@@ -623,14 +774,6 @@ declare namespace MakerJs.point {
* @returns A new point.
*/
function scale(pointToScale: IPoint, scaleValue: number): IPoint;
/**
* Get a string representation of a point.
*
* @param pointContext The point to serialize.
* @param accuracy Optional exemplar of number of decimal places.
* @returns String representing the point.
*/
function serialize(pointContext: IPoint, accuracy?: number): string;
/**
* Subtract a point from another point, and return the result as a new point. Shortcut to Add(a, b, subtract = true).
*
@@ -649,13 +792,12 @@ declare namespace MakerJs.point {
}
declare namespace MakerJs.path {
/**
* Find out if two paths are equal.
* Create a clone of a path. This is faster than cloneObject.
*
* @param a First path.
* @param b Second path.
* @returns true if paths are the same, false if they are not
* @param pathToClone The path to clone.
* @returns Cloned path.
*/
function areEqual(path1: IPath, path2: IPath, withinPointDistance?: number): boolean;
function clone(pathToClone: IPath): IPath;
/**
* Create a clone of a path, mirrored on either or both x and y axes.
*
@@ -679,9 +821,18 @@ declare namespace MakerJs.path {
*
* @param pathToMove The path to move.
* @param delta The x & y adjustments as a point object.
* @param subtract Optional boolean to subtract instead of add.
* @returns The original path (for chaining).
*/
function moveRelative(pathToMove: IPath, delta: IPoint): IPath;
function moveRelative(pathToMove: IPath, delta: IPoint, subtract?: boolean): IPath;
/**
* Move some paths relatively during a task execution, then unmove them.
*
* @param pathsToMove The paths to move.
* @param deltas The x & y adjustments as a point object array.
* @param task The function to call while the paths are temporarily moved.
*/
function moveTemporary(pathsToMove: IPath[], deltas: IPoint[], task: Function): void;
/**
* Rotate a path.
*
@@ -715,11 +866,6 @@ declare namespace MakerJs.path {
declare namespace MakerJs.paths {
/**
* Class for arc path.
*
* @param origin The center point of the arc.
* @param radius The radius of the arc.
* @param startAngle The start angle of the arc.
* @param endAngle The end angle of the arc.
*/
class Arc implements IPathArc {
origin: IPoint;
@@ -727,19 +873,71 @@ declare namespace MakerJs.paths {
startAngle: number;
endAngle: number;
type: string;
/**
* Class for arc path, created from origin point, radius, start angle, and end angle.
*
* @param origin The center point of the arc.
* @param radius The radius of the arc.
* @param startAngle The start angle of the arc.
* @param endAngle The end angle of the arc.
*/
constructor(origin: IPoint, radius: number, startAngle: number, endAngle: number);
/**
* Class for arc path, created from 2 points, radius, large Arc flag, and clockwise flag.
*
* @param pointA First end point of the arc.
* @param pointB Second end point of the arc.
* @param radius The radius of the arc.
* @param largeArc Boolean flag to indicate clockwise direction.
* @param clockwise Boolean flag to indicate clockwise direction.
*/
constructor(pointA: IPoint, pointB: IPoint, radius: number, largeArc: boolean, clockwise: boolean);
/**
* Class for arc path, created from 2 points and optional boolean flag indicating clockwise.
*
* @param pointA First end point of the arc.
* @param pointB Second end point of the arc.
* @param clockwise Boolean flag to indicate clockwise direction.
*/
constructor(pointA: IPoint, pointB: IPoint, clockwise?: boolean);
/**
* Class for arc path, created from 3 points.
*
* @param pointA First end point of the arc.
* @param pointB Middle point on the arc.
* @param pointC Second end point of the arc.
*/
constructor(pointA: IPoint, pointB: IPoint, pointC: IPoint);
}
/**
* Class for circle path.
*
* @param origin The center point of the circle.
* @param radius The radius of the circle.
*/
class Circle implements IPathCircle {
type: string;
origin: IPoint;
radius: number;
type: string;
/**
* Class for circle path, created from origin point and radius.
*
* @param origin The center point of the circle.
* @param radius The radius of the circle.
*/
constructor(origin: IPoint, radius: number);
/**
* Class for circle path, created from 2 points.
*
* @param pointA First point on the circle.
* @param pointB Second point on the circle.
*/
constructor(pointA: IPoint, pointB: IPoint);
/**
* Class for circle path, created from 3 points.
*
* @param pointA First point on the circle.
* @param pointB Second point on the circle.
* @param pointC Third point on the circle.
*/
constructor(pointA: IPoint, pointB: IPoint, pointC: IPoint);
}
/**
* Class for line path.
@@ -832,6 +1030,14 @@ declare namespace MakerJs.model {
* @returns The original model (for chaining).
*/
function moveRelative(modelToMove: IModel, delta: IPoint): IModel;
/**
* Prefix the ids of paths in a model.
*
* @param modelToPrefix The model to prefix.
* @param prefix The prefix to prepend on paths ids.
* @returns The original model (for chaining).
*/
function prefixPathIds(modelToPrefix: IModel, prefix: string): IModel;
/**
* Rotate a model.
*
@@ -865,6 +1071,15 @@ declare namespace MakerJs.model {
* @param callback Callback for each path.
*/
function walkPaths(modelContext: IModel, callback: IModelPathCallback): void;
/**
* Recursively walk through all paths for a given model.
*
* @param modelContext The model to walk.
* @param pathCallback Callback for each path.
* @param modelCallbackBeforeWalk Callback for each model prior to recursion, which can cancel the recursion if it returns false.
* @param modelCallbackAfterWalk Callback for each model after recursion.
*/
function walk(modelContext: IModel, options: IWalkOptions): void;
}
declare namespace MakerJs.model {
/**
@@ -875,7 +1090,7 @@ declare namespace MakerJs.model {
* @param farPoint Optional point of reference which is outside the bounds of the modelContext.
* @returns Boolean true if the path is inside of the modelContext.
*/
function isPathInsideModel(pathContext: IPath, modelContext: IModel, farPoint?: IPoint): boolean;
function isPathInsideModel(pathContext: IPath, modelContext: IModel, pathOffset?: IPoint, farPoint?: IPoint, measureAtlas?: measure.Atlas): boolean;
/**
* Break a model's paths everywhere they intersect with another path.
*
@@ -884,7 +1099,7 @@ declare namespace MakerJs.model {
*/
function breakPathsAtIntersections(modelToBreak: IModel, modelToIntersect?: IModel): void;
/**
* Combine 2 models. The models should be originated, and every path within each model should be part of a loop.
* Combine 2 models.
*
* @param modelA First model to combine.
* @param modelB Second model to combine.
@@ -896,6 +1111,106 @@ declare namespace MakerJs.model {
* @param farPoint Optional point of reference which is outside the bounds of both models.
*/
function combine(modelA: IModel, modelB: IModel, includeAInsideB?: boolean, includeAOutsideB?: boolean, includeBInsideA?: boolean, includeBOutsideA?: boolean, options?: ICombineOptions): void;
/**
* Combine 2 models, resulting in a intersection.
*
* @param modelA First model to combine.
* @param modelB Second model to combine.
*/
function combineIntersection(modelA: IModel, modelB: IModel): void;
/**
* Combine 2 models, resulting in a subtraction of B from A.
*
* @param modelA First model to combine.
* @param modelB Second model to combine.
*/
function combineSubtraction(modelA: IModel, modelB: IModel): void;
/**
* Combine 2 models, resulting in a union.
*
* @param modelA First model to combine.
* @param modelB Second model to combine.
*/
function combineUnion(modelA: IModel, modelB: IModel): void;
}
declare namespace MakerJs {
/**
* Compare keys to see if they are equal.
*/
interface ICollectionKeyComparer<K> {
(a: K, b: K): boolean;
}
/**
* A collection for items that share a common key.
*/
interface ICollection<K, T> {
key: K;
items: T[];
}
/**
* Collects items that share a common key.
*/
class Collector<K, T> {
private comparer;
collections: ICollection<K, T>[];
constructor(comparer?: ICollectionKeyComparer<K>);
addItemToCollection(key: K, item: T): void;
findCollection(key: K, action?: (index: number) => void): T[];
removeCollection(key: K): boolean;
removeItemFromCollection(key: K, item: T): boolean;
getCollectionsOfMultiple(cb: (key: K, items: T[]) => void): void;
}
}
declare namespace MakerJs.model {
/**
* Simplify a model's paths by reducing redundancy: combine multiple overlapping paths into a single path. The model must be originated.
*
* @param modelContext The originated model to search for similar paths.
* @param options Optional options object.
* @returns The simplified model (for chaining).
*/
function simplify(modelToSimplify: IModel, options?: ISimplifyOptions): IModel;
}
declare namespace MakerJs.path {
/**
* Expand path by creating a model which surrounds it.
*
* @param pathToExpand Path to expand.
* @param expansion Distance to expand.
* @param isolateCaps Optional flag to put the end caps into a separate model named "caps".
* @returns Model which surrounds the path.
*/
function expand(pathToExpand: IPath, expansion: number, isolateCaps?: boolean): IModel;
/**
* Represent an arc using straight lines.
*
* @param arc Arc to straighten.
* @param bevel Optional flag to bevel the angle to prevent it from being too sharp.
* @param prefix Optional prefix to apply to path ids.
* @returns Model of straight lines with same endpoints as the arc.
*/
function straighten(arc: IPathArc, bevel?: boolean, prefix?: string): IModel;
}
declare namespace MakerJs.model {
/**
* Expand all paths in a model, then combine the resulting expansions.
*
* @param modelToExpand Model to expand.
* @param distance Distance to expand.
* @param joints Number of points at a joint between paths. Use 0 for round joints, 1 for pointed joints, 2 for beveled joints.
* @returns Model which surrounds the paths of the original model.
*/
function expandPaths(modelToExpand: IModel, distance: number, joints?: number, combineOptions?: ICombineOptions): IModel;
/**
* Outline a model by a specified distance. Useful for accommodating for kerf.
*
* @param modelToOutline Model to outline.
* @param distance Distance to outline.
* @param joints Number of points at a joint between paths. Use 0 for round joints, 1 for pointed joints, 2 for beveled joints.
* @param inside Optional boolean to draw lines inside the model instead of outside.
* @returns Model which surrounds the paths outside of the original model.
*/
function outline(modelToOutline: IModel, distance: number, joints?: number, inside?: boolean): IModel;
}
declare namespace MakerJs.units {
/**
@@ -909,12 +1224,48 @@ declare namespace MakerJs.units {
}
declare namespace MakerJs.measure {
/**
* Total angle of an arc between its start and end angles.
* Find out if two angles are equal.
*
* @param arc The arc to measure.
* @returns Angle of arc.
* @param angleA First angle.
* @param angleB Second angle.
* @returns true if angles are the same, false if they are not
*/
function arcAngle(arc: IPathArc): number;
function isAngleEqual(angleA: number, angleB: number, accuracy?: number): boolean;
/**
* Find out if two paths are equal.
*
* @param pathA First path.
* @param pathB Second path.
* @returns true if paths are the same, false if they are not
*/
function isPathEqual(pathA: IPath, pathB: IPath, withinPointDistance?: number, pathAOffset?: IPoint, pathBOffset?: IPoint): boolean;
/**
* Find out if two points are equal.
*
* @param a First point.
* @param b Second point.
* @returns true if points are the same, false if they are not
*/
function isPointEqual(a: IPoint, b: IPoint, withinDistance?: number): boolean;
/**
* Check for slope equality.
*
* @param slopeA The ISlope to test.
* @param slopeB The ISlope to check for equality.
* @returns Boolean true if slopes are equal.
*/
function isSlopeEqual(slopeA: ISlope, slopeB: ISlope): boolean;
}
declare namespace MakerJs.measure {
/**
* Increase a measurement by an additional measurement.
*
* @param baseMeasure The measurement to increase.
* @param addMeasure The additional measurement.
* @param addOffset Optional offset point of the additional measurement.
* @returns The increased original measurement (for chaining).
*/
function increase(baseMeasure: IMeasure, addMeasure: IMeasure): IMeasure;
/**
* Check for arc being concave or convex towards a given point.
*
@@ -923,16 +1274,25 @@ declare namespace MakerJs.measure {
* @returns Boolean true if arc is concave towards point.
*/
function isArcConcaveTowardsPoint(arc: IPathArc, towardsPoint: IPoint): boolean;
/**
* Check for arc overlapping another arc.
*
* @param arcA The arc to test.
* @param arcB The arc to check for overlap.
* @param excludeTangents Boolean to exclude exact endpoints and only look for deep overlaps.
* @returns Boolean true if arc1 is overlapped with arcB.
*/
function isArcOverlapping(arcA: IPathArc, arcB: IPathArc, excludeTangents: boolean): boolean;
/**
* Check if a given number is between two given limits.
*
* @param valueInQuestion The number to test.
* @param limit1 First limit.
* @param limit2 Second limit.
* @param limitA First limit.
* @param limitB Second limit.
* @param exclusive Flag to exclude equaling the limits.
* @returns Boolean true if value is between (or equal to) the limits.
*/
function isBetween(valueInQuestion: number, limit1: number, limit2: number, exclusive: boolean): boolean;
function isBetween(valueInQuestion: number, limitA: number, limitB: number, exclusive: boolean): boolean;
/**
* Check if a given angle is between an arc's start and end angles.
*
@@ -951,6 +1311,27 @@ declare namespace MakerJs.measure {
* @returns Boolean true if point is between (or equal to) the line's origin and end points.
*/
function isBetweenPoints(pointInQuestion: IPoint, line: IPathLine, exclusive: boolean): boolean;
/**
* Check for line overlapping another line.
*
* @param lineA The line to test.
* @param lineB The line to check for overlap.
* @param excludeTangents Boolean to exclude exact endpoints and only look for deep overlaps.
* @returns Boolean true if line1 is overlapped with lineB.
*/
function isLineOverlapping(lineA: IPathLine, lineB: IPathLine, excludeTangents: boolean): boolean;
/**
* Check for measurement overlapping another measurement.
*
* @param measureA The measurement to test.
* @param measureB The measurement to check for overlap.
* @returns Boolean true if measure1 is overlapped with measureB.
*/
function isMeasurementOverlapping(measureA: IMeasure, measureB: IMeasure): boolean;
/**
* Gets the slope of a line.
*/
function lineSlope(line: IPathLine): ISlope;
/**
* Calculates the distance between two points.
*
@@ -965,7 +1346,7 @@ declare namespace MakerJs.measure {
* @param pathToMeasure The path to measure.
* @returns object with low and high points.
*/
function pathExtents(pathToMeasure: IPath): IMeasure;
function pathExtents(pathToMeasure: IPath, addOffset?: IPoint): IMeasure;
/**
* Measures the length of a path.
*
@@ -977,9 +1358,38 @@ declare namespace MakerJs.measure {
* Measures the smallest rectangle which contains a model.
*
* @param modelToMeasure The model to measure.
* @param atlas Optional atlas to save measurements.
* @returns object with low and high points.
*/
function modelExtents(modelToMeasure: IModel): IMeasure;
function modelExtents(modelToMeasure: IModel, atlas?: measure.Atlas): IMeasure;
/**
* A list of maps of measurements.
*
* @param modelToMeasure The model to measure.
* @param atlas Optional atlas to save measurements.
* @returns object with low and high points.
*/
class Atlas {
modelContext: IModel;
/**
* Flag that models have been measured.
*/
modelsMeasured: boolean;
/**
* Map of model measurements, mapped by routeKey.
*/
modelMap: IMeasureMap;
/**
* Map of path measurements, mapped by routeKey.
*/
pathMap: IMeasureMap;
/**
* Constructor.
* @param modelContext The model to measure.
*/
constructor(modelContext: IModel);
measureModels(): void;
}
}
declare namespace MakerJs.exporter {
/**
@@ -1050,12 +1460,12 @@ declare namespace MakerJs.solvers {
/**
* Solves for the angle of a triangle when you know lengths of 3 sides.
*
* @param length1 Length of side of triangle, opposite of the angle you are trying to find.
* @param length2 Length of any other side of the triangle.
* @param length3 Length of the remaining side of the triangle.
* @param lengthA Length of side of triangle, opposite of the angle you are trying to find.
* @param lengthB Length of any other side of the triangle.
* @param lengthC Length of the remaining side of the triangle.
* @returns Angle opposite of the side represented by the first parameter.
*/
function solveTriangleSSS(length1: number, length2: number, length3: number): number;
function solveTriangleSSS(lengthA: number, lengthB: number, lengthC: number): number;
/**
* Solves for the length of a side of a triangle when you know length of one side and 2 angles.
*
@@ -1076,33 +1486,24 @@ declare namespace MakerJs.path {
* @returns IPathIntersection object, with points(s) of intersection (and angles, when a path is an arc or circle); or null if the paths did not intersect.
*/
function intersection(path1: IPath, path2: IPath, options?: IPathIntersectionOptions): IPathIntersection;
/**
* Calculates the intersection of slopes of two lines.
*
* @param line1 First line to use for slope.
* @param line2 Second line to use for slope.
* @param options Optional IPathIntersectionOptions.
* @returns point of intersection of the two slopes, or null if the slopes did not intersect.
*/
function slopeIntersectionPoint(line1: IPathLine, line2: IPathLine, options?: IPathIntersectionOptions): IPoint;
}
declare namespace MakerJs.path {
/**
* Adds a round corner to the outside angle between 2 lines. The lines must meet at one point.
*
* @param line1 First line to fillet, which will be modified to fit the fillet.
* @param line2 Second line to fillet, which will be modified to fit the fillet.
* @param lineA First line to fillet, which will be modified to fit the fillet.
* @param lineB Second line to fillet, which will be modified to fit the fillet.
* @returns Arc path object of the new fillet.
*/
function dogbone(line1: IPathLine, line2: IPathLine, filletRadius: number, options?: IPointMatchOptions): IPathArc;
function dogbone(lineA: IPathLine, lineB: IPathLine, filletRadius: number, options?: IPointMatchOptions): IPathArc;
/**
* Adds a round corner to the inside angle between 2 paths. The paths must meet at one point.
*
* @param path1 First path to fillet, which will be modified to fit the fillet.
* @param path2 Second path to fillet, which will be modified to fit the fillet.
* @param pathA First path to fillet, which will be modified to fit the fillet.
* @param pathB Second path to fillet, which will be modified to fit the fillet.
* @returns Arc path object of the new fillet.
*/
function fillet(path1: IPath, path2: IPath, filletRadius: number, options?: IPointMatchOptions): IPathArc;
function fillet(pathA: IPath, pathB: IPath, filletRadius: number, options?: IPointMatchOptions): IPathArc;
}
declare namespace MakerJs.kit {
/**
@@ -1123,22 +1524,15 @@ declare namespace MakerJs.kit {
}
declare namespace MakerJs.model {
/**
* @private
* Find paths that have common endpoints and form chains.
*
* @param modelContext The model to search for chains.
* @param options Optional options object.
* @returns A list of chains.
*/
interface IPointMappedItem<T> {
averagePoint: IPoint;
item: T;
}
/**
* @private
*/
class PointMap<T> {
matchingDistance: number;
list: IPointMappedItem<T>[];
constructor(matchingDistance?: number);
add(pointToAdd: IPoint, item: T): void;
find(pointToFind: IPoint, saveAverage: boolean): T;
}
function findChains(modelContext: IModel, callback: IChainCallback, options?: IFindChainsOptions): void;
}
declare namespace MakerJs.model {
/**
* Find paths that have common endpoints and form loops.
*
@@ -1153,7 +1547,14 @@ declare namespace MakerJs.model {
* @param loopToDetach The model to search for loops.
*/
function detachLoop(loopToDetach: IModel): void;
function removeDeadEnds(modelContext: IModel, pointMatchingDistance?: number): void;
/**
* Remove paths from a model which have endpoints that do not connect to other paths.
*
* @param modelContext The model to search for dead ends.
* @param options Optional options object.
* @returns The input model (for chaining).
*/
function removeDeadEnds(modelContext: IModel, pointMatchingDistance?: number): IModel;
}
declare namespace MakerJs.exporter {
/**
@@ -1249,6 +1650,37 @@ declare namespace MakerJs.exporter {
}
}
declare namespace MakerJs.exporter {
/**
* Injects drawing into a PDFKit document.
*
* @param modelToExport Model object to export.
* @param options Export options object.
* @returns String of PDF file contents.
*/
function toPDF(doc: PDFKit.PDFDocument, modelToExport: IModel, options?: IPDFRenderOptions): void;
/**
* PDF rendering options.
*/
interface IPDFRenderOptions extends IExportOptions {
/**
* Rendered reference origin.
*/
origin?: IPoint;
/**
* SVG color of the rendered paths.
*/
stroke?: string;
}
}
declare namespace MakerJs.exporter {
/**
* Convert a chain to SVG path data.
*/
function chainToSVGPathData(chain: IChain, offset: IPoint): string;
/**
* Convert a path to SVG path data.
*/
function pathToSVGPathData(pathToExport: IPath, offset: IPoint, offset2: IPoint): string;
function toSVG(modelToExport: IModel, options?: ISVGRenderOptions): string;
function toSVG(pathsToExport: IPath[], options?: ISVGRenderOptions): string;
function toSVG(pathToExport: IPath, options?: ISVGRenderOptions): string;
@@ -1273,6 +1705,10 @@ declare namespace MakerJs.exporter {
* Optional attributes to add to the root svg tag.
*/
svgAttrs?: IXmlTagAttrs;
/**
* SVG fill color.
*/
fill?: string;
/**
* SVG font size and font size units.
*/
@@ -1314,9 +1750,11 @@ declare namespace MakerJs.models {
}
}
declare namespace MakerJs.models {
class Polygon extends ConnectTheDots {
constructor(numberOfSides: number, radius: number, firstCornerAngleInDegrees?: number);
static getPoints(numberOfSides: number, radius: number, firstCornerAngleInDegrees?: number): IPoint[];
class Polygon implements IModel {
paths: IPathMap;
constructor(numberOfSides: number, radius: number, firstCornerAngleInDegrees?: number, circumscribed?: boolean);
static circumscribedRadius(radius: number, angleInRadians: number): number;
static getPoints(numberOfSides: number, radius: number, firstCornerAngleInDegrees?: number, circumscribed?: boolean): IPoint[];
}
}
declare namespace MakerJs.models {
@@ -1344,19 +1782,24 @@ declare namespace MakerJs.models {
}
}
declare namespace MakerJs.models {
class Oval extends RoundRectangle {
class Oval implements IModel {
paths: IPathMap;
constructor(width: number, height: number);
}
}
declare namespace MakerJs.models {
class OvalArc implements IModel {
paths: IPathMap;
constructor(startAngle: number, endAngle: number, sweepRadius: number, slotRadius: number, selfIntersect?: boolean);
models: IModelMap;
constructor(startAngle: number, endAngle: number, sweepRadius: number, slotRadius: number, selfIntersect?: boolean, isolateCaps?: boolean);
}
}
declare namespace MakerJs.models {
class Rectangle extends ConnectTheDots {
class Rectangle implements IModel {
paths: IPathMap;
origin: IPoint;
constructor(width: number, height: number);
constructor(measurement: IMeasure);
}
}
declare namespace MakerJs.models {
@@ -1375,11 +1818,13 @@ declare namespace MakerJs.models {
class Slot implements IModel {
paths: IPathMap;
origin: IPoint;
constructor(origin: IPoint, endPoint: IPoint, radius: number);
models: IModelMap;
constructor(origin: IPoint, endPoint: IPoint, radius: number, isolateCaps?: boolean);
}
}
declare namespace MakerJs.models {
class Square extends Rectangle {
class Square implements IModel {
paths: IPathMap;
constructor(side: number);
}
}
+5 -3
View File
@@ -1587,18 +1587,20 @@ declare namespace __MaterialUI {
export class Tabs extends React.Component<TabsProps, {}> {
}
interface TabProps extends React.Props<Tab> {
interface TabProps extends SharedEnhancedButtonProps<Tab> {
className?: string;
icon?: React.ReactNode;
label?: React.ReactNode;
onActive?: (tab: Tab) => void;
onTouchTap?: (value: any, e: TouchTapEvent, tab: Tab) => void;
onTouchTap?: (value: any, e?: TouchTapEvent, tab?: Tab) => void;
selected?: boolean;
style?: React.CSSProperties;
value?: any;
width?: string;
disabled?: boolean;
}
export class Tab extends React.Component<TabProps, {}> {
export class Tab extends React.Component<
TabProps, {}> {
}
}
+5
View File
@@ -2208,3 +2208,8 @@ declare namespace mathjs {
toString(): string;
}
}
declare module 'mathjs'{
export = math;
}

Some files were not shown because too many files have changed in this diff Show More