Merge remote-tracking branch 'refs/remotes/DefinitelyTyped/master'

This commit is contained in:
CaselIT
2016-01-25 19:00:10 +01:00
49 changed files with 5078 additions and 1622 deletions
+1 -1
View File
@@ -7,7 +7,7 @@
/// <reference path='../node/node.d.ts'/>
/// <reference path='../redis/redis.d.ts'/>
/// <reference path="../mongodb/mongodb.d.ts" />
/// <reference path="../mongodb/mongodb-1.4.9.d.ts" />
declare module "acl" {
import http = require('http');
+165 -59
View File
@@ -1,68 +1,114 @@
/// <reference path="../jasmine/jasmine.d.ts" />
/// <reference path="../angularjs/angular.d.ts" />
/// <reference path="../angularjs/angular-mocks.d.ts" />
/// <reference path="angular-wizard.d.ts" />
// test file taken from https://github.com/mgonto/angular-wizard
interface WizardScope extends ng.IScope {
referenceCurrentStep:string;
stepValidation:()=>void;
finishedWizard:()=>void;
enterValidation:()=>void;
interface IWizardScope extends ng.IScope {
referenceCurrentStep: string;
stepValidation: () => void;
finishedWizard: () => void;
enterValidation: () => void;
exitValidation: boolean;
dynamicStepDisabled: string;
}
describe('AngularWizard', function () {
var $compile:ng.ICompileService,
$rootScope:ng.IRootScopeService, WizardHandler:angular.mgoAngularWizard.WizardHandler, scope:WizardScope;
var $compile: ng.ICompileService,
$q: ng.IQService,
$rootScope: ng.IRootScopeService,
$timeout: ng.ITimeoutService,
WizardHandler: angular.mgoAngularWizard.WizardHandler;
beforeEach(() => angular.module('mgo-angular-wizard'));
beforeEach(inject(function (_$compile_: ng.ICompileService,
_$q_: ng.IQService,
_$rootScope_: ng.IRootScopeService,
_$timeout_: ng.ITimeoutService,
_WizardHandler_: angular.mgoAngularWizard.WizardHandler) {
$compile = _$compile_;
$q = _$q_;
$rootScope = _$rootScope_;
$timeout = _$timeout_;
WizardHandler = _WizardHandler_;
}));
/**
* Create the view with wizard to test
* Create the generic view with wizard to test
* @param {Scope} scope A scope to bind to
* @return {[DOM element]} A DOM element compiled
*/
function createView(scope:WizardScope) {
function createGenericView(scope: IWizardScope) {
scope.referenceCurrentStep = null;
var element = angular.element('<wizard on-finish="finishedWizard()" current-step="referenceCurrentStep" ng-init="msg = 14" >'
+ ' <wz-step title="Starting" canenter="enterValidation">'
+ ' <h1>This is the first step</h1>'
+ ' <p>Here you can use whatever you want. You can use other directives, binding, etc.</p>'
+ ' <input type="submit" wz-next value="Continue" />'
+ ' </wz-step>'
+ ' <wz-step title="Continuing" canexit="stepValidation">'
+ ' <h1>Continuing</h1>'
+ ' <p>You have continued here!</p>'
+ ' <input type="submit" wz-next value="Go on" />'
+ ' </wz-step>'
+ ' <wz-step title="More steps" canenter="enterValidation">'
+ ' <p>Even more steps!!</p>'
+ ' <input type="submit" wz-next value="Finish now" />'
+ ' </wz-step>'
+ '</wizard>');
+ ' <wz-step wz-title="Starting" canenter="enterValidation" description="Step description">'
+ ' <h1>This is the first step</h1>'
+ ' <p>Here you can use whatever you want. You can use other directives, binding, etc.</p>'
+ ' <input type="submit" wz-next value="Continue" />'
+ ' </wz-step>'
+ ' <wz-step wz-title="Dynamic" wz-disabled="{{dynamicStepDisabled == \'Y\'}}">'
+ ' <h1>Dynamic {{dynamicStepDisabled}}</h1>'
+ ' <p>You have continued here!</p>'
+ ' <input type="submit" wz-next value="Go on" />'
+ ' </wz-step>'
+ ' <wz-step wz-title="Continuing" canexit="stepValidation">'
+ ' <h1>Continuing</h1>'
+ ' <p>You have continued here!</p>'
+ ' <input type="submit" wz-next value="Go on" />'
+ ' </wz-step>'
+ ' <wz-step wz-title="More steps" canenter="enterValidation">'
+ ' <p>Even more steps!!</p>'
+ ' <input type="submit" wz-next value="Finish now" />'
+ ' </wz-step>'
+ '</wizard>');
var elementCompiled = $compile(element)(scope);
$rootScope.$digest();
return elementCompiled;
}
it("should correctly create the wizard", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
var view = createGenericView(scope);
expect(WizardHandler).toBeTruthy();
expect(view.find('section').length).toEqual(3);
expect(view.find('section').length).toEqual(4);
// expect the correct step to be desirable one
expect(scope.referenceCurrentStep).toEqual('Starting');
});
it("should go to the next step", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Dynamic');
});
it("should render only those steps which are enabled", function () {
var scope =<IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Continuing');
});
it("should enable or disable dynamic steps based on conditions", function () {
var scope = <IWizardScope>$rootScope.$new();
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
scope.dynamicStepDisabled = 'Y';
$rootScope.$digest();
WizardHandler.wizard().goTo(2);
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('More steps');
});
it("should return to a previous step", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next();
$rootScope.$digest();
@@ -72,24 +118,27 @@ describe('AngularWizard', function () {
expect(scope.referenceCurrentStep).toEqual('Starting');
});
it("should go to a step specified by name", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().goTo('More steps');
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('More steps');
});
it("should go to a step specified by index", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().goTo(2);
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('More steps');
});
it("should go to next step becasue callback is truthy", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next(function () {
return true
@@ -98,8 +147,9 @@ describe('AngularWizard', function () {
expect(scope.referenceCurrentStep).toEqual('Continuing');
});
it("should NOT go to next step because callback is falsey", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next(function () {
return false
@@ -108,16 +158,18 @@ describe('AngularWizard', function () {
expect(scope.referenceCurrentStep).toEqual('Starting');
});
it("should go to next step because CANEXIT is UNDEFINED", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Continuing');
});
it("should go to next step because CANEXIT is TRUE", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
scope.stepValidation = function () {
return true;
};
@@ -130,8 +182,9 @@ describe('AngularWizard', function () {
expect(scope.referenceCurrentStep).toEqual('More steps');
});
it("should NOT go to next step because CANEXIT is FALSE", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
scope.stepValidation = function () {
return false;
};
@@ -144,8 +197,9 @@ describe('AngularWizard', function () {
expect(scope.referenceCurrentStep).toEqual('Continuing');
});
it("should go to next step because CANENTER is TRUE", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
scope.enterValidation = function () {
return true;
};
@@ -158,8 +212,9 @@ describe('AngularWizard', function () {
expect(scope.referenceCurrentStep).toEqual('More steps');
});
it("should NOT go to next step because CANENTER is FALSE", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
scope.enterValidation = function () {
return false;
};
@@ -172,8 +227,9 @@ describe('AngularWizard', function () {
expect(scope.referenceCurrentStep).toEqual('Continuing');
});
it("should NOT return to a previous step. Although CANEXIT is false and we are heading to a previous state, the can enter validation is false", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
scope.stepValidation = function () {
return false;
};
@@ -189,8 +245,9 @@ describe('AngularWizard', function () {
expect(scope.referenceCurrentStep).toEqual('Continuing');
});
it("should return to a previous step even though CANEXIT is false", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
scope.stepValidation = function () {
return false;
};
@@ -202,17 +259,66 @@ describe('AngularWizard', function () {
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Starting');
});
it("should finish", function () {
var flag = false;
scope.finishedWizard = function () {
flag = true;
it("should go to the next step because the promise that CANENTER returns resolves to true", function (done) {
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
scope.enterValidation = function () {
var deferred = $q.defer();
$timeout(function () {
deferred.resolve(true);
done();
});
return deferred.promise;
};
var view = createView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Continuing');
WizardHandler.wizard().next();
$timeout.flush();
expect(scope.referenceCurrentStep).toEqual('More steps');
});
it("should go to the next step because CANEXIT is set to true", function () {
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
scope.exitValidation = true;
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Continuing');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('More steps');
});
it("should finish", function () {
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var flag = false;
scope.finishedWizard = function () { flag = true; };
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().finish();
expect(flag).toBeTruthy();
$rootScope.$digest();
});
it("should go to first step when reset is called", function () {
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().goTo(2);
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('More steps');
WizardHandler.wizard().reset();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Starting');
});
it("step description should be accessible", function () {
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
expect((<any>view.isolateScope()).steps[0].description).toEqual('Step description');
});
});
+28 -11
View File
@@ -1,21 +1,38 @@
// Type definitions for Angular Wizard 0.4.2
// Type definitions for Angular Wizard 0.6.1
// Project: https://github.com/mgonto/angular-wizard
// Definitions by: Marko Jurisic <https://github.com/mjurisic>
// Definitions by: Marko Jurisic <https://github.com/mjurisic>, Ronald Wildenberg <https://github.com/rwwilden>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module angular.mgoAngularWizard {
interface WizardHandler {
wizard(name?:string): Wizard;
addWizard(name:string, wizard:Wizard):void;
removeWizard(name:string):void;
wizard(name?: string): Wizard;
addWizard(name: string, wizard: Wizard): void;
removeWizard(name: string): void;
}
interface Wizard {
next(nextHandler?:Function):void;
previous():void;
goTo(step:number):void;
goTo(step:string):void;
finish():void;
currentStepNumber():number;
next(nextHandler?: () => boolean): void;
previous(): void;
cancel: () => void;
goTo(step: number | string): void;
finish(): void;
reset: () => void;
addStep: (step: WzStep) => void;
currentStep: () => WzStep;
currentStepNumber(): number;
currentStepDescription: () => string;
currentStepTitle: () => string;
getEnabledSteps(): WzStep[];
}
interface WzStep {
canenter: (...args: any[]) => boolean;
canexit: (...args: any[]) => boolean;
description: string;
selected: boolean;
title: string;
wzData: any;
wzTitle: string;
}
}
@@ -1,37 +1,44 @@
/// <reference path="cordova-plugin-qrscanner.d.ts" />
var QRScanner: QRScanner = window.QRScanner;
QRScanner.prepare()
QRScanner.prepare((err, status) => { var error: Error = err; var obj: QRScannerStatus = status; })
QRScanner.scan((err, results) => { var error: Error = err; var contents: String = results; })
QRScanner.cancelScan()
QRScanner.cancelScan((status) => {var obj: QRScannerStatus = status; })
QRScanner.show()
QRScanner.show((status) => {var obj: QRScannerStatus = status; })
QRScanner.hide()
QRScanner.hide((status) => {var obj: QRScannerStatus = status; })
QRScanner.enableLight()
QRScanner.enableLight((err, status) => { var error: Error = err; var obj: QRScannerStatus = status; })
QRScanner.disableLight()
QRScanner.disableLight((err, status) => { var error: Error = err; var obj: QRScannerStatus = status; })
QRScanner.useCamera(1)
QRScanner.useCamera(1, (err, status) => { var error: Error = err; var obj: QRScannerStatus = status; })
QRScanner.useFrontCamera()
QRScanner.useFrontCamera((err, status) => { var error: Error = err; var obj: QRScannerStatus = status; })
QRScanner.useBackCamera()
QRScanner.useBackCamera((err, status) => { var error: Error = err; var obj: QRScannerStatus = status; })
QRScanner.pausePreview()
QRScanner.pausePreview((status) => {var obj: QRScannerStatus = status; })
QRScanner.resumePreview()
QRScanner.resumePreview((status) => {var obj: QRScannerStatus = status; })
QRScanner.openSettings()
QRScanner.openSettings((err, status) => { var error: Error = err; var obj: QRScannerStatus = status; })
QRScanner.destroy()
QRScanner.destroy((status) => {var obj: QRScannerStatus = status; })
QRScanner.prepare();
QRScanner.prepare((err, status) => { var error: QRScannerError = err; var obj: QRScannerStatus = status; });
QRScanner.scan((err, results) => { var error: QRScannerError = err; var contents: String = results; });
QRScanner.cancelScan();
QRScanner.cancelScan((status) => {var obj: QRScannerStatus = status; });
QRScanner.show();
QRScanner.show((status) => {var obj: QRScannerStatus = status; });
QRScanner.hide();
QRScanner.hide((status) => {var obj: QRScannerStatus = status; });
QRScanner.enableLight();
QRScanner.enableLight((err, status) => { var error: QRScannerError = err; var obj: QRScannerStatus = status; });
QRScanner.disableLight();
QRScanner.disableLight((err, status) => { var error: QRScannerError = err; var obj: QRScannerStatus = status; });
QRScanner.useCamera(1);
QRScanner.useCamera(1, (err, status) => { var error: QRScannerError = err; var obj: QRScannerStatus = status; });
QRScanner.useFrontCamera();
QRScanner.useFrontCamera((err, status) => { var error: QRScannerError = err; var obj: QRScannerStatus = status; });
QRScanner.useBackCamera();
QRScanner.useBackCamera((err, status) => { var error: QRScannerError = err; var obj: QRScannerStatus = status; });
QRScanner.pausePreview();
QRScanner.pausePreview((status) => {var obj: QRScannerStatus = status; });
QRScanner.resumePreview();
QRScanner.resumePreview((status) => {var obj: QRScannerStatus = status; });
QRScanner.openSettings();
QRScanner.openSettings((err, status) => { var error: QRScannerError = err; var obj: QRScannerStatus = status; });
QRScanner.destroy();
QRScanner.destroy((status) => {var obj: QRScannerStatus = status; });
QRScanner.prepare((err, status) => {
var error: QRScannerError = err;
var num: Number = error.code;
var str: String = error.name;
str = error._message;
QRScanner.getStatus((status) => {
var obj: QRScannerStatus = status;
var bool: Boolean = status.authorized;
bool = status.denied;
bool = status.restricted;
bool = status.prepared;
bool = status.scanning;
bool = status.previewing;
@@ -40,4 +47,4 @@ QRScanner.getStatus((status) => {
bool = status.canOpenSettings;
bool = status.canEnableLight;
var num: Number = status.currentCamera;
})
});
+93 -26
View File
@@ -1,4 +1,4 @@
// Type definitions for cordova-plugin-qrscanner
// Type definitions for cordova-plugin-qrscanner v1.0.0
// Project: https://github.com/bitpay/cordova-plugin-qrscanner
// Definitions by: Jason Dreyzehner <https://github.com/bitjson/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -22,20 +22,21 @@ interface QRScanner {
* only be visible if `QRScanner.show()` has already made the webview transparent.
* @param {function} [callback] Callback that gets an error or the QRScannerStatus object.
*/
prepare: (callback?: (error: Error, status: QRScannerStatus) => any) => void;
prepare: (callback?: (error: QRScannerError, status: QRScannerStatus) => any) => void;
/**
* Sets QRScanner to "watch" for valid QR codes. Once a valid code is
* detected, it's contents are passed to the callback, and scanning is
* toggled off. If `QRScanner.prepare()` has not been called,
* `QRScanner.scan()` performs that setup as well. The video preview does
* this method performs that setup as well. The video preview does
* not need to be visible for scanning to function.
* @param {function} callback Callback that gets an error or the results string.
*/
scan: (callback: (error: Error, result: String) => any) => void;
scan: (callback: (error: QRScannerError, result: String) => any) => void;
/**
* Cancels the current scan. The current scan() callback will not return.
* Cancels the current scan. If `QRScanner.prepare()` has not been called,
* this method performs that setup as well.
* @param {function} [callback] Callback that gets the QRScannerStatus object.
*/
cancelScan: (callback?: (status: QRScannerStatus) => any) => void;
@@ -44,6 +45,7 @@ interface QRScanner {
* Configures the native webview to have a transparent background, then sets
* the background of the `<body>` and parent elements to transparent,
* allowing the webview to re-render with the transparent background.
*
* To see the video preview, your application background must be transparent
* in the areas through which it should show.
* @param {function} [callback] Callback that gets the QRScannerStatus object.
@@ -59,36 +61,42 @@ interface QRScanner {
/**
* Enable the device's light (for scanning in low-light environments).
* Enable the device's light (for scanning in low-light environments). If
* `QRScanner.prepare()` has not been called, this method performs that setup
* as well.
* @param {function} [callback] Callback that gets an error or the QRScannerStatus object.
*/
enableLight: (callback?: (error: Error, status: QRScannerStatus) => any) => void;
enableLight: (callback?: (error: QRScannerError, status: QRScannerStatus) => any) => void;
/**
* Disable the device's light.
* Disable the device's light. If `QRScanner.prepare()` has not been called,
* this method performs that setup as well.
* @param {function} [callback] Callback that gets an error or the QRScannerStatus object.
*/
disableLight: (callback?: (error: Error, status: QRScannerStatus) => any) => void;
disableLight: (callback?: (error: QRScannerError, status: QRScannerStatus) => any) => void;
/**
* Switch video capture to the `index` camera. Camera `0` is the back camera,
* camera `1` is front camera.
* camera `1` is front camera. If `QRScanner.prepare()` has not been called,
* this method performs that setup as well.
* @param {number} index A number representing the index of the camera to use.
* @param {function} [callback] Callback that gets an error or the QRScannerStatus object.
*/
useCamera: (index: Number, callback?: (error: Error, status: QRScannerStatus) => any) => void;
useCamera: (index: Number, callback?: (error: QRScannerError, status: QRScannerStatus) => any) => void;
/**
* Switch video capture to the device's front camera.
* Switch video capture to the device's front camera. If `QRScanner.prepare()`
* has not been called, this method performs that setup as well.
* @param {function} [callback] Callback that gets an error or the QRScannerStatus object.
*/
useFrontCamera: (callback?: (error: Error, status: QRScannerStatus) => any) => void;
useFrontCamera: (callback?: (error: QRScannerError, status: QRScannerStatus) => any) => void;
/**
* Switch video capture to the device's back camera.
* Switch video capture to the device's back camera. If `QRScanner.prepare()`
* has not been called, this method performs that setup as well.
* @param {function} [callback] Callback that gets an error or the QRScannerStatus object.
*/
useBackCamera: (callback?: (error: Error, status: QRScannerStatus) => any) => void;
useBackCamera: (callback?: (error: QRScannerError, status: QRScannerStatus) => any) => void;
/**
* Pauses the video preview on the current frame (as if a snapshot was taken).
@@ -105,9 +113,13 @@ interface QRScanner {
/**
* Open the app-specific permission settings in the user's device settings.
* Here the user can enable/disable camera (and other) access for your app.
*
* Note: iOS immediately kills all apps affected by permissions changes. If
* the user changes a permission settings, your app will stop and only
* restart when they return.
* @param {function} [callback] Callback that gets the QRScannerStatus object.
*/
openSettings: (callback?: (error: Error, status: QRScannerStatus) => any) => void;
openSettings: (callback?: (error: QRScannerError, status: QRScannerStatus) => any) => void;
/**
* Retrieve the status of QRScanner and provide it to the callback function.
@@ -116,9 +128,9 @@ interface QRScanner {
getStatus: (callback: (status: QRScannerStatus) => any) => void;
/**
* Stops scanning, video capture, and the preview, and deallocates as much as
* possible. (E.g. to improve performance/battery life when the scanner is
* not likely to be used for a while.)
* Runs hide(), stops scanning, video capture, and the preview, and
* deallocates as much as possible. (E.g. to improve performance/battery life
* when the scanner is not likely to be used for a while.)
* Basically reverts the plugin to it's startup-state.
* @param {function} [callback] Callback that gets the QRScannerStatus object.
*/
@@ -132,16 +144,29 @@ interface QRScanner {
interface QRScannerStatus {
/**
* On iOS, camera access is granted to an app by the user (by clicking "Allow"
* at the dialog). The `authorized` property is a boolean value which is true
* only when the user has allowed camera access to your app
* (`AVAuthorizationStatus.Authorized`). The `NotDetermined`, `Restricted`
* (e.g.: parental controls), and `Denied` AVAuthorizationStatus states all
* cause this value to be false. If the user has denied access to your app,
* consider asking nicely and offering a link via `QRScanner.openSettings()`.
* On iOS and Android 6.0+, camera access is granted at runtime by the user (by
* clicking "Allow" at the dialog). The `authorized` property is a boolean
* value which is true only when the user has allowed camera access to your app
* (`AVAuthorizationStatus.Authorized`). On platforms with permissions granted
* at install (Android pre-6.0, Windows Phone) this property is always true.
*/
authorized: Boolean,
/**
* A boolean value which is true if the user permenantly denied camera access
* to the app (`AVAuthorizationStatus.Denied`). Once denied, camera access can
* only be gained by requesting the user change their decision (consider
* offering a link to the setting via `openSettings()`).
*/
denied: Boolean,
/**
* A boolean value which is true if the user is unable to grant permissions due
* to parental controls, organization security configuration profiles, or
* similar reasons.
*/
restricted: Boolean,
/**
* A boolean value which is true if QRScanner is prepared to capture video and
* render it to the view.
@@ -188,4 +213,46 @@ interface QRScannerStatus {
currentCamera: Number
}
/**
* An object representing an error issued by QRScanner.
*
* Many QRScanner functions accept a callback with an `error` parameter. When
* QRScanner experiences errors, this parameter contains a QRScannerError object
* with properties `name` (_String_), `code` (_Number_), and `_message`
* (_String_). When handling errors, rely only on the `name` or `code` parameter,
*as the specific content of `_message` is not considered part of the plugin's
* stable API.
*
* # Possible Error Types
*
* Code | Name | Description
* ---: | :-------------------------- | :----------------------------------------
* 0 | `UNEXPECTED_ERROR` | An unexpected error. Returned only by bugs in QRScanner.
* 1 | `CAMERA_ACCESS_DENIED` | The user denied camera access.
* 2 | `CAMERA_ACCESS_RESTRICTED` | Camera access is restricted (due to parental controls, organization security configuration profiles, or similar reasons).
* 3 | `BACK_CAMERA_UNAVAILABLE` | The back camera is unavailable.
* 4 | `FRONT_CAMERA_UNAVAILABLE` | The front camera is unavailable.
* 5 | `CAMERA_UNAVAILABLE` | The camera is unavailable because it doesn't exist or is otherwise unable to be configured. (Returned if QRScanner cannot return one of the more specific `BACK_CAMERA_UNAVAILABLE` or `FRONT_CAMERA_UNAVAILABLE` errors.)
* 6 | `SCAN_CANCELED` | Scan was canceled by the `cancelScan()` method. (Returned exclusively to the `QRScanner.scan()` method.)
* 7 | `LIGHT_UNAVAILABLE` | The device light is unavailable because it doesn't exist or is otherwise unable to be configured.
* 8 | `OPEN_SETTINGS_UNAVAILABLE` | The device is unable to open settings.
*/
interface QRScannerError {
/**
* The standard string identifying the type of this QRScannerError.
*/
name: String,
/**
* The standard number identifying the type of this QRScannerError.
*/
code: Number,
/**
* A simple message describing this QRScannerError.
*/
_message: String
}
declare var QRScanner: QRScanner;
@@ -26,9 +26,6 @@ import path = require('path');
// Quick start
// https://github.com/atom/electron/blob/master/docs/tutorial/quick-start.md
// Report crashes to our server.
require('crash-reporter').start();
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
var mainWindow: Electron.BrowserWindow = null;
@@ -501,7 +498,10 @@ crashReporter.start({
productName: 'YourName',
companyName: 'YourCompany',
submitURL: 'https://your-domain.com/url-to-submit',
autoSubmit: true
autoSubmit: true,
extra: {
someKey: "value"
}
});
// nativeImage
+4 -8
View File
@@ -1369,15 +1369,11 @@ declare module Electron {
* Default: Electron
*/
productName?: string;
/**
* Default: GitHub, Inc.
*/
companyName?: string;
companyName: string;
/**
* URL that crash reports would be sent to as POST.
* Default: http://54.249.141.255:1127/post
*/
submitURL?: string;
submitURL: string;
/**
* Send the crash report without user interaction.
* Default: true.
@@ -1392,7 +1388,7 @@ declare module Electron {
* Only string properties are send correctly.
* Nested objects are not supported.
*/
extra?: {};
extra?: {[prop: string]: string};
}
interface CrashReporterPayload extends Object {
@@ -1436,7 +1432,7 @@ declare module Electron {
}
interface CrashReporter {
start(options?: CrashReporterStartOptions): void;
start(options: CrashReporterStartOptions): void;
/**
* @returns The date and ID of the last crash report. When there was no crash report
+25
View File
@@ -0,0 +1,25 @@
/// <reference path="gulp-install.d.ts" />
/// <reference path="../gulp/gulp.d.ts" />
import * as gulp from 'gulp';
import * as install from 'gulp-install';
// Examples taken from https://www.npmjs.com/package/gulp-install
// Usage in a gulp stream
gulp.src('src')
.pipe(install());
// Options
install({
production: true,
ignoreScripts: true,
noOptional: true,
allowRoot: true,
args: ['one', 'two', 'three']
});
// Options: args only as a string
install({
args: 'one'
});
+22
View File
@@ -0,0 +1,22 @@
// Type definitions for gulp-install v0.6.0
// Project: https://www.npmjs.com/package/gulp-install
// Definitions by: Peter Juras <https://github.com/peterjuras>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "gulp-install" {
interface Options {
production?: boolean;
ignoreScripts?: boolean;
noOptional?: boolean;
allowRoot?: boolean;
args?: string | string[];
}
interface Install {
(options?: Options) : NodeJS.ReadWriteStream;
}
const install : Install;
export = install;
}
@@ -0,0 +1,40 @@
/// <reference path="gulp-json-editor.d.ts" />
/// <reference path="../gulp/gulp.d.ts" />
import * as gulp from 'gulp';
import * as jeditor from 'gulp-json-editor';
// Samples taken from https://www.npmjs.com/package/gulp-json-editor
/*
edit JSON object by merging with user specific object
*/
gulp.src("./manifest.json")
.pipe(jeditor({
'version': '1.2.3'
}))
.pipe(gulp.dest("./dest"));
/*
edit JSON object by using user specific function
*/
gulp.src("./manifest.json")
.pipe(jeditor(function(json : any) {
json.version = "1.2.3";
return json; // must return JSON object.
}))
.pipe(gulp.dest("./dest"));
/*
specify js-beautify option
*/
gulp.src("./manifest.json")
.pipe(jeditor({
'version': '1.2.3'
},
// the second argument is passed to js-beautify as its option
{
'indent_char': '\t',
'indent_size': 1
}))
.pipe(gulp.dest("./dest"));
+17
View File
@@ -0,0 +1,17 @@
// Type definitions for gulp-json-editor v2.2.1
// Project: https://www.npmjs.com/package/gulp-json-editor
// Definitions by: Peter Juras <https://github.com/peterjuras>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/// <reference path="../js-beautify/js-beautify.d.ts" />
declare module "gulp-json-editor" {
interface JEditor {
(mergeWith: any | ((json : any) => any ),
jsBeautifyOptions? : JsBeautifyOptions ) : NodeJS.ReadWriteStream;
}
const jeditor : JEditor;
export = jeditor;
}
+1
View File
@@ -30,6 +30,7 @@ declare module "gulp-typescript" {
jsx?: string;
declaration?: boolean;
emitDecoratorMetadata?: boolean;
experimentalDecorators?: boolean;
experimentalAsyncFunctions?: boolean;
moduleResolution?: string;
noEmitHelpers?: boolean;
+6
View File
@@ -4432,6 +4432,12 @@ interface HighchartsLineChart extends HighchartsSeriesChart {
* @since 1.2.5
*/
step?: boolean|string;
/**
* The line cap used for line ends and line joins on the graph.
* @default 'round'
*/
linecap?: string;
}
/**
+2 -1
View File
@@ -77,6 +77,7 @@ declare module JQueryUI {
interface Autocomplete extends Widget, AutocompleteOptions {
escapeRegex: (value: string) => string;
filter: (array: any, term: string) => any;
}
@@ -363,7 +364,7 @@ declare module JQueryUI {
title?: string;
width?: any; // number or string
zIndex?: number;
open?: DialogEvent;
close?: DialogEvent;
}
+28 -22
View File
@@ -2,28 +2,34 @@
// Project: https://github.com/beautify-web/js-beautify/
// Definitions by: Josh Goldberg <https://github.com/JoshuaKGoldberg/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Type definitions for js_beautify
// Project: https://github.com/beautify-web/js-beautify/
// Definitions by: Josh Goldberg <https://github.com/JoshuaKGoldberg/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface JsBeautifyOptions {
indent_size?: number;
indent_char?: string;
eol?: string;
indent_level?: number;
indent_with_tabs?: boolean;
preserve_newlines?: boolean;
max_preserve_newlines?: number;
jslint_happy?: boolean;
space_after_anon_function?: boolean;
brace_style?: string;
keep_array_indentation?: boolean;
keep_function_indentation?: boolean;
space_before_conditional?: boolean;
break_chained_methods?: boolean;
eval_code?: boolean;
unescape_strings?: boolean;
wrap_line_length?: number;
wrap_attributes?: string;
wrap_attributes_indent_size?: number;
end_with_newline?: boolean;
}
declare var js_beautify: {
(js_source_text: string, options?: {
indent_size?: number;
indent_char?: string;
eol?: string;
indent_level?: number;
indent_with_tabs?: boolean;
preserve_newlines?: boolean;
max_preserve_newlines?: number;
jslint_happy: boolean;
space_after_anon_function: boolean;
brace_style: string;
keep_array_indentation: boolean;
keep_function_indentation: boolean;
space_before_conditional: boolean;
break_chained_methods: boolean;
eval_code: boolean;
unescape_strings: boolean;
wrap_line_length: number;
wrap_attributes: string;
wrap_attributes_indent_size: number;
end_with_newline: boolean;
}): string;
(js_source_text: string, options?: JsBeautifyOptions): string;
};
+26
View File
@@ -0,0 +1,26 @@
/// <reference path="koa-1.1.2.d.ts" />
import * as Koa from 'koa';
var app = new Koa();
// logger
app.use(function *(next: Function) {
// at present, we can not typing 'this' in function
// but there is a proposal: https://github.com/Microsoft/TypeScript/issues/3694
var ctx: Koa.Context = this;
var start = new Date;
yield next;
var ms = <any>new Date - <any>start;
console.log('%s %s - %s', ctx.method, ctx.url, ms);
});
// response
app.use(function *(): Iterable<void> {
var ctx: Koa.Context = this;
ctx.body = 'Hello World';
});
app.listen(3000);
+1
View File
@@ -0,0 +1 @@
--noImplicitAny --module commonjs --target es6
+605
View File
@@ -0,0 +1,605 @@
// Type definitions for koa v1.1.2
// Project: https://github.com/koajs/koa
// Definitions by: jKey Lu <https://github.com/jkeylu>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/* =================== USAGE ===================
import * as Koa from 'koa;
var app = new Koa();
=============================================== */
/// <reference path="../node/node.d.ts" />
/// <reference path="../cookies/cookies.d.ts" />
declare module "koa" {
import * as net from 'net';
import * as http from 'http';
import * as events from 'events';
import * as Cookies from 'cookies';
interface IRequest {
/**
* Return request header.
*
* @readonly
*/
header: any;
/**
* Return request header, alias as request.header
*
* @readonly
*/
headers: any;
/**
* Get/Set request URL.
*/
url: string;
/**
* Get origin of URL.
*/
origin: string;
/**
* Get full request URL.
*
* @readonly
*/
href: string;
/**
* Get/Set request method.
*/
method: string;
/**
* Get request pathname.
* Set pathname, retaining the query-string when present.
*/
path: string;
/**
* Get parsed query-string.
* Set query-string as an object.
*/
query: any;
/**
* Get/Set query string.
*/
querystring: string;
/**
* Get the search string. Same as the querystring except it includes the leading ?.
* Set the search string. Same as response.querystring= but included for ubiquity.
*/
search: string;
/**
* Parse the "Host" header field host and support X-Forwarded-Host when a proxy is enabled.
*
* @readonly
*/
host: string;
/**
* Parse the "Host" header field hostname and support X-Forwarded-Host when a proxy is enabled.
*
* @readonly
*/
hostname: string;
/**
* Check if the request is fresh, aka
* Last-Modified and/or the ETag
* still match.
*
* @readonly
*/
fresh: boolean;
/**
* Check if the request is stale, aka
* "Last-Modified" and / or the "ETag" for the
* resource has changed.
*
* @readonly
*/
stale: boolean;
/**
* Check if the request is idempotent.
*
* @readonly
*/
idempotent: boolean;
/**
* Return the request socket.
*
* @readonly
*/
socket: net.Socket;
/**
* Return the protocol string "http" or "https"
* when requested with TLS. When the proxy setting
* is enabled the "X-Forwarded-Proto" header
* field will be trusted. If you're running behind
* a reverse proxy that supplies https for you this
* may be enabled.
*
* @readonly
*/
protocol: string;
/**
* Short-hand for:
*
* this.protocol == 'https'
*
* @readonly
*/
secure: boolean;
/**
* Return the remote address, or when
* `app.proxy` is `true` return
* the upstream addr.
*
* @readonly
*/
ip: string;
/**
* When `app.proxy` is `true`, parse
* the "X-Forwarded-For" ip address list.
*
* For example if the value were "client, proxy1, proxy2"
* you would receive the array `["client", "proxy1", "proxy2"]`
* where "proxy2" is the furthest down-stream.
*
* @readonly
*/
ips: string[];
/**
* Return subdomains as an array.
*
* Subdomains are the dot-separated parts of the host before the main domain of
* the app. By default, the domain of the app is assumed to be the last two
* parts of the host. This can be changed by setting `app.subdomainOffset`.
*
* For example, if the domain is "tobi.ferrets.example.com":
* If `app.subdomainOffset` is not set, this.subdomains is `["ferrets", "tobi"]`.
* If `app.subdomainOffset` is 3, this.subdomains is `["tobi"]`.
*
* @readonly
*/
subdomains: string[];
/**
* Check if the given `type(s)` is acceptable, returning
* the best match when true, otherwise `undefined`, in which
* case you should respond with 406 "Not Acceptable".
*
* The `type` value may be a single mime type string
* such as "application/json", the extension name
* such as "json" or an array `["json", "html", "text/plain"]`. When a list
* or array is given the _best_ match, if any is returned.
*
* Examples:
*
* // Accept: text/html
* this.accepts('html');
* // => "html"
*
* // Accept: text/*, application/json
* this.accepts('html');
* // => "html"
* this.accepts('text/html');
* // => "text/html"
* this.accepts('json', 'text');
* // => "json"
* this.accepts('application/json');
* // => "application/json"
*
* // Accept: text/*, application/json
* this.accepts('image/png');
* this.accepts('png');
* // => undefined
*
* // Accept: text/*;q=.5, application/json
* this.accepts(['html', 'json']);
* this.accepts('html', 'json');
* // => "json"
*/
accepts(...types: string[]): string|boolean|string[];
accepts(types: string[]): string|boolean|string[];
/**
* Return accepted encodings or best fit based on `encodings`.
*
* Given `Accept-Encoding: gzip, deflate`
* an array sorted by quality is returned:
*
* ['gzip', 'deflate']
*/
acceptsEncodings(...encodings: string[]): string|string[];
acceptsEncodings(encodings: string[]): string|string[];
/**
* Return accepted charsets or best fit based on `charsets`.
*
* Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
* an array sorted by quality is returned:
*
* ['utf-8', 'utf-7', 'iso-8859-1']
*/
acceptsCharsets(...charsets: string[]): string|string[];
acceptsCharsets(charsets: string[]): string|string[];
/**
* Return accepted languages or best fit based on `langs`.
*
* Given `Accept-Language: en;q=0.8, es, pt`
* an array sorted by quality is returned:
*
* ['es', 'pt', 'en']
*/
acceptsLanguages(...langs: string[]): string|string[];
acceptsLanguages(langs: string[]): string|string[];
/**
* Check if the incoming request contains the "Content-Type"
* header field, and it contains any of the give mime `type`s.
* If there is no request body, `null` is returned.
* If there is no content type, `false` is returned.
* Otherwise, it returns the first `type` that matches.
*
* Examples:
*
* // With Content-Type: text/html; charset=utf-8
* this.is('html'); // => 'html'
* this.is('text/html'); // => 'text/html'
* this.is('text/*', 'application/json'); // => 'text/html'
*
* // When Content-Type is application/json
* this.is('json', 'urlencoded'); // => 'json'
* this.is('application/json'); // => 'application/json'
* this.is('html', 'application/*'); // => 'application/json'
*
* this.is('html'); // => false
*/
is(type: string): string|boolean;
is(types: string[]): string|boolean;
/**
* Return request header.
*
* The `Referrer` header field is special-cased,
* both `Referrer` and `Referer` are interchangeable.
*
* Examples:
*
* this.get('Content-Type');
* // => "text/plain"
*
* this.get('content-type');
* // => "text/plain"
*
* this.get('Something');
* // => undefined
*/
get(field: string): string;
}
interface IResponse {
/**
* Get/Set response status code.
*/
status: number;
/**
* Get/Set response status message
*/
message: string;
/**
* Get/Set response body.
*/
body: any;
/**
* Return parsed response Content-Length when present.
* Set Content-Length field to `n`.
*/
length: number;
/**
* Check if a header has been written to the socket.
*
* @readonly
*/
headerSent: boolean;
/**
* Vary on `field`.
*/
vary(field: string): void;
/**
* Perform a 302 redirect to `url`.
*
* The string "back" is special-cased
* to provide Referrer support, when Referrer
* is not present `alt` or "/" is used.
*
* Examples:
*
* this.redirect('back');
* this.redirect('back', '/index.html');
* this.redirect('/login');
* this.redirect('http://google.com');
*/
redirect(url: string): void;
redirect(url: string, alt: string): void;
/**
* Set Content-Disposition header to "attachment" with optional `filename`.
*/
attachment(filename: string): void;
/**
* Return the response mime type void of
* parameters such as "charset".
*
* Set Content-Type response header with `type` through `mime.lookup()`
* when it does not contain a charset.
*
* Examples:
*
* this.type = '.html';
* this.type = 'html';
* this.type = 'json';
* this.type = 'application/json';
* this.type = 'png';
*/
type: string;
/**
* Get the Last-Modified date in Date form, if it exists.
* Set the Last-Modified date using a string or a Date.
*
* this.response.lastModified = new Date();
* this.response.lastModified = '2013-09-13';
*/
lastModified: Date;
/**
* Get the ETag of a response.
* Set the ETag of a response.
* This will normalize the quotes if necessary.
*
* this.response.etag = 'md5hashsum';
* this.response.etag = '"md5hashsum"';
* this.response.etag = 'W/"123456789"';
*/
etag: string;
/**
* Set header `field` to `val`, or pass
* an object of header fields.
*
* Examples:
*
* this.set('Foo', ['bar', 'baz']);
* this.set('Accept', 'application/json');
* this.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
*/
set(field: any): void;
set(field: string, val: string): void;
set(field: string, val: any[]): void;
/**
* Append additional header `field` with value `val`.
*
* Examples:
*
* this.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
* this.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
* this.append('Warning', '199 Miscellaneous warning');
*/
append(field: string, val: string): void;
append(field: string, val: any[]): void;
/**
* Remove header `field`.
*/
remove(field: string): void;
/**
* Checks if the request is writable.
* Tests for the existence of the socket
* as node sometimes does not set it.
*
* @readonly
* @private
*/
writable: boolean;
}
module koa {
interface BaseRequest extends IRequest {
/**
* Get the charset when present or undefined.
*
* @readonly
*/
charset: string;
/**
* Return parsed Content-Length when present.
*
* @readonly
*/
length: number;
/**
* Return the request mime type void of
* parameters such as "charset".
*
* @readonly
*/
type: string;
/**
* Inspect implementation.
*/
inspect(): any;
/**
* Return JSON representation.
*/
toJSON(): any;
}
interface BaseResponse extends IResponse {
/**
* Return the request socket.
*
* @readonly
*/
socket: net.Socket;
/**
* Return response header.
*
* @readonly
*/
header: any;
/**
* Return response header, alias as response.header
*/
headers: any;
/**
* Check whether the response is one of the listed types.
* Pretty much the same as `this.request.is()`.
*/
is(type: string): string|boolean;
is(types: string[]): string|boolean;
/**
* Return response header.
*
* Examples:
*
* this.get('Content-Type');
* // => "text/plain"
*
* this.get('content-type');
* // => "text/plain"
*/
get(field: string): string;
/**
* Inspect implementation.
*/
inspect(): any;
/**
* Return JSON representation.
*/
toJSON(): any;
}
interface BaseContext extends IRequest, IResponse {
/**
* util.inspect() implementation, which
* just returns the JSON output.
*/
inspect(): any;
/**
* Return JSON representation.
*
* Here we explicitly invoke .toJSON() on each
* object, as iteration will otherwise fail due
* to the getters and cause utilities such as
* clone() to fail.
*/
toJSON(): any;
/**
* Similar to .throw(), adds assertion.
*
* this.assert(this.user, 401, 'Please login!');
*
* See: https://github.com/jshttp/http-assert
*/
assert(test: any, status: number, message: string): void;
/**
* Throw an error with `msg` and optional `status`
* defaulting to 500. Note that these are user-level
* errors, and the message may be exposed to the client.
*
* this.throw(403)
* this.throw('name required', 400)
* this.throw(400, 'name required')
* this.throw('something exploded')
* this.throw(new Error('invalid'), 400);
* this.throw(400, new Error('invalid'));
*
* See: https://github.com/jshttp/http-errors
*/
throw(...args: any[]): void;
/**
* Default error handling.
*
* @private
*/
onerror(err: Error): void;
}
interface Request extends BaseRequest {
app: Application;
ctx: Context;
response: Response;
req: http.IncomingMessage;
res: http.ServerResponse;
}
interface Response extends BaseResponse {
app: Application;
ctx: Context;
request: Request;
req: http.IncomingMessage;
res: http.ServerResponse;
}
interface Context extends BaseContext {
request: Request;
response: Response;
app: Application;
req: http.IncomingMessage;
res: http.ServerResponse;
originalUrl: string;
cookies: Cookies.ICookies;
accept: any;
state: any;
}
interface Application extends events.EventEmitter {
env: string;
subdomainOffset: number;
middleware: any[];
proxy: boolean;
context: BaseContext;
request: BaseRequest;
response: BaseResponse;
/**
* Shorthand for:
*
* http.createServer(app.callback()).listen(...)
*/
listen(port: number, hostname?: string, backlog?: number, callback?: Function): http.Server;
listen(port: number, hostname?: string, callback?: Function): http.Server;
listen(path: string, callback?: Function): http.Server;
listen(handle: any, listeningListener?: Function): http.Server;
/**
* Return JSON representation.
* We only bother showing settings.
*/
inspect(): any;
/**
* Return JSON representation.
* We only bother showing settings.
*/
toJSON(): any;
/**
* Use the given middleware `fn`.
*/
use(fn: Function): Application;
/**
* Return a request handler callback
* for node's native http server.
*/
callback(): (req: http.IncomingMessage, res: http.ServerResponse) => void;
/**
* Initialize a new context.
*
* @private
*/
createContext(req: http.IncomingMessage, res: http.ServerResponse): Context;
/**
* Default error handler.
*
* @private
*/
onerror(err: Error): void;
}
}
interface KoaStatic {
new (): koa.Application;
(): koa.Application;
}
var koa: KoaStatic;
export = koa;
}
+101 -96
View File
@@ -8,6 +8,10 @@
import * as Koa from "koa"
const app = new Koa()
async function (ctx: Koa.Context, next: Function) {
// ...
}
=============================================== */
/// <reference path="../node/node.d.ts" />
@@ -16,99 +20,101 @@ declare module "koa" {
import * as http from "http";
import * as net from "net";
interface IContext extends IRequest, IResponse {
body?: any;
request?: IRequest;
response?: IResponse;
originalUrl?: string;
state?: any;
name?: string;
cookies?: any;
writable?: Boolean;
respond?: Boolean;
app?: Koa;
req?: http.IncomingMessage;
res?: http.ServerResponse;
onerror(err: any): void;
toJSON(): any;
inspect(): any;
throw(): void;
assert(): void;
}
module Koa {
export interface Context extends Request, Response {
body?: any;
request?: Request;
response?: Response;
originalUrl?: string;
state?: any;
name?: string;
cookies?: any;
writable?: Boolean;
respond?: Boolean;
app?: Koa;
req?: http.IncomingMessage;
res?: http.ServerResponse;
onerror(err: any): void;
toJSON(): any;
inspect(): any;
throw(code?: any, message?: any): void;
assert(): void;
}
interface IRequest {
_querycache?: string;
app?: Koa;
req?: http.IncomingMessage;
res?: http.ServerResponse;
response?: IResponse;
ctx?: IContext;
headers?: any;
header?: any;
method?: string;
length?: any;
url?: string;
origin?: string;
originalUrl?: string;
href?: string;
path?: string;
querystring?: string;
query?: any;
search?: string;
idempotent?: Boolean;
socket?: net.Socket;
protocol?: string;
host?: string;
hostname?: string;
fresh?: Boolean;
stale?: Boolean;
charset?: string;
secure?: Boolean;
ips?: Array<string>;
ip?: string;
subdomains?: Array<string>;
accept?: any;
type?: string;
accepts?: () => any;
acceptsEncodings?: () => any;
acceptsCharsets?: () => any;
acceptsLanguages?: () => any;
is?: (types: any) => any;
toJSON?: () => any;
inspect?: () => any;
get?: (field: string) => string;
}
export interface Request {
_querycache?: string;
app?: Koa;
req?: http.IncomingMessage;
res?: http.ServerResponse;
response?: Response;
ctx?: Context;
headers?: any;
header?: any;
method?: string;
length?: any;
url?: string;
origin?: string;
originalUrl?: string;
href?: string;
path?: string;
querystring?: string;
query?: any;
search?: string;
idempotent?: Boolean;
socket?: net.Socket;
protocol?: string;
host?: string;
hostname?: string;
fresh?: Boolean;
stale?: Boolean;
charset?: string;
secure?: Boolean;
ips?: Array<string>;
ip?: string;
subdomains?: Array<string>;
accept?: any;
type?: string;
accepts?: () => any;
acceptsEncodings?: () => any;
acceptsCharsets?: () => any;
acceptsLanguages?: () => any;
is?: (types: any) => any;
toJSON?: () => any;
inspect?: () => any;
get?: (field: string) => string;
}
interface IResponse {
_body?: any;
_explicitStatus?: Boolean;
app?: Koa;
res?: http.ServerResponse;
req?: http.IncomingMessage;
ctx?: IContext;
request?: IRequest;
socket?: net.Socket;
header?: any;
headers?: any;
status?: number;
message?: string;
type?: string;
body?: any;
length?: any;
headerSent?: Boolean;
lastModified?: Date;
etag?: string;
writable?: Boolean;
is?: (types: any) => any;
redirect?: (url: string, alt: string) => void;
attachment?: (filename?: string) => void;
vary?: (field: string) => void;
get?: (field: string) => string;
set?: (field: any, val: any) => void;
remove?: (field: string) => void;
append?: (field: string, val: any) => void;
toJSON?: () => any;
inspect?: () => any;
export interface Response {
_body?: any;
_explicitStatus?: Boolean;
app?: Koa;
res?: http.ServerResponse;
req?: http.IncomingMessage;
ctx?: Context;
request?: Request;
socket?: net.Socket;
header?: any;
headers?: any;
status?: number;
message?: string;
type?: string;
body?: any;
length?: any;
headerSent?: Boolean;
lastModified?: Date;
etag?: string;
writable?: Boolean;
is?: (types: any) => any;
redirect?: (url: string, alt: string) => void;
attachment?: (filename?: string) => void;
vary?: (field: string) => void;
get?: (field: string) => string;
set?: (field: any, val: any) => void;
remove?: (field: string) => void;
append?: (field: string, val: any) => void;
toJSON?: () => any;
inspect?: () => any;
}
}
class Koa extends EventEmitter {
@@ -117,12 +123,12 @@ declare module "koa" {
proxy: Boolean;
server: http.Server;
env: string;
context: IContext;
request: IRequest;
response: IResponse;
context: Koa.Context;
request: Koa.Request;
response: Koa.Response;
silent: Boolean;
constructor();
use(middleware: (ctx: IContext, next: Function) => any): Koa;
use(middleware: (ctx: Koa.Context, next: Function) => any): Koa;
callback(): (req: http.IncomingMessage, res: http.ServerResponse) => void;
listen(port: number, callback?: Function): http.Server;
toJSON(): any;
@@ -131,6 +137,5 @@ declare module "koa" {
}
namespace Koa {}
export = Koa;
}
+47
View File
@@ -0,0 +1,47 @@
/// <reference path="../leaflet/leaflet.d.ts" />
/// <reference path="leaflet-draw.d.ts" />
var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
osmAttrib = '&copy; <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors',
osm = L.tileLayer(osmUrl, {maxZoom: 18, attribution: osmAttrib}),
map = new L.Map('map', {layers: [osm], center: new L.LatLng(-37.7772, 175.2756), zoom: 15 });
var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
var drawControl = new L.Control.Draw({
position: 'topleft' ,
draw: {
polygon: {
allowIntersection: false,
drawError: {
color: '#b00b00',
timeout: 1000
},
shapeOptions: {
color: '#bada55'
},
showArea: true
},
polyline: {
metric: false
},
circle: {
shapeOptions: {
color: '#662d91'
}
}
},
edit: {
featureGroup: drawnItems
}
});
map.addControl(drawControl);
map.on('draw:created', function (e: L.DrawEvents.Created) {
var type = e.layerType,
layer = e.layer;
drawnItems.addLayer(layer);
});
+333
View File
@@ -0,0 +1,333 @@
// Type definitions for leaflet-draw 0.2.4
// Project: https://github.com/Leaflet/Leaflet.draw
// Definitions by: Matt Guest <https://github.com/matt-guest>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../leaflet/leaflet.d.ts" />
declare module L {
export interface MapOptions {
drawControl?: boolean;
}
export interface ControlStatic {
Draw: Control.DrawStatic;
}
module Control {
export interface DrawStatic {
new (options?: IDrawConstructorOptions): Draw;
}
export interface IDrawConstructorOptions {
/**
* The initial position of the control (one of the map corners).
*
* Default value: 'topleft'
*/
position?: string;
/**
* The options used to configure the draw toolbar.
*
* Default value: {}
*/
draw?: DrawOptions;
/**
* The options used to configure the edit toolbar.
*
* Default value: false
*/
edit: EditOptions;
}
export interface DrawOptions {
/**
* Polyline draw handler options. Set to false to disable handler.
*
* Default value: {}
*/
polyline?: DrawOptions.PolylineOptions;
/**
* Polygon draw handler options. Set to false to disable handler.
*
* Default value: {}
*/
polygon?: DrawOptions.PolygonOptions;
/**
* Rectangle draw handler options. Set to false to disable handler.
*
* Default value: {}
*/
rectangle?: DrawOptions.RectangleOptions;
/**
* Circle draw handler options. Set to false to disable handler.
*
* Default value: {}
*/
circle?: DrawOptions.CircleOptions;
/**
* Marker draw handler options. Set to false to disable handler.
*
* Default value: {}
*/
marker?: DrawOptions.MarkerOptions;
}
export interface EditOptions {
/**
* This is the FeatureGroup that stores all editable shapes.
* THIS IS REQUIRED FOR THE EDIT TOOLBAR TO WORK
*
* Default value: null
*/
featureGroup: FeatureGroup<ILayer>;
/**
* Edit handler options. Set to false to disable handler.
*
* Default value: null
*/
edit?: DrawOptions.EditHandlerOptions;
/**
* Delete handler options. Set to false to disable handler.
*
* Default value: null
*/
remove?: DrawOptions.DeleteHandlerOptions;
}
export interface Draw extends IControl {
}
}
module DrawOptions {
export interface PolylineOptions {
/**
* Determines if line segments can cross.
*
* Default value: true
*/
allowIntersection?: boolean;
/**
* Configuration options for the error that displays if an intersection is detected.
*
* Default value: See code
*/
drawError?: any;
/**
* Distance in pixels between each guide dash.
*
* Default value: 20
*/
guidelineDistance?: number;
/**
* The options used when drawing the polyline/polygon on the map.
*
* Default value: See code
*/
shapeOptions?: L.PolylineOptions;
/**
* Determines which measurement system (metric or imperial) is used.
*
* Default value: true
*/
metric?: boolean;
/**
* This should be a high number to ensure that you can draw over all other layers on the map.
*
* Default value: 2000
*/
zIndexOffset?: number;
/**
* Determines if the draw tool remains enabled after drawing a shape.
*
* Default value: false
*/
repeatMode?: boolean;
}
export interface PolygonOptions extends PolylineOptions {
/**
* Show the area of the drawn polygon in m², ha or km².
* The area is only approximate and become less accurate the larger the polygon is.
*
* Default value: false
*/
showArea?: boolean;
}
export interface RectangleOptions {
/**
* The options used when drawing the rectangle on the map.
*
* Default value: See code
*/
shapeOptions?: L.PathOptions;
/**
* Determines if the draw tool remains enabled after drawing a shape.
*
* Default value: false
*/
repeatMode?: boolean;
}
export interface CircleOptions {
/**
* The options used when drawing the circle on the map.
*
* Default value: See code
*/
shapeOptions?: L.PathOptions;
/**
* Determines if the draw tool remains enabled after drawing a shape.
*
* Default value: false
*/
repeatMode?: boolean;
}
export interface MarkerOptions {
/**
* TThe icon displayed when drawing a marker.
*
* Default value: L.Icon.Default()
*/
icon?: L.Icon;
/**
* This should be a high number to ensure that you can draw over all other layers on the map.
*
* Default value: 2000
*/
zIndexOffset?: number;
/**
* Determines if the draw tool remains enabled after drawing a shape.
*
* Default value: false
*/
repeatMode?: boolean;
}
export interface EditHandlerOptions {
/**
* The path options for how the layers will look while in edit mode.
* If this is set to null the editable path options will not be set.
*
* Default value: See code
*/
selectedPathOptions?: L.PathOptions;
}
export interface DeleteHandlerOptions {
}
}
module DrawEvents {
export interface Created {
/**
* Layer that was just created.
*/
layer: ILayer;
/**
* The type of layer this is. One of: polyline, polygon, rectangle, circle, marker.
*/
layerType: string;
}
export interface Edited {
/**
* List of all layers just edited on the map.
*/
layers: LayerGroup<ILayer>;
}
/**
* Triggered when layers have been removed (and saved) from the FeatureGroup.
*/
export interface Deleted {
/**
* List of all layers just removed from the map.
*/
layers: LayerGroup<ILayer>;
}
export interface DrawStart {
/**
* The type of layer this is. One of: polyline, polygon, rectangle, circle, marker
*/
layerType: string;
}
export interface DrawStop {
/**
* The type of layer this is. One of: polyline, polygon, rectangle, circle, marker
*/
layerType: string;
}
export interface EditStart {
/**
* The type of edit this is. One of: edit
*/
handler: string;
}
export interface EditStop {
/**
* The type of edit this is. One of: edit
*/
handler: string;
}
export interface DeleteStart {
/**
* The type of edit this is. One of: remove
*/
handler: string;
}
export interface DeleteStop {
/**
* The type of edit this is. One of: remove
*/
handler: string;
}
}
}
+57 -7
View File
@@ -230,7 +230,6 @@ declare module _ {
interface LoDashExplicitObjectWrapper<T> extends LoDashExplicitWrapperBase<T, LoDashExplicitObjectWrapper<T>> { }
interface LoDashImplicitArrayWrapper<T> extends LoDashImplicitWrapperBase<T[], LoDashImplicitArrayWrapper<T>> {
join(seperator?: string): string;
pop(): T;
push(...items: T[]): LoDashImplicitArrayWrapper<T>;
shift(): T;
@@ -246,6 +245,49 @@ declare module _ {
interface LoDashExplicitNumberArrayWrapper extends LoDashExplicitArrayWrapper<number> { }
// join (exists only in wrappers)
interface LoDashImplicitWrapper<T> {
/**
* @see _.join
*/
join(separator?: string): string;
}
interface LoDashImplicitArrayWrapper<T> {
/**
* @see _.join
*/
join(separator?: string): string;
}
interface LoDashImplicitObjectWrapper<T> {
/**
* @see _.join
*/
join(separator?: string): string;
}
interface LoDashExplicitWrapper<T> {
/**
* @see _.join
*/
join(separator?: string): LoDashExplicitWrapper<string>;
}
interface LoDashExplicitArrayWrapper<T> {
/**
* @see _.join
*/
join(separator?: string): LoDashExplicitWrapper<string>;
}
interface LoDashExplicitObjectWrapper<T> {
/**
* @see _.join
*/
join(separator?: string): LoDashExplicitWrapper<string>;
}
/*********
* Array *
*********/
@@ -10432,19 +10474,27 @@ declare module _ {
/**
* Checks if value is empty. A value is considered empty unless its an arguments object, array, string, or
* jQuery-like collection with a length greater than 0 or an object with own enumerable properties.
*
* @param value The value to inspect.
* @return Returns true if value is empty, else false.
**/
isEmpty(value?: any[]|Dictionary<any>|string|any): boolean;
*/
isEmpty(value?: any): boolean;
}
interface LoDashImplicitWrapperBase<T,TWrapper> {
interface LoDashImplicitWrapperBase<T, TWrapper> {
/**
* @see _.isEmpty
*/
isEmpty(): boolean;
}
interface LoDashExplicitWrapperBase<T, TWrapper> {
/**
* @see _.isEmpty
*/
isEmpty(): LoDashExplicitWrapper<boolean>;
}
//_.isEqual
interface IsEqualCustomizer {
(value: any, other: any, indexOrKey?: number|string): boolean;
@@ -14183,21 +14233,21 @@ declare module _ {
* @param func The function to attempt.
* @return Returns the func result or error object.
*/
attempt<TResult>(func: (...args: any[]) => TResult): TResult|Error;
attempt<TResult>(func: (...args: any[]) => TResult, ...args: any[]): TResult|Error;
}
interface LoDashImplicitObjectWrapper<T> {
/**
* @see _.attempt
*/
attempt<TResult>(): TResult|Error;
attempt<TResult>(...args: any[]): TResult|Error;
}
interface LoDashExplicitObjectWrapper<T> {
/**
* @see _.attempt
*/
attempt<TResult>(): LoDashExplicitObjectWrapper<TResult|Error>;
attempt<TResult>(...args: any[]): LoDashExplicitObjectWrapper<TResult|Error>;
}
//_.callback
+51 -7
View File
@@ -133,7 +133,6 @@ module TestWrapper {
}
//Wrapped array shortcut methods
result = <string>_([1, 2, 3, 4]).join(',');
result = <number>_([1, 2, 3, 4]).pop();
result = <_.LoDashImplicitArrayWrapper<number>>_([1, 2, 3, 4]).push(5, 6, 7);
result = <number>_([1, 2, 3, 4]).shift();
@@ -142,6 +141,34 @@ result = <_.LoDashImplicitArrayWrapper<number>>_([1, 2, 3, 4]).splice(1);
result = <_.LoDashImplicitArrayWrapper<number>>_([1, 2, 3, 4]).splice(1, 2, 5, 6);
result = <_.LoDashImplicitArrayWrapper<number>>_([1, 2, 3, 4]).unshift(5, 6);
// join (exists only in wrappers)
namespace TestJoin {
let array = [1, 2];
let list = {0: 1, 1: 2, length: 2};
{
let result: string;
result = _('abc').join();
result = _('abc').join('_');
result = _(array).join();
result = _(array).join('_');
result = _(list).join();
result = _(list).join('_');
}
{
let result: _.LoDashExplicitWrapper<string>;
result = _('abc').chain().join();
result = _('abc').chain().join('_');
result = _(array).chain().join();
result = _(array).chain().join('_');
result = _(list).chain().join();
result = _(list).chain().join('_');
}
}
/*********
* Array *
*********/
@@ -6574,12 +6601,26 @@ module TestIsElement {
}
// _.isEmpty
result = <boolean>_.isEmpty([1, 2, 3]);
result = <boolean>_.isEmpty({});
result = <boolean>_.isEmpty('');
result = <boolean>_([1, 2, 3]).isEmpty();
result = <boolean>_({}).isEmpty();
result = <boolean>_('').isEmpty();
module TestIsEmpty {
{
let result: boolean;
result = _.isEmpty(any);
result = _(1).isEmpty();
result = _('').isEmpty();
result = _<any>([]).isEmpty();
result = _({}).isEmpty();
}
{
let result: _.LoDashExplicitWrapper<boolean>;
result = _(1).chain().isEmpty();
result = _('').chain().isEmpty();
result = _<any>([]).chain().isEmpty();
result = _({}).chain().isEmpty();
}
}
// _.isEqual
module TestIsEqual {
@@ -9239,13 +9280,16 @@ module TestAttempt {
let result: {a: string}|Error;
result = _.attempt<{a: string}>(func);
result = _.attempt<{a: string}>(func, 'foo', 'bar', 'baz');
result = _(func).attempt<{a: string}>();
result = _(func).attempt<{a: string}>('foo', 'bar', 'baz');
}
{
let result: _.LoDashExplicitObjectWrapper<{a: string}|Error>;
result = _(func).chain().attempt<{a: string}>();
result = _(func).chain().attempt<{a: string}>('foo', 'bar', 'baz');
}
}
+88 -7
View File
@@ -133,7 +133,6 @@ module TestWrapper {
}
//Wrapped array shortcut methods
result = <string>_([1, 2, 3, 4]).join(',');
result = <number>_([1, 2, 3, 4]).pop();
result = <_.LoDashImplicitArrayWrapper<number>>_([1, 2, 3, 4]).push(5, 6, 7);
result = <number>_([1, 2, 3, 4]).shift();
@@ -941,6 +940,41 @@ module TestIntersection {
}
}
// _.join
namespace TestJoin {
let array = [1, 2];
let list = {0: 1, 1: 2, length: 2};
{
let result: string;
result = _.join('abc');
result = _.join('abc', '_');
result = _.join(array);
result = _.join(array, '_');
result = _.join(list);
result = _.join(list, '_');
result = _('abc').join();
result = _('abc').join('_');
result = _(array).join();
result = _(array).join('_');
result = _(list).join();
result = _(list).join('_');
}
{
let result: _.LoDashExplicitWrapper<string>;
result = _('abc').chain().join();
result = _('abc').chain().join('_');
result = _(array).chain().join();
result = _(array).chain().join('_');
result = _(list).chain().join();
result = _(list).chain().join('_');
}
}
// _.last
module TestLast {
let array: TResult[];
@@ -5894,12 +5928,26 @@ module TestIsElement {
}
// _.isEmpty
result = <boolean>_.isEmpty([1, 2, 3]);
result = <boolean>_.isEmpty({});
result = <boolean>_.isEmpty('');
result = <boolean>_([1, 2, 3]).isEmpty();
result = <boolean>_({}).isEmpty();
result = <boolean>_('').isEmpty();
module TestIsEmpty {
{
let result: boolean;
result = _.isEmpty(any);
result = _(1).isEmpty();
result = _('').isEmpty();
result = _<any>([]).isEmpty();
result = _({}).isEmpty();
}
{
let result: _.LoDashExplicitWrapper<boolean>;
result = _(1).chain().isEmpty();
result = _('').chain().isEmpty();
result = _<any>([]).chain().isEmpty();
result = _({}).chain().isEmpty();
}
}
// _.isEqual
module TestIsEqual {
@@ -9396,13 +9444,16 @@ module TestAttempt {
let result: {a: string}|Error;
result = _.attempt<{a: string}>(func);
result = _.attempt<{a: string}>(func, 'foo', 'bar', 'baz');
result = _(func).attempt<{a: string}>();
result = _(func).attempt<{a: string}>('foo', 'bar', 'baz');
}
{
let result: _.LoDashExplicitObjectWrapper<{a: string}|Error>;
result = _(func).chain().attempt<{a: string}>();
result = _(func).chain().attempt<{a: string}>('foo', 'bar', 'baz');
}
}
@@ -9830,6 +9881,36 @@ module TestNoop {
}
}
// _.over
namespace TestOver {
{
let result: (...args: any[]) => number[];
result = _.over<number>(Math.max);
result = _.over<number>(Math.max, Math.min);
result = _.over<number>([Math.max]);
result = _.over<number>([Math.max], [Math.min]);
}
{
let result: _.LoDashImplicitObjectWrapper<(...args: any[]) => number[]>;
result = _(Math.max).over<number>();
result = _(Math.max).over<number>(Math.min);
result = _([Math.max]).over<number>();
result = _([Math.max]).over<number>([Math.min]);
}
{
let result: _.LoDashExplicitObjectWrapper<(...args: any[]) => number[]>;
result = _(Math.max).chain().over<number>();
result = _(Math.max).chain().over<number>(Math.min);
result = _([Math.max]).chain().over<number>();
result = _([Math.max]).chain().over<number>([Math.min]);
}
}
// _.property
module TestProperty {
interface SampleObject {
+119 -22
View File
@@ -256,7 +256,7 @@ declare module _ {
* keyBy, initial, intersection, invert, invoke, keys, map, max, memoize, merge, min,
* object, omit, once, pairs, partial, partialRight, pick, pluck, pull, push, range, reject,
* remove, rest, reverse, sample, shuffle, slice, sort, sortBy, splice, tap, throttle, times,
* toArray, transform, union, uniq, unshift, unzip, values, where, without, wrap, and zip
* toArray, transform, union, uniq, unset, unshift, unzip, values, where, without, wrap, and zip
*
* The non-chainable wrapper functions are:
* clone, cloneDeep, contains, escape, every, find, findIndex, findKey, findLast,
@@ -375,7 +375,6 @@ declare module _ {
interface LoDashExplicitObjectWrapper<T> extends LoDashExplicitWrapperBase<T, LoDashExplicitObjectWrapper<T>> { }
interface LoDashImplicitArrayWrapper<T> extends LoDashImplicitWrapperBase<T[], LoDashImplicitArrayWrapper<T>> {
join(seperator?: string): string;
pop(): T;
push(...items: T[]): LoDashImplicitArrayWrapper<T>;
shift(): T;
@@ -1676,26 +1675,61 @@ declare module _ {
): any[];
}
//_.join DUMMY
//_.join
interface LoDashStatic {
/**
* Converts all elements in `array` into a string separated by `separator`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to convert.
* @param {string} [separator=','] The element separator.
* @returns {string} Returns the joined string.
* @example
*
* _.join(['a', 'b', 'c'], '~');
* // => 'a~b~c'
* @param array The array to convert.
* @param separator The element separator.
* @returns Returns the joined string.
*/
join(
array: any[]|List<any>,
...values: any[]
): any[];
array: List<any>,
separator?: string
): string;
}
interface LoDashImplicitWrapper<T> {
/**
* @see _.join
*/
join(separator?: string): string;
}
interface LoDashImplicitArrayWrapper<T> {
/**
* @see _.join
*/
join(separator?: string): string;
}
interface LoDashImplicitObjectWrapper<T> {
/**
* @see _.join
*/
join(separator?: string): string;
}
interface LoDashExplicitWrapper<T> {
/**
* @see _.join
*/
join(separator?: string): LoDashExplicitWrapper<string>;
}
interface LoDashExplicitArrayWrapper<T> {
/**
* @see _.join
*/
join(separator?: string): LoDashExplicitWrapper<string>;
}
interface LoDashExplicitObjectWrapper<T> {
/**
* @see _.join
*/
join(separator?: string): LoDashExplicitWrapper<string>;
}
//_.pullAll DUMMY
@@ -4236,6 +4270,21 @@ declare module _ {
): any[];
}
//_.unset
interface LoDashStatic {
/**
* Removes the property at path of object.
*
* @param object The object to modify.
* @param path The path of the property to unset.
* @return Returns true if the property is deleted, else false.
*/
unset<T>(
object: T,
path: StringRepresentable | StringRepresentable[]
): boolean;
}
//_.unzip
interface LoDashStatic {
/**
@@ -10009,19 +10058,27 @@ declare module _ {
/**
* Checks if value is empty. A value is considered empty unless its an arguments object, array, string, or
* jQuery-like collection with a length greater than 0 or an object with own enumerable properties.
*
* @param value The value to inspect.
* @return Returns true if value is empty, else false.
**/
isEmpty(value?: any[]|Dictionary<any>|string|any): boolean;
*/
isEmpty(value?: any): boolean;
}
interface LoDashImplicitWrapperBase<T,TWrapper> {
interface LoDashImplicitWrapperBase<T, TWrapper> {
/**
* @see _.isEmpty
*/
isEmpty(): boolean;
}
interface LoDashExplicitWrapperBase<T, TWrapper> {
/**
* @see _.isEmpty
*/
isEmpty(): LoDashExplicitWrapper<boolean>;
}
//_.isEqual
interface LoDashStatic {
/**
@@ -15653,21 +15710,21 @@ declare module _ {
* @param func The function to attempt.
* @return Returns the func result or error object.
*/
attempt<TResult>(func: (...args: any[]) => TResult): TResult|Error;
attempt<TResult>(func: (...args: any[]) => TResult, ...args: any[]): TResult|Error;
}
interface LoDashImplicitObjectWrapper<T> {
/**
* @see _.attempt
*/
attempt<TResult>(): TResult|Error;
attempt<TResult>(...args: any[]): TResult|Error;
}
interface LoDashExplicitObjectWrapper<T> {
/**
* @see _.attempt
*/
attempt<TResult>(): LoDashExplicitObjectWrapper<TResult|Error>;
attempt<TResult>(...args: any[]): LoDashExplicitObjectWrapper<TResult|Error>;
}
//_.constant
@@ -16138,6 +16195,46 @@ declare module _ {
noop(...args: any[]): _.LoDashExplicitWrapper<void>;
}
//_.over
interface LoDashStatic {
/**
* Creates a function that invokes iteratees with the arguments provided to the created function and returns
* their results.
*
* @param iteratees The iteratees to invoke.
* @return Returns the new function.
*/
over<TResult>(...iteratees: (Function|Function[])[]): (...args: any[]) => TResult[];
}
interface LoDashImplicitArrayWrapper<T> {
/**
* @see _.over
*/
over<TResult>(...iteratees: (Function|Function[])[]): LoDashImplicitObjectWrapper<(...args: any[]) => TResult[]>;
}
interface LoDashImplicitObjectWrapper<T> {
/**
* @see _.over
*/
over<TResult>(...iteratees: (Function|Function[])[]): LoDashImplicitObjectWrapper<(...args: any[]) => TResult[]>;
}
interface LoDashExplicitArrayWrapper<T> {
/**
* @see _.over
*/
over<TResult>(...iteratees: (Function|Function[])[]): LoDashExplicitObjectWrapper<(...args: any[]) => TResult[]>;
}
interface LoDashExplicitObjectWrapper<T> {
/**
* @see _.over
*/
over<TResult>(...iteratees: (Function|Function[])[]): LoDashExplicitObjectWrapper<(...args: any[]) => TResult[]>;
}
//_.property
interface LoDashStatic {
/**
+2
View File
@@ -77,3 +77,5 @@ moment.tz.load({
moment.tz.names();
moment.tz.setDefault('America/Los_Angeles');
moment.tz.guess();
+1
View File
@@ -68,6 +68,7 @@ interface MomentTimezone {
}): void;
names(): string[];
guess(): MomentZone;
setDefault(timezone: string): void;
}
+30
View File
@@ -0,0 +1,30 @@
///<reference path="mongodb-1.4.9.d.ts"/>
// Test source : https://github.com/mongodb/node-mongodb-native
import mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/test', function (err, db) {
if (err) throw err;
var collection = db.collection('test_insert');
collection.insert({ a: 2 }, function (err, docs) {
collection.count(function (err, count) {
console.log(format("count = %s", count));
});
// Locate all the entries using find
collection.find().toArray(function (err, results) {
console.dir(results);
// Let's close the db
db.close();
});
// Get some statistics
collection.stats(function (err, stats) {
console.log(stats.count + " documents");
});
});
})
+543
View File
@@ -0,0 +1,543 @@
// Type definitions for MongoDB
// Project: https://github.com/mongodb/node-mongodb-native
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Documentation : http://mongodb.github.io/node-mongodb-native/
/// <reference path='../node/node.d.ts' />
declare module "mongodb" {
// Class documentation : http://mongodb.github.io/node-mongodb-native/api-generated/mongoclient.html
export class MongoClient{
constructor(serverConfig: any, options: any);
static connect(uri: string, callback?: (err: Error, db: Db) => void): void;
static connect(uri: string, options: any, callback?: (err: Error, db: Db) => void): void;
}
// Class documentation : http://mongodb.github.io/node-mongodb-native/api-generated/server.html
export class Server {
constructor (host: string, port: number, opts?: ServerOptions);
public connect(): any;
}
// Class documentation : http://mongodb.github.io/node-mongodb-native/api-generated/db.html
export class Db {
constructor (databaseName: string, serverConfig: Server, dbOptions?: DbCreateOptions);
public db(dbName: string): Db;
public open(callback?: (err : Error, db : Db) => void ): void;
public close(forceClose?: boolean, callback?: (err: Error, result: any) => void ): void;
public admin(callback?: (err: Error, result: any) => void ): any;
public collectionsInfo(collectionName: string, callback?: (err: Error, result: any) => void ): void;
public collectionNames(collectionName: string, options: any, callback?: (err: Error, result: any) => void ): void;
public collection(collectionName: string): Collection;
public collection(collectionName: string, callback?: (err: Error, collection: Collection) => void ): Collection;
public collection(collectionName: string, options: MongoCollectionOptions, callback?: (err: Error, collection: Collection) => void ): Collection;
public collections(callback?: (err: Error, collections: Collection[]) => void ): void;
public eval(code: any, parameters: any[], options?: any, callback?: (err: Error, result: any) => void ): void;
//public dereference(dbRef: DbRef, callback?: (err: Error, result: any) => void): void;
public logout(callback?: (err: Error, result: any) => void ): void;
public logout(options: any, callback?: (err: Error, result: any) => void ): void;
public authenticate(userName: string, password: string, callback?: (err: Error, result: any) => void ): void;
public authenticate(userName: string, password: string, options: any, callback?: (err: Error, result: any) => void ): void;
public addUser(username: string, password: string, callback?: (err: Error, result: any) => void ): void;
public addUser(username: string, password: string, options: any, callback?: (err: Error, result: any) => void ): void;
public removeUser(username: string, callback?: (err: Error, result: any) => void ): void;
public removeUser(username: string, options: any, callback?: (err: Error, result: any) => void ): void;
public createCollection(collectionName: string, callback?: (err: Error, result: Collection) => void ): void;
public createCollection(collectionName: string, options: CollectionCreateOptions, callback?: (err: Error, result: any) => void ): void;
public command(selector: Object, callback?: (err: Error, result: any) => void ): void;
public command(selector: Object, options: any, callback?: (err: Error, result: any) => void ): void;
public dropCollection(collectionName: string, callback?: (err: Error, result: any) => void ): void;
public renameCollection(fromCollection: string, toCollection: string, callback?: (err: Error, result: any) => void ): void;
public lastError(options: Object, connectionOptions: any, callback?: (err: Error, result: any) => void ): void;
public previousError(options: Object, callback?: (err: Error, result: any) => void ): void;
// error = lastError
// lastStatus = lastError
public executeDbCommand(command_hash: any, callback?: (err: Error, result: any) => void ): void;
public executeDbCommand(command_hash: any, options: any, callback?: (err: Error, result: any) => void ): void;
public executeDbAdminCommand(command_hash: any, callback?: (err: Error, result: any) => void ): void;
public executeDbAdminCommand(command_hash: any, options: any, callback?: (err: Error, result: any) => void ): void;
public resetErrorHistory(callback?: (err: Error, result: any) => void ): void;
public resetErrorHistory(options: any, callback?: (err: Error, result: any) => void ): void;
public createIndex(collectionName: any, fieldOrSpec: any, options: IndexOptions, callback?: Function): void;
public ensureIndex(collectionName: any, fieldOrSpec: any, options: IndexOptions, callback?: Function): void;
public cursorInfo(options: any, callback?: Function): void;
public dropIndex(collectionName: string, indexName: string, callback?: Function): void;
public reIndex(collectionName: string, callback?: Function): void;
public indexInformation(collectionName: string, options: any, callback?: Function): void;
public dropDatabase(callback?: (err: Error, result: any) => void ): void;
public stats(options: any, callback?: Function): void;
public _registerHandler(db_command: any, raw: any, connection: any, exhaust: any, callback?: Function): void;
public _reRegisterHandler(newId: any, object: any, callback?: Function): void;
public _callHandler(id: any, document: any, err: any): any;
public _hasHandler(id: any): any;
public _removeHandler(id: any): any;
public _findHandler(id: any): { id: string; callback?: Function; };
public __executeQueryCommand(self: any, db_command: any, options: any, callback?: any): void;
public DEFAULT_URL: string;
public connect(url: string, options: { uri_decode_auth?: boolean; }, callback?: (err: Error, result: any) => void ): void;
public addListener(event: string, handler:(param: any) => any): any;
}
// Class documentation : http://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html
// Last update: doc. version 1.3.13 (28.08.2013)
export class ObjectID {
constructor (s?: string);
// Returns the ObjectID id as a 24 byte hex string representation
public toHexString() : string;
// Compares the equality of this ObjectID with otherID.
public equals(otherID: ObjectID) : boolean;
// Returns the generation date (accurate up to the second) that this ID was generated.
public getTimestamp(): Date;
// Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID.
// time an integer number representing a number of seconds.
public static createFromTime(time: number): ObjectID;
// Creates an ObjectID from a hex string representation of an ObjectID.
// hexString create a ObjectID from a passed in 24 byte hexstring.
public static createFromHexString(hexString: string): ObjectID;
// Checks if a value is a valid bson ObjectId
// id - Value to be checked
public static isValid(id: string): Boolean;
// Generate a 12 byte id string used in ObjectID's
// time - optional parameter allowing to pass in a second based timestamp
public generate(time?: number): string;
}
// Class documentation : http://mongodb.github.io/node-mongodb-native/api-bson-generated/binary.html
export class Binary {
constructor (buffer: Buffer, subType?: number);
// Updates this binary with byte_value
put(byte_value: any): void;
// Writes a buffer or string to the binary
write(buffer: any, offset: number): void;
// Reads length bytes starting at position.
read(position: number, length: number): Buffer;
// Returns the value of this binary as a string.
value(): string;
// The length of the binary.
length(): number;
}
export interface SocketOptions {
//= set seconds before connection times out default:0
timeout?: number;
//= Disables the Nagle algorithm default:true
noDelay?: boolean;
//= Set if keepAlive is used default:0 , which means no keepAlive, set higher than 0 for keepAlive
keepAlive?: number;
//= ascii|utf8|base64 default:null
encoding?: string;
}
export interface ServerOptions {
// - to reconnect automatically, default:false
auto_reconnect?: boolean;
// - specify the number of connections in the pool default:1
poolSize?: number;
// - a collection of pr socket settings
socketOptions?: any;
}
export interface PKFactory {
counter: number;
createPk: () => number;
}
// See : http://mongodb.github.io/node-mongodb-native/api-generated/db.html
// Current definition by documentation version 1.3.13 (28.08.2013)
export interface DbCreateOptions {
// the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = majority or tag acknowledges the write.
w?: any;
// set the timeout for waiting for write concern to finish (combines with w option).
wtimeout?: number;
// write waits for fsync before returning. default:false.
fsync?: boolean;
// write waits for journal sync before returning. default:false.
journal?: boolean;
// the prefered read preference. use 'ReadPreference' class.
readPreference?: string;
// use c++ bson parser. default:false.
native_parser?: boolean;
// force server to create _id fields instead of client. default:false.
forceServerObjectId?: boolean;
// custom primary key factory to generate _id values (see Custom primary keys).
pkFactory?: PKFactory;
// serialize functions. default:false.
serializeFunctions?: boolean;
// peform operations using raw bson buffers. default:false.
raw?: boolean;
// record query statistics during execution. default:false.
recordQueryStats?: boolean;
// number of miliseconds between retries. default:5000.
retryMiliSeconds?: number;
// number of retries off connection. default:5.
numberOfRetries?: number;
// an object representing a logger that you want to use, needs to support functions debug, log, error. default:null.
logger?: Object
// force setting of SlaveOk flag on queries (only use when explicitly connecting to a secondary server). default:null.
slaveOk?: number;
// when deserializing a Long will fit it into a Number if its smaller than 53 bits. default:true.
promoteLongs?: boolean;
}
export class ReadPreference {
public static PRIMARY: string;
public static PRIMARY_PREFERRED: string;
public static SECONDARY: string;
public static SECONDARY_PREFERRED: string;
public static NEAREST: string;
}
// See : http://mongodb.github.io/node-mongodb-native/api-generated/collection.html
// Current definition by documentation version 1.3.13 (28.08.2013)
export interface CollectionCreateOptions {
// the prefered read preference. use 'ReadPreference' class.
readPreference?: string;
// Allow reads from secondaries. default:false.
slaveOk?: boolean;
// serialize functions on the document. default:false.
serializeFunctions?: boolean;
// perform all operations using raw bson objects. default:false.
raw?: boolean;
// object overriding the basic ObjectID primary key generation.
pkFactory?: PKFactory;
}
// Documentation: http://docs.mongodb.org/manual/reference/command/collStats/
export interface CollStats {
// Namespace.
ns: string;
// Number of documents.
count: number;
// Collection size in bytes.
size: number;
// Average object size in bytes.
avgObjSize: number;
// (Pre)allocated space for the collection in bytes.
storageSize: number;
// Number of extents (contiguously allocated chunks of datafile space).
numExtents: number;
// Number of indexes.
nindexes: number;
// Size of the most recently created extent in bytes.
lastExtentSize: number;
// Padding can speed up updates if documents grow.
paddingFactor: number;
flags: number;
// Total index size in bytes.
totalIndexSize: number;
// Size of specific indexes in bytes.
indexSizes: {
_id_: number;
username: number;
};
}
// Documentation : http://mongodb.github.io/node-mongodb-native/api-generated/collection.html
export interface Collection {
new (db: Db, collectionName: string, pkFactory?: Object, options?: CollectionCreateOptions): Collection; // is this right?
/**
* @deprecated use insertOne or insertMany
* Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insert
*/
insert(query: any, callback?: (err: Error, result: any) => void): void;
insert(query: any, options: { safe?: any; continueOnError?: boolean; keepGoing?: boolean; serializeFunctions?: boolean; }, callback?: (err: Error, result: any) => void): void;
// Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insertOne
insertOne(doc:any, callback?: (err: Error, result: any) => void) :void;
insertOne(doc: any, options: { w?: any; wtimeout?: number; j?: boolean; serializeFunctions?: boolean; forceServerObjectId?: boolean }, callback?: (err: Error, result: any) => void): void;
// Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insertMany
insertMany(docs: any, callback?: (err: Error, result: any) => void): void;
insertMany(docs: any, options: { w?: any; wtimeout?: number; j?: boolean; serializeFunctions?: boolean; forceServerObjectId?: boolean }, callback?: (err: Error, result: any) => void): void;
/**
* @deprecated use deleteOne or deleteMany
* Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#remove
*/
remove(selector: Object, callback?: (err: Error, result: any) => void): void;
remove(selector: Object, options: { safe?: any; single?: boolean; }, callback?: (err: Error, result: any) => void): void;
// Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#deleteOne
deleteOne(filter: any, callback?: (err: Error, result: any) => void): void;
deleteOne(filter: any, options: { w?: any; wtimeout?: number; j?: boolean;}, callback?: (err: Error, result: any) => void): void;
// Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#deleteMany
deleteMany(filter: any, callback?: (err: Error, result: any) => void): void;
deleteMany(filter: any, options: { w?: any; wtimeout?: number; j?: boolean;}, callback?: (err: Error, result: any) => void): void;
rename(newName: String, callback?: (err: Error, result: any) => void): void;
save(doc: any, callback : (err: Error, result: any) => void): void;
save(doc: any, options: { w?: any; wtimeout?: number; j?: boolean;}, callback : (err: Error, result: any) => void): void;
/**
* @deprecated use updateOne or updateMany
* Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#update
*/
update(selector: Object, document: any, callback?: (err: Error, result: any) => void): void;
update(selector: Object, document: any, options: { safe?: boolean; upsert?: any; multi?: boolean; serializeFunctions?: boolean; }, callback?: (err: Error, result: any) => void): void;
// Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#updateOne
updateOne(filter: Object, update: any, callback?: (err: Error, result: any) => void): void;
updateOne(filter: Object, update: any, options: { upsert?: boolean; w?: any; wtimeout?: number; j?: boolean;}, callback?: (err: Error, result: any) => void): void;
// Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#updateMany
updateMany(filter: Object, update: any, callback?: (err: Error, result: any) => void): void;
updateMany(filter: Object, update: any, options: { upsert?: boolean; w?: any; wtimeout?: number; j?: boolean;}, callback?: (err: Error, result: any) => void): void;
distinct(key: string, query: Object, callback?: (err: Error, result: any) => void): void;
distinct(key: string, query: Object, options: { readPreference: string; }, callback?: (err: Error, result: any) => void): void;
count(callback?: (err: Error, result: any) => void): void;
count(query: Object, callback?: (err: Error, result: any) => void): void;
count(query: Object, options: { readPreference: string; }, callback?: (err: Error, result: any) => void): void;
drop(callback?: (err: Error, result: any) => void): void;
/**
* @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete
* Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify
*/
findAndModify(query: Object, sort: any[], doc: Object, callback?: (err: Error, result: any) => void): void;
findAndModify(query: Object, sort: any[], doc: Object, options: { safe?: any; remove?: boolean; upsert?: boolean; new?: boolean; }, callback?: (err: Error, result: any) => void): void;
/**
* @deprecated use findOneAndDelete
* Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndRemove
*/
findAndRemove(query : Object, sort? : any[], callback?: (err: Error, result: any) => void): void;
findAndRemove(query : Object, sort? : any[], options?: { safe: any; }, callback?: (err: Error, result: any) => void): void;
// Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findOneAndDelete
findOneAndDelete(filter: any, callback?: (err: Error, result: any) => void): void;
findOneAndDelete(filter: any, options: { projection?: any; sort?: any; maxTimeMS?: number; }, callback?: (err: Error, result: any) => void): void;
// Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findOneAndReplace
findOneAndReplace(filter: any, replacement: any, callback?: (err: Error, result: any) => void): void;
findOneAndReplace(filter: any, replacement: any, options: { projection?: any; sort?: any; maxTimeMS?: number; upsert?: boolean; returnOriginal?: boolean }, callback?: (err: Error, result: any) => void): void;
// Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findOneAndUpdate
findOneAndUpdate(filter: any, update: any, callback?: (err: Error, result: any) => void): void;
findOneAndUpdate(filter: any, update: any, options: { projection?: any; sort?: any; maxTimeMS?: number; upsert?: boolean; returnOriginal?: boolean }, callback?: (err: Error, result: any) => void): void;
find(callback?: (err: Error, result: Cursor) => void): Cursor;
find(selector: Object, callback?: (err: Error, result: Cursor) => void): Cursor;
find(selector: Object, fields: any, callback?: (err: Error, result: Cursor) => void): Cursor;
find(selector: Object, options: CollectionFindOptions, callback?: (err: Error, result: Cursor) => void): Cursor;
find(selector: Object, fields: any, options: CollectionFindOptions, callback?: (err: Error, result: Cursor) => void): Cursor;
find(selector: Object, fields: any, skip: number, limit: number, callback?: (err: Error, result: Cursor) => void): Cursor;
find(selector: Object, fields: any, skip: number, limit: number, timeout: number, callback?: (err: Error, result: Cursor) => void): Cursor;
findOne(callback?: (err: Error, result: any) => void): Cursor;
findOne(selector: Object, callback?: (err: Error, result: any) => void): Cursor;
findOne(selector: Object, fields: any, callback?: (err: Error, result: any) => void): Cursor;
findOne(selector: Object, options: CollectionFindOptions, callback?: (err: Error, result: any) => void): Cursor;
findOne(selector: Object, fields: any, options: CollectionFindOptions, callback?: (err: Error, result: any) => void): Cursor;
findOne(selector: Object, fields: any, skip: number, limit: number, callback?: (err: Error, result: any) => void): Cursor;
findOne(selector: Object, fields: any, skip: number, limit: number, timeout: number, callback?: (err: Error, result: any) => void): Cursor;
createIndex(fieldOrSpec: any, callback?: (err: Error, indexName: string) => void): void;
createIndex(fieldOrSpec: any, options: IndexOptions, callback?: (err: Error, indexName: string) => void): void;
ensureIndex(fieldOrSpec: any, callback?: (err: Error, indexName: string) => void): void;
ensureIndex(fieldOrSpec: any, options: IndexOptions, callback?: (err: Error, indexName: string) => void): void;
indexInformation(options: any, callback?: Function): void;
dropIndex(name: string, callback?: Function): void;
dropAllIndexes(callback?: Function): void;
// dropIndexes = dropAllIndexes
reIndex(callback?: Function): void;
mapReduce(map: Function, reduce: Function, options: MapReduceOptions, callback?: Function): void;
group(keys: Object, condition: Object, initial: Object, reduce: Function, finalize: Function, command: boolean, options: {readPreference: string}, callback?: Function): void;
options(callback?: Function): void;
isCapped(callback?: Function): void;
indexExists(indexes: string, callback?: Function): void;
geoNear(x: number, y: number, callback?: Function): void;
geoNear(x: number, y: number, options: Object, callback?: Function): void;
geoHaystackSearch(x: number, y: number, callback?: Function): void;
geoHaystackSearch(x: number, y: number, options: Object, callback?: Function): void;
indexes(callback?: Function): void;
aggregate(pipeline: any[], callback?: (err: Error, results: any) => void): void;
aggregate(pipeline: any[], options: {readPreference: string}, callback?: (err: Error, results: any) => void): void;
stats(callback?: (err: Error, results: CollStats) => void): void;
stats(options: {readPreference: string; scale: number}, callback?: (err: Error, results: CollStats) => void): void;
hint: any;
}
export interface MapReduceOptions {
out?: Object;
query?: Object;
sort?: Object;
limit?: number;
keeptemp?: boolean;
finalize?: any;
scope?: Object;
jsMode?: boolean;
verbose?: boolean;
readPreference?: string;
}
export interface IndexOptions {
w?: any;
wtimeout?: number;
fsync?: boolean;
journal?: boolean;
unique?: boolean;
sparse?: boolean;
background?: boolean;
dropDups?: boolean;
min?: number;
max?: number;
v?: number;
expireAfterSeconds?: number;
name?: string;
}
// Class documentation : http://mongodb.github.io/node-mongodb-native/api-generated/cursor.html
// Last update: doc. version 1.3.13 (29.08.2013)
export class Cursor {
// INTERNAL TYPE
// constructor (db: Db, collection: Collection, selector, fields, skip, limit, sort, hint, explain, snapshot, timeout, tailable, batchSize, slaveOk, raw, read, returnKey, maxScan, min, max, showDiskLoc, comment, awaitdata, numberOfRetries, dbName, tailableRetryInterval, exhaust, partial);
// constructor(db: Db, collection: Collection, selector, fields, options);
rewind() : Cursor;
toArray(callback?: (err: Error, results: any[]) => any) : void;
each(callback?: (err: Error, item: any) => void) : void;
count(applySkipLimit: boolean, callback?: (err: Error, count: number) => void) : void;
sort(keyOrList: any, callback? : (err: Error, result: any) => void): Cursor;
// this determines how the results are sorted. "asc", "ascending" or 1 for asceding order while "desc", "desceding or -1 for descending order. Note that the strings are case insensitive.
sort(keyOrList: String, direction : string, callback : (err: Error, result: any) => void): Cursor;
limit(limit: number, callback?: (err: Error, result: any) => void): Cursor;
setReadPreference(preference: string, callback?: Function): Cursor;
skip(skip: number, callback?: (err: Error, result: any) => void): Cursor;
batchSize(batchSize: number, callback?: (err: Error, result: any) => void): Cursor;
nextObject(callback?: (err: Error, doc: any) => void) : void;
explain(callback?: (err: Error, result: any) => void) : void;
stream(): CursorStream;
close(callback?: (err: Error, result: any) => void) : void;
isClosed(): boolean;
public static INIT: number;
public static OPEN: number;
public static CLOSED: number;
public static GET_MORE: number;
}
// Class documentation : http://mongodb.github.io/node-mongodb-native/api-generated/cursorstream.html
// Last update: doc. version 1.3.13 (29.08.2013)
export class CursorStream {
constructor(cursor: Cursor);
public pause(): any;
public resume(): any;
public destroy(): any;
}
export interface CollectionFindOptions {
limit?: number;
sort?: any;
fields?: Object;
skip?: number;
hint?: Object;
explain?: boolean;
snapshot?: boolean;
timeout?: boolean;
tailtable?: boolean;
tailableRetryInterval?: number;
numberOfRetries?: number;
awaitdata?: boolean;
oplogReplay?: boolean;
exhaust?: boolean;
batchSize?: number;
returnKey?: boolean;
maxScan?: number;
min?: number;
max?: number;
showDiskLoc?: boolean;
comment?: String;
raw?: boolean;
readPreference?: String;
partial?: boolean;
}
export interface MongoCollectionOptions {
safe?: any;
serializeFunctions?: any;
strict?: boolean;
raw?: boolean;
pkFactory?: any;
readPreference?: string;
}
}
+5 -5
View File
@@ -5,25 +5,25 @@ import mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/test', function (err, db) {
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err: mongodb.MongoError, db: mongodb.Db) {
if (err) throw err;
var collection = db.collection('test_insert');
collection.insert({ a: 2 }, function (err, docs) {
collection.insertOne({ a: 2 }, function(err: mongodb.MongoError, docs: any) {
collection.count(function (err, count) {
collection.count(function(err: mongodb.MongoError, count: any) {
console.log(format("count = %s", count));
});
// Locate all the entries using find
collection.find().toArray(function (err, results) {
collection.find({}).toArray(function(err: mongodb.MongoError, results: any) {
console.dir(results);
// Let's close the db
db.close();
});
// Get some statistics
collection.stats(function (err, stats) {
collection.stats(function(err: mongodb.MongoError, stats: any) {
console.log(stats.count + " documents");
});
});
+1186 -460
View File
File diff suppressed because it is too large Load Diff
+9 -2
View File
@@ -459,7 +459,7 @@ declare module "http" {
host?: string;
hostname?: string;
family?: number;
port?: number
port?: number;
localAddress?: string;
socketPath?: string;
method?: string;
@@ -643,6 +643,13 @@ declare module "cluster" {
// Event emitter
export function addListener(event: string, listener: Function): void;
export function on(event: "disconnect", listener: (worker: Worker) => void): void;
export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): void;
export function on(event: "fork", listener: (worker: Worker) => void): void;
export function on(event: "listening", listener: (worker: Worker, address: any) => void): void;
export function on(event: "message", listener: (worker: Worker, message: any) => void): void;
export function on(event: "online", listener: (worker: Worker) => void): void;
export function on(event: "setup", listener: (settings: any) => void): void;
export function on(event: string, listener: Function): any;
export function once(event: string, listener: Function): void;
export function removeListener(event: string, listener: Function): void;
@@ -731,7 +738,7 @@ declare module "os" {
sys: number;
idle: number;
irq: number;
}
};
}
export interface NetworkInterfaceInfo {
+5 -1
View File
@@ -12,7 +12,11 @@ Polymer({
reflectToAttribute: true,
notify: true,
computed: "__prop2()"
}
},
prop3: {
type: Object,
value: { "foo": "bar" },
},
},
hostAttributes: {
+2 -2
View File
@@ -1,4 +1,4 @@
// Type definitions for polymer v1.1.5
// Type definitions for polymer v1.1.6
// Project: https://github.com/Polymer/polymer
// Definitions by: Louis Grignon <https://github.com/lgrignon>, Suguru Inatomi <https://github.com/laco0416>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -11,7 +11,7 @@ declare module polymer {
interface PropObjectType {
type: PropConstructorType;
value?: boolean | number | string | Function;
value?: boolean | number | string | Function | Object;
reflectToAttribute?: boolean;
readOnly?: boolean;
notify?: boolean;
+84
View File
@@ -0,0 +1,84 @@
/// <reference path="rc-select.d.ts" />
/// <reference path="../react/react.d.ts" />
import React = require('react');
import Select = require('rc-select');
class Component extends React.Component<any, any> {
private onChange(value: any) {
console.log('selected', value);
}
private onSelect(value: string, option: RcSelect.Option) {
console.log('selected value', value);
console.log('selected option', option);
}
private onSearch() {
console.log('input changed');
}
private defaultSelectProps: RcSelect.SelectProps = {
className: "my-select",
prefixCls: "prefix",
animation: "slide-up",
transitionName: "my-animation",
choiceTransitionName: "multiple-animation",
dropdownMatchSelectWidth: true,
dropdownClassName: "my-dropdown",
dropdownStyle: { backgroundColor: "green" },
dropdownMenuStyle: { backgroundColor: "red" },
notFoundContent: "Something went wrong...",
showSearch: true,
allowClear: true,
tags: false,
maxTagTextLength: 30,
combobox: false,
multiple: true,
disabled: false,
filterOption: false,
defaultValue: "Option2",
value: "Option2",
defaultLabel: "Option2",
defaultActiveFirstOption: false
};
private defaultOptGroupProps: RcSelect.OptGroupProps = {
label: "Option group",
key: "option-group-0",
value: "option-group-0"
};
private defaultOptionProps: RcSelect.OptionProps = {
className: "option",
disabled: true,
key: "option-0",
value: "option-0"
};
private createOptions(count: number): React.ReactElement<RcSelect.OptionProps>[] {
let options: React.ReactElement<RcSelect.OptionProps>[] = [];
for (let i = 0; i < count; i++) {
let props = this.defaultOptionProps;
props.key = `option-${i}`;
props.value = `option-${i}`;
options.push(React.createElement(Select.Option, props));
}
return options;
}
render() {
let options: React.ReactElement<RcSelect.OptionProps>[] = this.createOptions(10);
let optionGroup: React.ReactElement<RcSelect.OptGroupProps> = React.createElement(Select.OptGroup, this.defaultOptGroupProps, options);
let select: React.ReactElement<RcSelect.SelectProps> = React.createElement(Select.default, this.defaultSelectProps, optionGroup);
return select;
}
}
+67
View File
@@ -0,0 +1,67 @@
// Type definitions for React Select v5.9.0
// Project: https://github.com/react-component/select
// Definitions by: Denis Tirilis <https://github.com/DenisTirilis>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../react/react.d.ts" />
declare namespace RcSelect {
import React = __React;
interface SelectProps {
className?: string;
prefixCls?: string;
animation?: string;
transitionName?: string;
choiceTransitionName?: string;
dropdownMatchSelectWidth?: boolean;
dropdownClassName?: string;
dropdownStyle?: { [key: string]: string };
dropdownMenuStyle?: { [key: string]: string };
notFoundContent?: string;
showSearch?: boolean;
allowClear?: boolean;
tags?: boolean;
maxTagTextLength?: number;
combobox?: boolean;
multiple?: boolean;
disabled?: boolean;
filterOption?: boolean;
optionFilterProp?: string;
optionLabelProp?: string;
defaultValue?: string | Array<string>;
value?: string | Array<string>;
onChange?: (value: string, label: string) => void;
onSearch?: Function;
onSelect?: (value: string, ontion: Option) => void;
onDeselect?: Function;
defaultLabel?: string | Array<string>;
defaultActiveFirstOption?: boolean;
getPopupContainer?: (trigger: Node) => Node;
}
export class Select extends React.Component<SelectProps, any> { }
interface OptionProps {
className?: string;
disabled?: boolean;
key?: string;
value?: string;
}
export class Option extends React.Component<OptionProps, any> { }
interface OptGroupProps {
label?: string | React.ReactElement<any>;
key?: string;
value?: string;
}
export class OptGroup extends React.Component<OptGroupProps, any> { }
}
declare module 'rc-select' {
import Select = RcSelect.Select;
import Option = RcSelect.Option;
import OptGroup = RcSelect.OptGroup;
export default Select;
export {
Option,
OptGroup
};
}
+2 -2
View File
@@ -4,8 +4,8 @@
/// <reference path="../express/express.d.ts" />
import { createStore, applyMiddleware, Store, Dispatch } from 'redux';
import thunk from 'redux-thunk';
import { ThunkInterface } from 'redux-thunk';
import * as thunk from 'redux-thunk';
import ThunkInterface = ReduxThunk.ThunkInterface;
import { Promise } from 'es6-promise';
declare var rootReducer: Function;
+7 -10
View File
@@ -5,17 +5,14 @@
/// <reference path="../redux/redux.d.ts" />
declare module "redux-thunk" {
import { Middleware, Dispatch } from 'redux';
export interface Thunk extends Middleware { }
declare module ReduxThunk {
export interface Thunk extends Redux.Middleware {}
export interface ThunkInterface {
<T>(dispatch: Dispatch, getState?: () => T): any;
<T>(dispatch: Redux.Dispatch, getState?: () => T): any;
}
var thunk: Thunk;
export default thunk;
}
declare module "redux-thunk" {
var thunk: ReduxThunk.Thunk;
export = thunk;
}
+150 -79
View File
@@ -20,7 +20,24 @@ declare module RiotGamesAPI{
champions: Array<ChampionDto>
}
}
/**
* championmastery
*/
module ChampionMastery{
interface ChampionMasteryDto {
championId: number,
championLevel: number,
championPoints: number,
championPointsSinceLastLevel: number,
championPointsUntilNextLevel: number,
chestGranted: boolean,
highestGrade: string,
lastPlayTime: number,
playerId: number
}
}
/**
* current-game-v1.0
*/
@@ -67,7 +84,7 @@ declare module RiotGamesAPI{
runeId: number
}
}
/**
* featured-games-v1.0
*/
@@ -107,7 +124,7 @@ declare module RiotGamesAPI{
encryptionKey: string
}
}
/**
* game-v1.3
*/
@@ -219,7 +236,7 @@ declare module RiotGamesAPI{
win: boolean
}
}
/**
* league-v2.5
*/
@@ -251,7 +268,7 @@ declare module RiotGamesAPI{
wins: number
}
}
/**
* lol-static-data-v1.2
*/
@@ -450,70 +467,70 @@ declare module RiotGamesAPI{
tags: Array<string>
}
interface BasicDataStatsDto{
FlatArmorMod: number,
FlatAttackSpeedMod: number,
FlatBlockMod: number,
FlatCritChanceMod: number,
FlatCritDamageMod: number,
FlatEXPBonus: number,
FlatEnergyPoolMod: number,
FlatEnergyRegenMod: number,
FlatHPPoolMod: number,
FlatHPRegenMod: number,
FlatMPPoolMod: number,
FlatMPRegenMod: number,
FlatMagicDamageMod: number,
FlatMovementSpeedMod: number,
FlatPhysicalDamageMod: number,
FlatSpellBlockMod: number,
PercentArmorMod: number,
PercentAttackSpeedMod: number,
PercentBlockMod: number,
PercentCritChanceMod: number,
PercentCritDamageMod: number,
PercentDodgeMod: number,
PercentEXPBonus: number,
PercentHPPoolMod: number,
PercentHPRegenMod: number,
PercentLifeStealMod: number,
PercentMPPoolMod: number,
PercentMPRegenMod: number,
PercentMagicDamageMod: number,
PercentMovementSpeedMod: number,
PercentPhysicalDamageMod: number,
PercentSpellBlockMod: number,
PercentSpellVampMod: number,
rFlatArmorModPerLevel: number,
rFlatArmorPenetrationMod: number,
rFlatArmorPenetrationModPerLevel: number,
rFlatCritChanceModPerLevel: number,
rFlatCritDamageModPerLevel: number,
rFlatDodgeMod: number,
rFlatDodgeModPerLevel: number,
rFlatEnergyModPerLevel: number,
rFlatEnergyRegenModPerLevel: number,
rFlatGoldPer10Mod: number,
rFlatHPModPerLevel: number,
rFlatHPRegenModPerLevel: number,
rFlatMPModPerLevel: number,
rFlatMPRegenModPerLevel: number,
rFlatMagicDamageModPerLevel: number,
rFlatMagicPenetrationMod: number,
rFlatMagicPenetrationModPerLevel: number,
rFlatMovementSpeedModPerLevel: number,
rFlatPhysicalDamageModPerLevel: number,
rFlatSpellBlockModPerLevel: number,
rFlatTimeDeadMod: number,
rFlatTimeDeadModPerLevel: number,
rPercentArmorPenetrationMod: number,
rPercentArmorPenetrationModPerLevel: number,
rPercentAttackSpeedModPerLevel: number,
rPercentCooldownMod: number,
rPercentCooldownModPerLevel: number,
rPercentMagicPenetrationMod: number,
rPercentMagicPenetrationModPerLevel: number,
rPercentMovementSpeedModPerLevel: number,
rPercentTimeDeadMod: number,
FlatArmorMod: number,
FlatAttackSpeedMod: number,
FlatBlockMod: number,
FlatCritChanceMod: number,
FlatCritDamageMod: number,
FlatEXPBonus: number,
FlatEnergyPoolMod: number,
FlatEnergyRegenMod: number,
FlatHPPoolMod: number,
FlatHPRegenMod: number,
FlatMPPoolMod: number,
FlatMPRegenMod: number,
FlatMagicDamageMod: number,
FlatMovementSpeedMod: number,
FlatPhysicalDamageMod: number,
FlatSpellBlockMod: number,
PercentArmorMod: number,
PercentAttackSpeedMod: number,
PercentBlockMod: number,
PercentCritChanceMod: number,
PercentCritDamageMod: number,
PercentDodgeMod: number,
PercentEXPBonus: number,
PercentHPPoolMod: number,
PercentHPRegenMod: number,
PercentLifeStealMod: number,
PercentMPPoolMod: number,
PercentMPRegenMod: number,
PercentMagicDamageMod: number,
PercentMovementSpeedMod: number,
PercentPhysicalDamageMod: number,
PercentSpellBlockMod: number,
PercentSpellVampMod: number,
rFlatArmorModPerLevel: number,
rFlatArmorPenetrationMod: number,
rFlatArmorPenetrationModPerLevel: number,
rFlatCritChanceModPerLevel: number,
rFlatCritDamageModPerLevel: number,
rFlatDodgeMod: number,
rFlatDodgeModPerLevel: number,
rFlatEnergyModPerLevel: number,
rFlatEnergyRegenModPerLevel: number,
rFlatGoldPer10Mod: number,
rFlatHPModPerLevel: number,
rFlatHPRegenModPerLevel: number,
rFlatMPModPerLevel: number,
rFlatMPRegenModPerLevel: number,
rFlatMagicDamageModPerLevel: number,
rFlatMagicPenetrationMod: number,
rFlatMagicPenetrationModPerLevel: number,
rFlatMovementSpeedModPerLevel: number,
rFlatPhysicalDamageModPerLevel: number,
rFlatSpellBlockModPerLevel: number,
rFlatTimeDeadMod: number,
rFlatTimeDeadModPerLevel: number,
rPercentArmorPenetrationMod: number,
rPercentArmorPenetrationModPerLevel: number,
rPercentAttackSpeedModPerLevel: number,
rPercentCooldownMod: number,
rPercentCooldownModPerLevel: number,
rPercentMagicPenetrationMod: number,
rPercentMagicPenetrationModPerLevel: number,
rPercentMovementSpeedModPerLevel: number,
rPercentTimeDeadMod: number,
rPercentTimeDeadModPerLevel: number
}
interface GoldDto{
@@ -547,7 +564,7 @@ declare module RiotGamesAPI{
data: Array<{[str: string]: MasteryDto}>,
tree: MasteryTreeDto,
type: string,
version: string
version: string
}
interface MasteryDto{
description: Array<string>,
@@ -643,7 +660,7 @@ declare module RiotGamesAPI{
vars: Array<SpellVarsDto>
}
}
/**
* lol-status-v1.0
*/
@@ -690,7 +707,7 @@ declare module RiotGamesAPI{
updated_at: string
}
}
/**
* match-v2.2
*/
@@ -910,7 +927,7 @@ declare module RiotGamesAPI{
y: number
}
}
/**
* matchlist-v2.2
*/
@@ -933,7 +950,7 @@ declare module RiotGamesAPI{
timestamp: number
}
}
/**
* stats-v1.3
*/
@@ -959,7 +976,7 @@ declare module RiotGamesAPI{
averageObjectivePlayerScore: number,
averageTeamObjective: number,
averageTotalPlayerScore: number,
botGamesPlayed: number,
botGamesPlayed: number,
killingSpree: number,
maxAssists: number,
maxChampionsKilled: number,
@@ -1004,7 +1021,7 @@ declare module RiotGamesAPI{
totalTripleKills: number,
totalTurretsKilleds: number,
totalUnrealKills: number
}
}
interface PlayerStatsSummaryListDto{
playerStatSummaries: Array<PlayerStatsSummaryDto>,
summonerId: number
@@ -1017,7 +1034,7 @@ declare module RiotGamesAPI{
wins: number
}
}
/**
* summoner-v1.4
*/
@@ -1058,7 +1075,7 @@ declare module RiotGamesAPI{
runeSlotId: number
}
}
/**
* team-v2.4
*/
@@ -1109,4 +1126,58 @@ declare module RiotGamesAPI{
status: string
}
}
}
/**
* tournament-provider-v1
*/
module TournamentProvider{
interface TournamentCodeParameters{
allowedSummonerIds: SummonerIdParams,
mapType: string,
metadata: string,
pickType: string,
spectatorType: string,
teamSize: number
}
interface SummonerIdParams{
participants: number[]
}
interface TournamentCodeDto{
code: string,
id: number,
lobbyName: string,
map: string,
metaData: string,
participants: number[],
password: string,
pickType: string,
providerId: number,
region: string,
spectators: string,
teamSize: number,
tournamentId: number
}
interface TournamentCodeUpdateParameters{
allowedParticipants: string,
mapType: string,
pickType: string,
spectatorType: string
}
interface LobbyEventDtoWrapper{
eventList: LobbyEventDto[]
}
interface LobbyEventDto{
eventType: string,
summonerId: string,
timestamp: string
}
interface ProviderRegistrationParameters{
region: string,
url: string
}
interface TournamentRegistrationParameters{
name: string,
providerId: number
}
}
}
+1 -1
View File
@@ -5666,7 +5666,7 @@ declare module "sequelize" {
/**
* Validator Interface
*/
interface Validator extends IValidatorStatic {
interface Validator extends ValidatorJS.ValidatorStatic {
notEmpty( str : string ) : boolean;
len( str : string, min : number, max : number ) : boolean;
+7 -4
View File
@@ -31,19 +31,22 @@ function tester1() {
}
function tester2() {
var m1 = Snap.Matrix(1,2,3,4,5,6);
var m1 = Snap.matrix(1,2,3,4,5,6);
m1.add(m1).add(m1);
var m2 = Snap.Matrix(0,0,0,0,0,0);
var m2 = Snap.matrix(0,0,0,0,0,0);
m2.add(1,-1,1,-1,1,-1).add(-1,1,-1,1,-1,1);
var m3 = Snap.Matrix(1,1,1,1,1,1);
m3.add(Snap.Matrix(0,0,0,0,0,0)).add(m2);
var m3 = Snap.matrix(1,1,1,1,1,1);
m3.add(Snap.matrix(0,0,0,0,0,0)).add(m2);
var m4 = Snap.matrix();
console.log(m1.toString());
console.log(m2.toString());
console.log(m3.toString());
console.log(m4.toString());
}
function tester3() {
+311 -311
View File
@@ -5,231 +5,231 @@
window.onload=()=>{
var s = Snap("#svgout");
var path = Snap.path;
var s = Snap("#svgout");
var path = Snap.path;
// bboxing
var b1 = path.bezierBBox(0, 0, 0, 0, 100, 100, 100, 100);
var b2 = path.bezierBBox(50, 50, 50, 50, 150, 150, 150, 150);
var b3 = path.bezierBBox(100, 100, 100, 100, 200, 200, 200, 200);
alert(b1);
alert(b1);
// all true
console.log(path.isBBoxIntersect(b1, b2));
console.log(path.isBBoxIntersect(b1, b3));
console.log(path.isPointInsideBBox(b1, 50, 50));
console.log(path.isPointInsideBBox(b2, 50, 50));
console.log(!path.isPointInsideBBox(b3, 50, 50));
{
// Snap Transforms
var c = s.circle( 200,200,10 );
var r = s.rect(200,100,100,100,20,20).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'red', 'opacity': 0.3 });
var rclone = r.clone();
var rclone2 = r.clone();
var rclone3 = r.clone();
var rclone4 = r.clone();
var rclone5 = r.clone();
//t=relative transform, T=absolute transform, s=relative scale, S=absolute Scale
//r=relative rotate, R=relative rotate
//relative means it takes into account previous transforms to accumulate
//here it doesn't make much difference, until we combine later
rclone.transform( 't100,100');
rclone2.transform( 'r20,200,200' );
rclone3.transform( 'r40,200,200' );
s.text(350,150,"rotate around 200,200");
rclone4.transform( 't100,100r20,200,200' );
rclone5.transform( 't100,100r40,200,200' );
s.text(450,250,"combined translate of 100,100 and rotate around 200,200");
}
{
// Filters - Blur
s.attr({ viewBox: "0 0 600 600" });
var f = s.filter(Snap.filter.blur(5, 10));
var shadow = s.filter(Snap.filter.shadow(0, 2, 3));
var filterChild = f.node.firstChild;
var r = s.rect(100,100,100,100,20,20).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'red', filter: f });
Snap.animate( 0, 10, function( value ) { filterChild.attributes[0].value = value + ',' + value; }, 1000 );
var t = s.text(0,50, 'Hover to blur, hover out for shadow' );
r.hover( addBlur, addShadow );
function addBlur() {
this.attr({ filter: f });
Snap.animate( 0, 10, function( value ) { filterChild.attributes[0].value = value + ',' + value; }, 1000 );
};
function addShadow() {
this.attr({ filter: shadow });
};
}
{
// Drag Handler
var rect = s.rect(20,20,40,40);
var circle = s.circle(60,150,50);
var move = function(dx,dy) {
this.attr({
transform: this.data('origTransform') + (this.data('origTransform') ? "T" : "t") + [dx, dy]
});
}
var start = function() {
this.data('origTransform', this.transform().local );
}
var stop = function() {
console.log('finished dragging');
}
rect.drag(move, start, stop );
circle.drag(move, start, stop );
}
{
// Snap drag and scale example
var dragging = 0;
var handleGroup;
function addHandleFunc() {
if( dragging == 0 ) {
dragging = 1;
var bb = this.getBBox();
var handle = new Array();
handle[0] = s.circle(bb.x,bb.y,10).attr({class: 'handler'});;
handle[1] = s.circle(bb.x+bb.width, bb.y, 10).attr({class: 'handler'});
handleGroup = s.group(this, handle[0], handle[1]);
handleGroup.drag(move,start,stop);
} else {
dragging = 0;
s.append(this);
handleGroup.selectAll('handler').remove();
handleGroup.remove();
}
}
var start = function() {
this.data('origTransform', this.transform().local);
}
var move = function(dx,dy) {
var scale = 1 + dx / 50;
this.attr({
transform: this.data('origTransform') + (this.data('origTransform') ? "S" : "s") + scale
});
}
var stop = function() {};
var myRect = s.rect( 100,100,100,100 ).attr({fill: 'blue'});
myRect.dblclick( addHandleFunc );;
s.text(70,220, 'double click the rect');
}
{
// Snap mask
var bigC = s.circle(200,200,175).attr({ stroke: 'silver', 'strokeWidth': 40, fill: 'silver' });
{
// Snap Transforms
var r = s.rect(100,100,100,100,20,20).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'red' });
var c = s.circle(50,50,50).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'blue' });
var g = s.group(r,c);
g.attr({ mask: bigC });
g.animate({ transform: 'r360,150,150' }, 1000, mina.bounce );
}
{
// Snap animated mask-clippath
var bigC = s.circle(100,100,75).attr({ stroke: 'silver', 'strokeWidth': 40, fill: 'silver' });
var bigC2 = s.circle(250,250,75).attr({ stroke: 'silver', 'strokeWidth': 40, fill: 'silver' });
var clipG = s.group(bigC,bigC2);
var r = s.rect(100,100,100,100,20,20).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'red' });
var c = s.circle(50,50,50).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'blue' });
var g = s.group(r,c);
g.attr({ mask: clipG });
g.animate({ transform: 'r360,150,150' }, 3000, mina.bounce );
clipG.animate({ transform: 't200,0' }, 3000, mina.bounce, function() { clipG.animate({ transform: 't0,0' }, 3000, mina.bounce) } );
var c = s.circle( 200,200,10 );
var r = s.rect(200,100,100,100,20,20).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'red', 'opacity': 0.3 });
}
{
// Snap load and animate svg
var g = s.group();
var tux = Snap.load("Dreaming_tux.svg", function ( loadedFragment ) {
g.append( loadedFragment );
g.hover( hoverover, hoverout );
g.text(300,100, 'hover over me');
} );
var hoverover = function() { g.animate({ transform: 's2r45,150,150' }, 1000, mina.bounce ) };
var hoverout = function() { g.animate({ transform: 's1r0,150,150' }, 1000, mina.bounce ) };
var rclone = r.clone();
var rclone2 = r.clone();
var rclone3 = r.clone();
var rclone4 = r.clone();
var rclone5 = r.clone();
}
{
// Snap path test if a point inside with translation
var x, y, myTranslateX = 200, myTranslateY = 100;
//t=relative transform, T=absolute transform, s=relative scale, S=absolute Scale
//r=relative rotate, R=relative rotate
//relative means it takes into account previous transforms to accumulate
//here it doesn't make much difference, until we combine later
var myPathString = "M 60 0 L 120 0 L 180 60 L 180 120 L 120 180 L 60 180 L 0 120 L 0 60 Z";
var p = s.path( myPathString );
var p2 = s.path( myPathString ).transform("t" + myTranslateX + "," + myTranslateY);
for( var count = 0; count < 500; count++ ) {
x = Math.random() * 800; y = Math.random() * 400;
c = s.circle( x,y,5 ).attr({ fill: "silver" });
// basic path
if( Snap.path.isPointInside( myPathString, x,y ) ) {
c.attr({ fill: "#ff0000" });
}
// matching against path as though it was translated
if( Snap.path.isPointInside( myPathString, x - myTranslateX, y - myTranslateY ) ) {
c.attr({ fill: "#0000ff" });
}
}
}
{
// Snap animate rotate a group
var r = s.rect(100,100,100,100,20,20).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'red' });
var c = s.circle(50,50,50).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'blue' });
var g = s.group(r,c);
g.animate({ transform: 'r360,150,150' }, 1000, mina.bounce );
}
{
// Snap animate in a sequence and multiple anims
var myFrames = [{
rclone.transform( 't100,100');
rclone2.transform( 'r20,200,200' );
rclone3.transform( 'r40,200,200' );
s.text(350,150,"rotate around 200,200");
rclone4.transform( 't100,100r20,200,200' );
rclone5.transform( 't100,100r40,200,200' );
s.text(450,250,"combined translate of 100,100 and rotate around 200,200");
}
{
// Filters - Blur
s.attr({ viewBox: "0 0 600 600" });
var f = s.filter(Snap.filter.blur(5, 10));
var shadow = s.filter(Snap.filter.shadow(0, 2, 3));
var filterChild = f.node.firstChild;
var r = s.rect(100,100,100,100,20,20).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'red', filter: f });
Snap.animate( 0, 10, function( value ) { filterChild.attributes[0].value = value + ',' + value; }, 1000 );
var t = s.text(0,50, 'Hover to blur, hover out for shadow' );
r.hover( addBlur, addShadow );
function addBlur() {
this.attr({ filter: f });
Snap.animate( 0, 10, function( value ) { filterChild.attributes[0].value = value + ',' + value; }, 1000 );
};
function addShadow() {
this.attr({ filter: shadow });
};
}
{
// Drag Handler
var rect = s.rect(20,20,40,40);
var circle = s.circle(60,150,50);
var move = function(dx:number,dy:number) {
this.attr({
transform: this.data('origTransform') + (this.data('origTransform') ? "T" : "t") + [dx, dy]
});
}
var start = function() {
this.data('origTransform', this.transform().local );
}
var stop = function() {
console.log('finished dragging');
}
rect.drag(move, start, stop );
circle.drag(move, start, stop );
}
{
// Snap drag and scale example
var dragging = 0;
var handleGroup:any;
function addHandleFunc() {
if( dragging == 0 ) {
dragging = 1;
var bb = this.getBBox();
var handle = new Array();
handle[0] = s.circle(bb.x,bb.y,10).attr({class: 'handler'});;
handle[1] = s.circle(bb.x+bb.width, bb.y, 10).attr({class: 'handler'});
handleGroup = s.group(this, handle[0], handle[1]);
handleGroup.drag(move,start,stop);
} else {
dragging = 0;
s.append(this);
handleGroup.selectAll('handler').remove();
handleGroup.remove();
}
}
var start = function() {
this.data('origTransform', this.transform().local);
}
var move = function(dx:number,dy:number) {
var scale = 1 + dx / 50;
this.attr({
transform: this.data('origTransform') + (this.data('origTransform') ? "S" : "s") + scale
});
}
var stop = function() {};
var myRect = s.rect( 100,100,100,100 ).attr({fill: 'blue'});
myRect.dblclick( addHandleFunc );;
s.text(70,220, 'double click the rect');
}
{
// Snap mask
var bigC = s.circle(200,200,175).attr({ stroke: 'silver', 'strokeWidth': 40, fill: 'silver' });
var r = s.rect(100,100,100,100,20,20).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'red' });
var c = s.circle(50,50,50).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'blue' });
var g = s.group(r,c);
g.attr({ mask: bigC });
g.animate({ transform: 'r360,150,150' }, 1000, mina.bounce );
}
{
// Snap animated mask-clippath
var bigC = s.circle(100,100,75).attr({ stroke: 'silver', 'strokeWidth': 40, fill: 'silver' });
var bigC2 = s.circle(250,250,75).attr({ stroke: 'silver', 'strokeWidth': 40, fill: 'silver' });
var clipG = s.group(bigC,bigC2);
var r = s.rect(100,100,100,100,20,20).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'red' });
var c = s.circle(50,50,50).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'blue' });
var g = s.group(r,c);
g.attr({ mask: clipG });
g.animate({ transform: 'r360,150,150' }, 3000, mina.bounce );
clipG.animate({ transform: 't200,0' }, 3000, mina.bounce, function() { clipG.animate({ transform: 't0,0' }, 3000, mina.bounce) } );
}
{
// Snap load and animate svg
var g = s.group();
var tux = Snap.load("Dreaming_tux.svg", function ( loadedFragment:Snap.Element ) {
g.append( loadedFragment );
g.hover( hoverover, hoverout );
g.text(300,100, 'hover over me');
} );
var hoverover = function() { g.animate({ transform: 's2r45,150,150' }, 1000, mina.bounce ) };
var hoverout = function() { g.animate({ transform: 's1r0,150,150' }, 1000, mina.bounce ) };
}
{
// Snap path test if a point inside with translation
var x:number, y:number, myTranslateX = 200, myTranslateY = 100;
var myPathString = "M 60 0 L 120 0 L 180 60 L 180 120 L 120 180 L 60 180 L 0 120 L 0 60 Z";
var p = s.path( myPathString );
var p2 = s.path( myPathString ).transform("t" + myTranslateX + "," + myTranslateY);
for( var count = 0; count < 500; count++ ) {
x = Math.random() * 800; y = Math.random() * 400;
c = s.circle( x,y,5 ).attr({ fill: "silver" });
// basic path
if( Snap.path.isPointInside( myPathString, x,y ) ) {
c.attr({ fill: "#ff0000" });
}
// matching against path as though it was translated
if( Snap.path.isPointInside( myPathString, x - myTranslateX, y - myTranslateY ) ) {
c.attr({ fill: "#0000ff" });
}
}
}
{
// Snap animate rotate a group
var r = s.rect(100,100,100,100,20,20).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'red' });
var c = s.circle(50,50,50).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'blue' });
var g = s.group(r,c);
g.animate({ transform: 'r360,150,150' }, 1000, mina.bounce );
}
{
// Snap animate in a sequence and multiple anims
var myFrames = [{
animation: { transform: 'r360,150,150' }, dur: 1000 },
{ animation: { transform: 't100,-100s2,3' }, dur: 1000 },
{ animation: { transform: 't100,100' }, dur: 1000 },
@@ -237,108 +237,108 @@ window.onload=()=>{
{ animation: { transform: 's1,0' }, dur: 1000 },
{ animation: { transform: 's1,1' }, dur: 1000 }];
var rectAnim = [{
animation: { fill: 'green', transform: 'r1180,150,150' }, dur: 1500 },
{ animation: { fill: 'silver', transform: 'r360,150,150' }, dur: 1500 }];
var circleAnim = [{ animation: { transform: 's0,1' }, dur: 1500 },
{ animation: { transform: 's1,1' }, dur: 1500 }];
function nextFrame ( el:Snap.Element, frameArray, whichFrame ) {
if( whichFrame >= frameArray.length ) { return }
el.animate( frameArray[ whichFrame ].animation, frameArray[ whichFrame ].dur, nextFrame.bind( null, el, frameArray, whichFrame + 1 ) );
}
var r = s.rect(100,100,100,100,20,20).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'red' });
var c = s.circle(50,50,50).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'blue' });
var g = s.group(r,c);
//g.animate({ transform: 'r360,150,150' }, 1000, mina.bounce );
nextFrame( g, myFrames, 0 );
nextFrame( r, rectAnim, 0 );
nextFrame( c, circleAnim, 0 );
}
{
// Snap animate number
var t = s.text(50,50,0);
var rectAnim = [{
animation: { fill: 'green', transform: 'r1180,150,150' }, dur: 1500 },
{ animation: { fill: 'silver', transform: 'r360,150,150' }, dur: 1500 }];
Snap.animate(0, 100, function (value) {
t.attr({text: Math.round(value)});
}, 1000);
}
{
// Snap animate text announce
var text = 'Here is some dynamic exciting announcement';
// inspired from http://codepen.io/GreenSock/pen/AGzci
var textArray = text.split(" ");
var len = textArray.length;
var timing = 750;
for( var index=0; index < len; index++ ) {
(function() {
var svgTextElement = s.text(350,100, textArray[index]).attr({ fontSize: '120px', opacity: 0, "text-anchor": "middle" });
setTimeout( function() {
Snap.animate( 0, 1, function( value ) {
//svgTextElement.transform('s' + value ); // Animate by transform
svgTextElement.attr({ 'font-size': value * 100, opacity: value }); // Animate by font-size ?
}, timing, mina.bounce, function() { svgTextElement.remove() } );
}
,index * timing)
}());
};
}
{
// Snap animate on click
var r = s.rect(100,100,100,100,20,20).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'red' });
var c = s.circle(50,50,50).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'blue' });
var otherRect = s.rect(200,200,50,50,10,10).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'green' });
var g = s.group(r,c);
var clickFunc = function () {
g.transform(''); // reset the animation, may not be needed
otherRect.transform('');
g.animate({ transform: 'r45,150,150' }, 1000, mina.bounce ) ;;
otherRect.animate({ transform: 'r360, 150,150' },2000, mina.bounce, endAnim );
};
var endAnim = function() {
otherRect.animate({ transform: 'r90,200,200' }, 2000, mina.bounce );
}
g.click( clickFunc );
}
var circleAnim = [{ animation: { transform: 's0,1' }, dur: 1500 },
{ animation: { transform: 's1,1' }, dur: 1500 }];
{
// Snap and the matrix
var s = Snap("#svgout");
function nextFrame ( el:Snap.Element, frameArray:any[], whichFrame:number ) {
if( whichFrame >= frameArray.length ) { return }
el.animate( frameArray[ whichFrame ].animation, frameArray[ whichFrame ].dur, nextFrame.bind( null, el, frameArray, whichFrame + 1 ) );
var r = s.rect(100,100,100,100,20,20).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'red' });
var c = s.circle(50,50,50).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'blue' });
var t = s.text(150,75,'The order of transformations is important!!!');
var g = s.group(r,c,t);
// TODO: add constructor to Matrix
//var myMatrix = new Snap.Matrix();
var myMatrix :Snap.Matrix;
myMatrix.scale(4,2); // play with scaling before and after the rotate
myMatrix.translate(100,0); // this translate will not be applied to the rotation
myMatrix.rotate(45); // rotate
//myMatrix.scale(4,2);
//myMatrix.translate(100,0); // this translate will take into account the rotated coord space
//g.animate({ transform: myMatrix.toTransformString() },1000); // probably not needed
var myInvertedMatrix = myMatrix.invert();
g.animate({ transform: myMatrix },3000, mina.bounce, function() { g.animate({ transform: myInvertedMatrix }, 3000, mina.bounce) } );
console.log( g.transform(), g.matrix, myMatrix.split() );
}
}
}
var r = s.rect(100,100,100,100,20,20).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'red' });
var c = s.circle(50,50,50).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'blue' });
var g = s.group(r,c);
//g.animate({ transform: 'r360,150,150' }, 1000, mina.bounce );
nextFrame( g, myFrames, 0 );
nextFrame( r, rectAnim, 0 );
nextFrame( c, circleAnim, 0 );
}
{
// Snap animate number
var t = s.text(50,50,0);
Snap.animate(0, 100, function (value) {
t.attr({text: Math.round(value)});
}, 1000);
}
{
// Snap animate text announce
var text = 'Here is some dynamic exciting announcement';
// inspired from http://codepen.io/GreenSock/pen/AGzci
var textArray = text.split(" ");
var len = textArray.length;
var timing = 750;
for( var index=0; index < len; index++ ) {
(function() {
var svgTextElement = s.text(350,100, textArray[index]).attr({ fontSize: '120px', opacity: 0, "text-anchor": "middle" });
setTimeout( function() {
Snap.animate( 0, 1, function( value ) {
//svgTextElement.transform('s' + value ); // Animate by transform
svgTextElement.attr({ 'font-size': value * 100, opacity: value }); // Animate by font-size ?
}, timing, mina.bounce, function() { svgTextElement.remove() } );
}
,index * timing)
}());
};
}
{
// Snap animate on click
var r = s.rect(100,100,100,100,20,20).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'red' });
var c = s.circle(50,50,50).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'blue' });
var otherRect = s.rect(200,200,50,50,10,10).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'green' });
var g = s.group(r,c);
var clickFunc = function () {
g.transform(''); // reset the animation, may not be needed
otherRect.transform('');
g.animate({ transform: 'r45,150,150' }, 1000, mina.bounce ) ;;
otherRect.animate({ transform: 'r360, 150,150' },2000, mina.bounce, endAnim );
};
var endAnim = function() {
otherRect.animate({ transform: 'r90,200,200' }, 2000, mina.bounce );
}
g.click( clickFunc );
}
{
// Snap and the matrix
var s = Snap("#svgout");
var r = s.rect(100,100,100,100,20,20).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'red' });
var c = s.circle(50,50,50).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'blue' });
var t = s.text(150,75,'The order of transformations is important!!!');
var g = s.group(r,c,t);
// TODO: add constructor to Matrix
//var myMatrix = new Snap.Matrix();
var myMatrix :Snap.Matrix;
myMatrix.scale(4,2); // play with scaling before and after the rotate
myMatrix.translate(100,0); // this translate will not be applied to the rotation
myMatrix.rotate(45); // rotate
//myMatrix.scale(4,2);
//myMatrix.translate(100,0); // this translate will take into account the rotated coord space
//g.animate({ transform: myMatrix.toTransformString() },1000); // probably not needed
var myInvertedMatrix = myMatrix.invert();
g.animate({ transform: myMatrix },3000, mina.bounce, function() { g.animate({ transform: myInvertedMatrix }, 3000, mina.bounce) } );
console.log( g.transform(), g.matrix, myMatrix.split() );
}
}
+260 -260
View File
@@ -37,16 +37,16 @@ declare module mina {
update(): void;
}
export function backin(n:number):number;
export function backout(n:number):number;
export function bounce(n:number):number;
export function easein(n:number):number;
export function easeinout(n:number):number;
export function easeout(n:number):number;
export function elastic(n:number):number;
export function getById(id:string):AnimationDescriptor;
export function linear(n:number):number;
export function time():number;
export function backin(n:number):number;
export function backout(n:number):number;
export function bounce(n:number):number;
export function easein(n:number):number;
export function easeinout(n:number):number;
export function easeout(n:number):number;
export function elastic(n:number):number;
export function getById(id:string):AnimationDescriptor;
export function linear(n:number):number;
export function time():number;
}
declare function Snap(width:number|string,height:number|string):Snap.Paper;
@@ -54,111 +54,112 @@ declare function Snap(query:string):Snap.Paper;
declare function Snap(DOM:SVGElement):Snap.Paper;
declare module Snap {
export var filter:Filter;
export var path:Path;
export var filter:Filter;
export var path:Path;
export function Matrix():void;
export function matrix(a:number,b:number,c:number,d:number,e:number,f:number):Matrix;
export function matrix(svgMatrix:SVGMatrix):Matrix;
export function Matrix():void;
export function matrix():Matrix;
export function matrix(a:number,b:number,c:number,d:number,e:number,f:number):Matrix;
export function matrix(svgMatrix:SVGMatrix):Matrix;
export function ajax(url:string,postData:string,callback:Function,scope?:Object):XMLHttpRequest;
export function ajax(url:string,postData:Object,callback:Function,scope?:Object):XMLHttpRequest;
export function ajax(url:string,callback:Function,scope?:Object):XMLHttpRequest;
export function format(token:string,json:Object):string;
export function fragment(varargs:any):Fragment;
export function getElementByPoint(x:number,y:number):Snap.Element;
export function is(o:any,type:string):boolean;
export function load(url:string,callback:Function,scope?:Object):void;
export function plugin(f:Function):void;
export function select(query:string):Snap.Element;
export function selectAll(query:string):any;
export function snapTo(values:Array<number>,value:number,tolerance?:number):number;
export function ajax(url:string,postData:string,callback:Function,scope?:Object):XMLHttpRequest;
export function ajax(url:string,postData:Object,callback:Function,scope?:Object):XMLHttpRequest;
export function ajax(url:string,callback:Function,scope?:Object):XMLHttpRequest;
export function format(token:string,json:Object):string;
export function fragment(varargs:any):Fragment;
export function getElementByPoint(x:number,y:number):Snap.Element;
export function is(o:any,type:string):boolean;
export function load(url:string,callback:Function,scope?:Object):void;
export function plugin(f:Function):void;
export function select(query:string):Snap.Element;
export function selectAll(query:string):any;
export function snapTo(values:Array<number>,value:number,tolerance?:number):number;
export function animate(from:number|number[],to:number|number[],updater:(n:number)=>void,duration:number,easing?:(num:number)=>number,callback?:()=>void):mina.MinaAnimation;
export function animation(attr:Object,duration:number,easing?:(num:number)=>number,callback?:()=>void):Snap.Animation;
export function animate(from:number|number[],to:number|number[],updater:(n:number)=>void,duration:number,easing?:(num:number)=>number,callback?:()=>void):mina.MinaAnimation;
export function animation(attr:Object,duration:number,easing?:(num:number)=>number,callback?:()=>void):Snap.Animation;
export function color(clr:string):RGBHSB;
export function getRGB(color:string):RGB;
export function hsb(h:number,s:number,b:number):HSB;
export function hsl(h:number,s:number,l:number):HSL;
export function rgb(r:number,g:number,b:number):RGB;
export function hsb2rgb(h:number,s:number,v:number):RGB;
export function hsl2rgb(h:number,s:number,l:number):RGB;
export function rgb2hsb(r:number,g:number,b:number):HSB;
export function rgb2hsl(r:number,g:number,b:number):HSL;
export function color(clr:string):RGBHSB;
export function getRGB(color:string):RGB;
export function hsb(h:number,s:number,b:number):HSB;
export function hsl(h:number,s:number,l:number):HSL;
export function rgb(r:number,g:number,b:number):RGB;
export function hsb2rgb(h:number,s:number,v:number):RGB;
export function hsl2rgb(h:number,s:number,l:number):RGB;
export function rgb2hsb(r:number,g:number,b:number):HSB;
export function rgb2hsl(r:number,g:number,b:number):HSL;
export function angle(x1:number,y1:number,x2:number,y2:number,x3?:number,y3?:number):number;
export function rad(deg:number):number;
export function deg(rad:number):number;
export function sin(angle: number): number;
export function cos(angle: number): number;
export function tan(angle: number): number;
export function asin(angle: number): number;
export function acos(angle: number): number;
export function atan(angle: number): number;
export function atan2(angle: number): number;
export function angle(x1:number,y1:number,x2:number,y2:number,x3?:number,y3?:number):number;
export function rad(deg:number):number;
export function deg(rad:number):number;
export function sin(angle: number): number;
export function cos(angle: number): number;
export function tan(angle: number): number;
export function asin(angle: number): number;
export function acos(angle: number): number;
export function atan(angle: number): number;
export function atan2(angle: number): number;
export function len(x1: number, y1: number, x2: number, y2: number): number;
export function len2(x1: number, y1: number, x2: number, y2: number): number;
export function len(x1: number, y1: number, x2: number, y2: number): number;
export function len2(x1: number, y1: number, x2: number, y2: number): number;
export function parse(svg:string):Fragment;
export function parsePathString(pathString:string):Array<any>;
export function parsePathString(pathString:Array<string>):Array<any>;
export function parseTransformString(TString:string):Array<any>;
export function parseTransformString(TString:Array<string>):Array<any>;
export function parse(svg:string):Fragment;
export function parsePathString(pathString:string):Array<any>;
export function parsePathString(pathString:Array<string>):Array<any>;
export function parseTransformString(TString:string):Array<any>;
export function parseTransformString(TString:Array<string>):Array<any>;
export function closest(x: number, y: number, X: number, Y: number): boolean;
export function closest(x: number, y: number, X: number, Y: number): boolean;
export interface RGB {
r:number;
g:number;
b:number;
hex:string;
}
export interface RGB {
r:number;
g:number;
b:number;
hex:string;
}
export interface HSB {
h:number;
s:number;
b:number;
}
export interface HSB {
h:number;
s:number;
b:number;
}
export interface RGBHSB {
r:number;
g:number;
b:number;
hex:string;
error:boolean;
h:number;
s:number;
v:number;
l:number;
}
export interface RGBHSB {
r:number;
g:number;
b:number;
hex:string;
error:boolean;
h:number;
s:number;
v:number;
l:number;
}
export interface HSL {
h:number;
s:number;
l:number;
}
export interface HSL {
h:number;
s:number;
l:number;
}
export interface BBox {
cx:number;
cy:number;
h:number;
height:number;
path:number;
r0:number;
r1:number;
r2:number;
vb:string;
w:number;
width:number;
x2:number;
x:number;
y2:number;
y:number;
}
export interface BBox {
cx:number;
cy:number;
h:number;
height:number;
path:number;
r0:number;
r1:number;
r2:number;
vb:string;
w:number;
width:number;
x2:number;
x:number;
y2:number;
y:number;
}
export interface TransformationDescriptor {
export interface TransformationDescriptor {
string: string;
globalMatrix: Snap.Matrix;
localMatrix: Snap.Matrix;
@@ -168,61 +169,61 @@ declare module Snap {
toString(): string;
}
export interface Animation {
attr:{[attr:string]:string|number|boolean|any};
duration:number;
easing?:(num:number)=>number;
callback?:()=>void;
}
export interface Animation {
attr:{[attr:string]:string|number|boolean|any};
duration:number;
easing?:(num:number)=>number;
callback?:()=>void;
}
export interface Element {
add(el:Snap.Element):Snap.Element;
addClass(value:string):Snap.Element;
after(el:Snap.Element):Snap.Element;
align(el: Snap.Element, way: string):Snap.Element;
animate(animation:any):Snap.Element;
animate(attrs:{[attr:string]:string|number|boolean|any},duration:number,easing?:(num: number)=> number,callback?:()=>void):Snap.Element;
append(el:Snap.Element):Snap.Element;
appendTo(el:Snap.Element):Snap.Element;
asPX(attr:string,value?:string):number; //TODO: check what is really returned
attr(param:string):string;
attr(params:{[attr:string]:string|number|boolean|any}):Snap.Element;
before(el:Snap.Element):Snap.Element;
children(): Snap.Element[];
clone():Snap.Element;
data(key:string,value?:any):any;
getAlign(el: Snap.Element, way: string): string;
getBBox():BBox;
getPointAtLength(length:number):{x:number, y:number, alpha:number};
getSubpath(from:number,to:number):string;
getTotalLength():number;
hasClass(value:string):boolean;
inAnim(): { anim: Animation; mina: mina.AnimationDescriptor; curStatus: number; status: (n?: number) => number; stop: () => void }[];
innerSVG():string;
insertAfter(el:Snap.Element):Snap.Element;
insertBefore(el:Snap.Element):Snap.Element;
marker(x:number,y:number,width:number,height:number,refX:number,refY:number):Snap.Element;
node:HTMLElement;
outerSVG():string;
parent():Snap.Element;
pattern(x:any,y:any,width:any,height:any):Snap.Element;
prepend(el:Snap.Element):Snap.Element;
prependTo(el:Snap.Element):Snap.Element;
remove():Snap.Element;
removeClass(value:string):Snap.Element;
removeData(key?:string):Snap.Element;
select(query:string):Snap.Element;
stop():Snap.Element;
toDefs():Snap.Element;
toJSON(): any;
toggleClass(value:string,flag:boolean):Snap.Element;
toPattern(x:number,y:number,width:number,height:number):Object;
toPattern(x:string,y:string,width:string,height:string):Object;
toString():string;
transform(): TransformationDescriptor;
transform(tstr:string):Snap.Element;
type:string;
use():Object;
export interface Element {
add(el:Snap.Element):Snap.Element;
addClass(value:string):Snap.Element;
after(el:Snap.Element):Snap.Element;
align(el: Snap.Element, way: string):Snap.Element;
animate(animation:any):Snap.Element;
animate(attrs:{[attr:string]:string|number|boolean|any},duration:number,easing?:(num: number)=> number,callback?:()=>void):Snap.Element;
append(el:Snap.Element):Snap.Element;
appendTo(el:Snap.Element):Snap.Element;
asPX(attr:string,value?:string):number; //TODO: check what is really returned
attr(param:string):string;
attr(params:{[attr:string]:string|number|boolean|any}):Snap.Element;
before(el:Snap.Element):Snap.Element;
children(): Snap.Element[];
clone():Snap.Element;
data(key:string,value?:any):any;
getAlign(el: Snap.Element, way: string): string;
getBBox():BBox;
getPointAtLength(length:number):{x:number, y:number, alpha:number};
getSubpath(from:number,to:number):string;
getTotalLength():number;
hasClass(value:string):boolean;
inAnim(): { anim: Animation; mina: mina.AnimationDescriptor; curStatus: number; status: (n?: number) => number; stop: () => void }[];
innerSVG():string;
insertAfter(el:Snap.Element):Snap.Element;
insertBefore(el:Snap.Element):Snap.Element;
marker(x:number,y:number,width:number,height:number,refX:number,refY:number):Snap.Element;
node:HTMLElement;
outerSVG():string;
parent():Snap.Element;
pattern(x:any,y:any,width:any,height:any):Snap.Element;
prepend(el:Snap.Element):Snap.Element;
prependTo(el:Snap.Element):Snap.Element;
remove():Snap.Element;
removeClass(value:string):Snap.Element;
removeData(key?:string):Snap.Element;
select(query:string):Snap.Element;
stop():Snap.Element;
toDefs():Snap.Element;
toJSON(): any;
toggleClass(value:string,flag:boolean):Snap.Element;
toPattern(x:number,y:number,width:number,height:number):Object;
toPattern(x:string,y:string,width:string,height:string):Object;
toString():string;
transform(): TransformationDescriptor;
transform(tstr:string):Snap.Element;
type:string;
use():Object;
selectAll(): Snap.Set;
selectAll(query: string): Snap.Set;
@@ -254,7 +255,7 @@ declare module Snap {
hover(hoverInHandler: (event: MouseEvent) => void, hoverOutHandler: (event: MouseEvent) => void, inThisArg?: any, outThisArg?: any): Snap.Element;
unhover(hoverInHandler: (event: MouseEvent) => void, hoverOutHandler: (event: MouseEvent) => void): Snap.Element;
drag():Snap.Element;
drag():Snap.Element;
drag(onMove: (dx: number, dy: number, x: number, y: number, event: MouseEvent) => void,
onStart: (x: number, y: number, event: MouseEvent) => void,
onEnd: (event: MouseEvent) => void,
@@ -265,33 +266,32 @@ declare module Snap {
undrag(onMove: (dx: number, dy: number, event: MouseEvent) => void,
onStart: (x: number, y: number, event: MouseEvent) => void,
onEnd: (event: MouseEvent) => void): Snap.Element;
undrag(): Snap.Element;
}
undrag(): Snap.Element;
}
export interface Fragment {
//TODO: The documentation says that selectAll returns a set, but the getting started guide
// uses .attr on the returned object. That's not supported by a set
select(query:string):Snap.Element;
selectAll(query ?:string):Snap.Set;
}
export interface Fragment {
//TODO: The documentation says that selectAll returns a set, but the getting started guide
// uses .attr on the returned object. That's not supported by a set
select(query:string):Snap.Element;
selectAll(query ?:string):Snap.Set;
}
export interface Matrix {
add(a:number,b:number,c:number,d:number,e:number,f:number):Matrix;
add(matrix:Matrix):Matrix;
clone():Matrix;
determinant():number;
invert():Matrix;
rotate(a:number,x?:number,y?:number):Matrix;
scale(x:number,y?:number,cx?:number,cy?:number):Matrix;
split():ExplicitTransform;
toTransformString():string;
translate(x:number,y:number):Matrix;
x(x:number,y:number):number;
y(x:number,y:number):number;
export interface Matrix {
add(a:number,b:number,c:number,d:number,e:number,f:number):Matrix;
add(matrix:Matrix):Matrix;
clone():Matrix;
determinant():number;
invert():Matrix;
rotate(a:number,x?:number,y?:number):Matrix;
scale(x:number,y?:number,cx?:number,cy?:number):Matrix;
split():ExplicitTransform;
toTransformString():string;
translate(x:number,y:number):Matrix;
x(x:number,y:number):number;
y(x:number,y:number):number;
}
}
interface ExplicitTransform {
interface ExplicitTransform {
dx: number;
dy: number;
scalex: number;
@@ -301,94 +301,94 @@ declare module Snap {
isSimple: boolean;
}
interface Paper extends Snap.Element {
clear():void;
el(name:string, attr:Object):Snap.Element;
filter(filstr:string):Snap.Element;
gradient(gradient:string):any;
g(varargs?:any):any;
group(...els:any[]):any;
mask(varargs:any):Object;
ptrn(x:number,y:number,width:number,height:number,vbx:number,vby:number,vbw:number,vbh:number):Object;
svg(x:number,y:number,width:number,height:number,vbx:number,vby:number,vbw:number,vbh:number):Object;
toDataUrl(): string;
toString():string;
use(id?:string):Object;
use(id?:Snap.Element):Object;
interface Paper extends Snap.Element {
clear():void;
el(name:string, attr:Object):Snap.Element;
filter(filstr:string):Snap.Element;
gradient(gradient:string):any;
g(varargs?:any):any;
group(...els:any[]):any;
mask(varargs:any):Object;
ptrn(x:number,y:number,width:number,height:number,vbx:number,vby:number,vbw:number,vbh:number):Object;
svg(x:number,y:number,width:number,height:number,vbx:number,vby:number,vbw:number,vbh:number):Object;
toDataUrl(): string;
toString():string;
use(id?:string):Object;
use(id?:Snap.Element):Object;
circle(x:number,y:number,r:number):Snap.Element;
ellipse(x:number,y:number,rx:number,ry:number):Snap.Element;
image(src:string,x:number,y:number,width:number,height:number):Snap.Element;
line(x1:number,y1:number,x2:number,y2:number):Snap.Element;
path(pathString?:string):Snap.Element;
polygon(varargs:any[]):Snap.Element;
polyline(varargs:any[]):Snap.Element;
rect(x:number,y:number,width:number,height:number,rx?:number,ry?:number):Snap.Element;
text(x:number,y:number,text:string|number):Snap.Element;
text(x:number,y:number,text:Array<string|number>):Snap.Element;
}
circle(x:number,y:number,r:number):Snap.Element;
ellipse(x:number,y:number,rx:number,ry:number):Snap.Element;
image(src:string,x:number,y:number,width:number,height:number):Snap.Element;
line(x1:number,y1:number,x2:number,y2:number):Snap.Element;
path(pathString?:string):Snap.Element;
polygon(varargs:any[]):Snap.Element;
polyline(varargs:any[]):Snap.Element;
rect(x:number,y:number,width:number,height:number,rx?:number,ry?:number):Snap.Element;
text(x:number,y:number,text:string|number):Snap.Element;
text(x:number,y:number,text:Array<string|number>):Snap.Element;
}
export interface Set {
animate(attrs:{[attr:string]:string|number|boolean|any},duration:number,easing?:(num:number)=>number,callback?:()=>void):Snap.Element;
export interface Set {
animate(attrs:{[attr:string]:string|number|boolean|any},duration:number,easing?:(num:number)=>number,callback?:()=>void):Snap.Element;
animate(...params:Array<{attrs:any,duration:number,easing:(num:number)=>number,callback?:()=>void}>):Snap.Element;
attr(params: {[attr:string]:string|number|boolean|any}): Snap.Element;
attr(params: {[attr:string]:string|number|boolean|any}): Snap.Element;
attr(param: string): string;
bind(attr: string, callback: Function): Snap.Set;
bind(attr:string,element:Snap.Element):Snap.Set;
bind(attr:string,element:Snap.Element,eattr:string):Snap.Set;
clear():Snap.Set;
exclude(element:Snap.Element):boolean;
forEach(callback:Function,thisArg?:Object):Snap.Set;
pop():Snap.Element;
push(el:Snap.Element):Snap.Element;
push(els:Snap.Element[]):Snap.Element;
splice(index:number,count:number,insertion?:Object[]):Snap.Element[];
}
bind(attr:string,element:Snap.Element):Snap.Set;
bind(attr:string,element:Snap.Element,eattr:string):Snap.Set;
clear():Snap.Set;
exclude(element:Snap.Element):boolean;
forEach(callback:Function,thisArg?:Object):Snap.Set;
pop():Snap.Element;
push(el:Snap.Element):Snap.Element;
push(els:Snap.Element[]):Snap.Element;
splice(index:number,count:number,insertion?:Object[]):Snap.Element[];
}
interface Filter {
blur(x:number,y?:number):string;
brightness(amount:number):string;
contrast(amount:number):string;
grayscale(amount:number):string;
hueRotate(angle:number):string;
invert(amount:number):string;
saturate(amount:number):string;
sepia(amount:number):string;
shadow(dx: number, dy: number, blur: number, color: string, opacity: number): string;
interface Filter {
blur(x:number,y?:number):string;
brightness(amount:number):string;
contrast(amount:number):string;
grayscale(amount:number):string;
hueRotate(angle:number):string;
invert(amount:number):string;
saturate(amount:number):string;
sepia(amount:number):string;
shadow(dx: number, dy: number, blur: number, color: string, opacity: number): string;
shadow(dx: number, dy: number, color: string, opacity: number): string;
shadow(dx: number, dy: number, opacity: number): string;
}
}
interface Path {
bezierBBox(...args:number[]):BBox;
bezierBBox(bez:Array<number>):BBox;
findDotsAtSegment(p1x:number,p1y:number,c1x:number,
c1y:number,c2x:number,c2y:number,
p2x:number,p2y:number,t:number):Object;
getBBox(path:string):BBox;
getPointAtLength(path:string,length:number):Object;
getSubpath(path:string,from:number,to:number):string;
getTotalLength(path:string):number;
intersection(path1:string,path2:string):Array<IntersectionDot>;
isBBoxIntersect(bbox1:BBox,bbox2:BBox):boolean
isPointInside(path:string,x:number,y:number):boolean;
isPointInsideBBox(bbox:BBox,x:number,y:number):boolean;
map(path:string,matrix:Snap.Matrix):string;
map(path:string,matrix:Object):string;
toAbsolute(path:string):Array<any>;
toCubic(pathString:string):Array<any>;
toCubic(pathString:Array<string>):Array<any>;
toRelative(path:string):Array<any>;
}
interface Path {
bezierBBox(...args:number[]):BBox;
bezierBBox(bez:Array<number>):BBox;
findDotsAtSegment(p1x:number,p1y:number,c1x:number,
c1y:number,c2x:number,c2y:number,
p2x:number,p2y:number,t:number):Object;
getBBox(path:string):BBox;
getPointAtLength(path:string,length:number):Object;
getSubpath(path:string,from:number,to:number):string;
getTotalLength(path:string):number;
intersection(path1:string,path2:string):Array<IntersectionDot>;
isBBoxIntersect(bbox1:BBox,bbox2:BBox):boolean
isPointInside(path:string,x:number,y:number):boolean;
isPointInsideBBox(bbox:BBox,x:number,y:number):boolean;
map(path:string,matrix:Snap.Matrix):string;
map(path:string,matrix:Object):string;
toAbsolute(path:string):Array<any>;
toCubic(pathString:string):Array<any>;
toCubic(pathString:Array<string>):Array<any>;
toRelative(path:string):Array<any>;
}
interface IntersectionDot{
x:number,
y:number,
t1:number,
t2:number,
segment1:number,
segment2:number,
bez1:Array<number>,
bez2:Array<number>
}
interface IntersectionDot{
x:number,
y:number,
t1:number,
t2:number,
segment1:number,
segment2:number,
bez1:Array<number>,
bez2:Array<number>
}
}
+1
View File
@@ -14,6 +14,7 @@ declare module THREE {
update():void;
detach(): void;
attach(object: Object3D): void;
getMode(): string;
setMode(mode: string): void;
setSnap(snap: any): void;
setSize(size:number):void;
+2
View File
@@ -2971,6 +2971,8 @@ declare module THREE {
}
export class Euler {
static DefaultOrder: string;
constructor(x?: number, y?: number, z?: number, order?: string);
x: number;
+137 -55
View File
@@ -1,108 +1,190 @@
/// <reference path="./validator.d.ts" />
/// <reference path='./validator.d.ts' />
import validator = require("validator");
import * as validator from 'validator';
let any: any;
validator.extend("isTest", function(str) {
return !str;
});
/**************
* Validators *
**************/
validator.equals("abc", "Abc");
{
let result: boolean;
validator.contains("foo", "foobar");
result = validator.contains('sample', 'sample');
validator.matches("foobar", "foo/i");
result = validator.equals('sample', 'sample');
validator.isEmail("sample");
result = validator.isAfter('sample');
result = validator.isAfter('sample', new Date());
validator.isURL("sample");
result = validator.isAlpha('sample');
validator.isFQDN("sample");
result = validator.isAlphanumeric('sample');
validator.isMACAddress("sample");
result = validator.isAscii('sample');
validator.isIP("sample");
result = validator.isBase64('sample');
validator.isAlpha("sample");
result = validator.isBefore('sample');
result = validator.isBefore('sample', new Date());
validator.isNumeric("sample");
result = validator.isBoolean('sample');
validator.isAlphanumeric("sample");
let isByteLengthOptions: ValidatorJS.IsByteLengthOptions;
result = validator.isByteLength('sample', isByteLengthOptions);
result = validator.isByteLength('sample', 0);
result = validator.isByteLength('sample', 0, 42);
validator.isBase64("sample");
result = validator.isCreditCard('sample');
validator.isHexadecimal("sample");
let isCurrencyOptions: ValidatorJS.IsCurrencyOptions;
result = validator.isCurrency('sample');
result = validator.isCurrency('sample', isCurrencyOptions);
validator.isHexColor("sample");
result = validator.isDate('sample');
validator.isLowercase("sample");
result = validator.isDecimal('sample');
validator.isUppercase("sample");
result = validator.isDivisibleBy('sample', 2);
validator.isInt("sample");
let isEmailOptions: ValidatorJS.IsEmailOptions;
result = validator.isEmail('sample');
result = validator.isEmail('sample', isEmailOptions);
validator.isFloat("sample");
let isFQDNOptions: ValidatorJS.IsFQDNOptions;
result = validator.isFQDN('sample');
result = validator.isFQDN('sample', isFQDNOptions);
validator.isDivisibleBy("sample", 2);
let isFloatOptions: ValidatorJS.IsFloatOptions;
result = validator.isFloat('sample');
result = validator.isFloat('sample', isFloatOptions);
validator.isNull("sample");
result = validator.isFullWidth('sample');
validator.isLength("sample", 3, 5);
result = validator.isHalfWidth('sample');
validator.isByteLength("sample", 3);
result = validator.isHexColor('sample');
validator.isUUID("sample");
result = validator.isHexadecimal('sample');
validator.isDate("sample");
result = validator.isIP('sample');
result = validator.isIP('sample', 6);
validator.isAfter("sample");
result = validator.isISBN('sample');
result = validator.isISBN('sample', 13);
validator.isBefore("sample");
result = validator.isISIN('sample');
validator.isIn("sample", []);
result = validator.isISO8601('sample');
validator.isCreditCard("sample");
result = validator.isIn('sample', []);
validator.isISBN("sample");
let isIntOptions: ValidatorJS.IsIntOptions;
result = validator.isInt('sample');
result = validator.isInt('sample', isIntOptions);
validator.isJSON("sample");
result = validator.isJSON('sample');
validator.isMultibyte("sample");
let isLengthOptions: ValidatorJS.IsLengthOptions;
result = validator.isLength('sample', isLengthOptions);
result = validator.isLength('sample', 3);
result = validator.isLength('sample', 3, 5);
validator.isAscii("sample");
result = validator.isLowercase('sample');
validator.isFullWidth("sample");
result = validator.isMACAddress('sample');
validator.isHalfWidth("sample");
result = validator.isMobilePhone('sample', 'en-US');
validator.isVariableWidth("sample");
result = validator.isMongoId('sample');
validator.isSurrogatePair("sample");
result = validator.isMultibyte('sample');
validator.isMongoId("sample");
result = validator.isNull('sample');
validator.toString(123);
result = validator.isNumeric('sample');
validator.toDate(1225);
result = validator.isSurrogatePair('sample');
validator.toFloat('011');
let isURLOptions: ValidatorJS.IsURLOptions;
result = validator.isURL('sample');
result = validator.isURL('sample', isURLOptions);
validator.toInt('aa');
result = validator.isUUID('sample');
result = validator.isUUID('sample', 5);
validator.toBoolean('yes!');
result = validator.isUppercase('sample');
validator.trim(' triming ');
result = validator.isVariableWidth('sample');
validator.ltrim(' triming ');
result = validator.isWhitelisted('sample', 'abc');
result = validator.isWhitelisted('sample', ['a', 'b', 'c']);
validator.rtrim(' triming ');
result = validator.matches('foobar', 'foo/i');
result = validator.matches('foobar', 'foo', 'i');
}
validator.escape('<script>');
/**************
* Sanitizers *
**************/
validator.stripLow('\x7Ffoo\x02');
{
let result: string;
validator.whitelist('ab', 'abcdef');
result = validator.blacklist('sample', 'abc');
validator.blacklist('abc', 'abcdef');
result = validator.escape('sample');
validator.normalizeEmail('!');
result = validator.ltrim('sample');
result = validator.ltrim('sample', ' ');
let normalizeEmailOptions: ValidatorJS.NormalizeEmailOptions;
result = validator.normalizeEmail('sample');
result = validator.normalizeEmail('sample', normalizeEmailOptions);
result = validator.rtrim('sample');
result = validator.rtrim('sample', ' ');
result = validator.stripLow('sample');
result = validator.stripLow('sample', true);
}
{
let result: boolean;
result = validator.toBoolean(any);
result = validator.toBoolean(any, true);
}
{
let result: Date;
result = validator.toDate(any);
}
{
let result: number;
result = validator.toFloat(any);
result = validator.toInt(any);
result = validator.toInt(any, 10);
}
{
let result: string;
result = validator.toString(any);
result = validator.trim('sample');
result = validator.trim('sample', ' ');
result = validator.whitelist('sample', 'abc');
}
/**************
* Extensions *
**************/
validator.extend<(str: string, options: {}) => boolean>('isTest', (str: any, options: {}) => !str);
+229 -130
View File
@@ -1,193 +1,292 @@
// Type definitions for validator.js v3.22.1
// Type definitions for validator.js v4.5.1
// Project: https://github.com/chriso/validator.js
// Definitions by: tgfjt <https://github.com/tgfjt>
// Definitions by: tgfjt <https://github.com/tgfjt>, Ilya Mochalov <https://github.com/chrootsu>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// options for #isURL
interface IURLoptions {
protocols?: string[]
require_tld?: boolean
require_protocol?: boolean
allow_underscores?: boolean
}
declare namespace ValidatorJS {
interface ValidatorStatic {
// options for isFQDN
interface IFQDNoptions {
require_tld?: boolean
allow_underscores?: boolean
}
/**************
* Validators *
**************/
// options for normalizeEmail
interface IEmailoptions {
lowercase?: boolean
}
// check if the string contains the seed.
contains(str: string, elem: any): boolean;
// callback type for #extend
interface IExtendCallback {
(argv: string): any
}
// check if the string matches the comparison.
equals(str: string, comparison: any): boolean;
// return function for #extend
interface IExtendFunc {
(argv: string): boolean
}
// check if the string is a date that's after the specified date (defaults to now).
isAfter(str: string, date?: Date): boolean;
interface IValidatorStatic {
// add your own validators
extend(name: string, fn: IExtendCallback): IExtendFunc;
// check if the string contains only letters (a-zA-Z).
isAlpha(str: string): boolean;
// check if the string matches the comparison.
equals(str: string, comparison: any): boolean;
// check if the string contains only letters and numbers.
isAlphanumeric(str: string): boolean;
// check if the string contains the seed.
contains(str: string, elem: any): boolean;
// check if the string contains ASCII chars only.
isAscii(str: string): boolean;
// check if string matches the pattern.
matches(str: string, pattern: any, modifiers?: string): boolean;
// check if a string is base64 encoded.
isBase64(str: string): boolean;
// check if the string is an email.
isEmail(str: string): boolean;
// check if the string is a date that's before the specified date.
isBefore(str: string, date?: Date): boolean;
// check if the string is an URL.
isURL(str: string, options?: IURLoptions): boolean;
// check if a string is a boolean.
isBoolean(str: string): boolean;
// check if the string is a fully qualified domain name (e.g. domain.com).
isFQDN(str: string, options?: IFQDNoptions): boolean;
// check if the string's length (in bytes) falls in a range.
isByteLength(str: string, options: IsByteLengthOptions): boolean;
isByteLength(str: string, min: number, max?: number): boolean;
// check if the string is a MAC address.
isMACAddress(str: string): boolean;
// check if the string is a credit card.
isCreditCard(str: string): boolean;
// check if the string is an IP (version 4 or 6).
isIP(str: string, version?: number): boolean;
// check if the string is a valid currency amount.
isCurrency(str: string, options?: IsCurrencyOptions): boolean;
// check if the string contains only letters (a-zA-Z).
isAlpha(str: string): boolean;
// check if the string is a date.
isDate(str: string): boolean;
// check if the string contains only numbers.
isNumeric(str: string): boolean;
// check if the string represents a decimal number, such as 0.1, .3, 1.1, 1.00003, 4.0, etc.
isDecimal(str: string): boolean;
// check if the string contains only letters and numbers.
isAlphanumeric(str: string): boolean;
// check if the string is a number that's divisible by another.
isDivisibleBy(str: string, number: number): boolean;
// check if a string is base64 encoded.
isBase64(str: string): boolean;
// check if the string is an email.
isEmail(str: string, options?: IsEmailOptions): boolean;
// check if the string is a hexadecimal number.
isHexadecimal(str: string): boolean;
// check if the string is a fully qualified domain name (e.g. domain.com).
isFQDN(str: string, options?: IsFQDNOptions): boolean;
// check if the string is a hexadecimal color.
isHexColor(str: string): boolean;
// check if the string is a float.
isFloat(str: string, options?: IsFloatOptions): boolean;
// check if the string is lowercase.
isLowercase(str: string): boolean;
// check if the string contains any full-width chars.
isFullWidth(str: string): boolean;
// check if the string is uppercase.
isUppercase(str: string): boolean;
// check if the string contains any half-width chars.
isHalfWidth(str: string): boolean;
// check if the string is an integer.
isInt(str: string): boolean;
// check if the string is a hexadecimal color.
isHexColor(str: string): boolean;
// check if the string is a float.
isFloat(str: string): boolean;
// check if the string is a hexadecimal number.
isHexadecimal(str: string): boolean;
// check if the string is a number that's divisible by another.
isDivisibleBy(str: string, number: number): boolean;
// check if the string is an IP (version 4 or 6).
isIP(str: string, version?: number): boolean;
// check if the string is null.
isNull(str: string): boolean;
// check if the string is an ISBN (version 10 or 13).
isISBN(str: string, version?: number): boolean;
// check if the string's length falls in a range. Note: this function takes into account surrogate pairs.
isLength(str: string, min: number, max?: number): boolean;
// check if the string is an ISIN (https://en.wikipedia.org/wiki/International_Securities_Identification_Number)
// (stock/security identifier).
isISIN(str: string): boolean;
// check if the string's length (in bytes) falls in a range.
isByteLength(str: string, min: number, max?: number): boolean;
// check if the string is a valid ISO 8601 (https://en.wikipedia.org/wiki/ISO_8601) date.
isISO8601(str: string): boolean;
// check if the string is a UUID (version 3, 4 or 5).
isUUID(str: string, version?: number): boolean;
// check if the string is in a array of allowed values.
isIn(str: string, values: any[]): boolean;
// check if the string is a date.
isDate(str: string): boolean;
// check if the string is an integer.
isInt(str: string, options?: IsIntOptions): boolean;
// check if the string is a date that's after the specified date (defaults to now).
isAfter(str: string, date?: Date): boolean;
// check if the string is valid JSON (note: uses JSON.parse).
isJSON(str: string): boolean;
// check if the string is a date that's before the specified date.
isBefore(str: string, date?: Date): boolean;
// check if the string's length falls in a range.
// Note: this function takes into account surrogate pairs.
isLength(str: string, options: IsLengthOptions): boolean;
isLength(str: string, min: number, max?: number): boolean;
// check if the string is in a array of allowed values.
isIn(str: string, values: any[]): boolean;
// check if the string is lowercase.
isLowercase(str: string): boolean;
// check if the string is a credit card.
isCreditCard(str: string): boolean;
// check if the string is a MAC address.
isMACAddress(str: string): boolean;
// check if the string is an ISBN (version 10 or 13).
isISBN(str: string, version?: number): boolean;
// check if the string is a mobile phone number, (locale is one of ['zh-CN', 'zh-TW', 'en-ZA', 'en-AU', 'en-HK',
// 'pt-PT', 'fr-FR', 'el-GR', 'en-GB', 'en-US', 'en-ZM', 'ru-RU', 'nb-NO', 'nn-NO', 'vi-VN', 'en-NZ', 'en-IN']).
isMobilePhone(str: string, locale: string): boolean;
// check if the string is valid JSON (note: uses JSON.parse).
isJSON(str: string): boolean;
// check if the string is a valid hex-encoded representation of a MongoDB ObjectId
// (http://docs.mongodb.org/manual/reference/object-id/).
isMongoId(str: string): boolean;
// check if the string contains one or more multibyte chars.
isMultibyte(str: string): boolean;
// check if the string contains one or more multibyte chars.
isMultibyte(str: string): boolean;
// check if the string contains ASCII chars only.
isAscii(str: string): boolean;
// check if the string is null.
isNull(str: string): boolean;
// check if the string contains any full-width chars.
isFullWidth(str: string): boolean;
// check if the string contains only numbers.
isNumeric(str: string): boolean;
// check if the string contains any half-width chars.
isHalfWidth(str: string): boolean;
// check if the string contains any surrogate pairs chars.
isSurrogatePair(str: string): boolean;
// check if the string contains a mixture of full and half-width chars.
isVariableWidth(str: string): boolean;
// check if the string is an URL.
isURL(str: string, options?: IsURLOptions): boolean;
// check if the string contains any surrogate pairs chars.
isSurrogatePair(str: string): boolean;
// check if the string is a UUID (version 3, 4 or 5).
isUUID(str: string, version?: number): boolean;
// check if the string is a valid hex-encoded representation of a MongoDB ObjectId.
isMongoId(str: string): boolean;
// check if the string is uppercase.
isUppercase(str: string): boolean;
// convert the input to a string.
toString(input: any): string;
// check if the string contains a mixture of full and half-width chars.
isVariableWidth(str: string): boolean;
// convert the input to a date, or null if the input is not a date.
toDate(input: any): any; // Date or null
// checks characters if they appear in the whitelist.
isWhitelisted(str: string, chars: string|string[]): boolean;
// convert the input to a float, or NaN if the input is not a float.
toFloat(input:any): number; // number or NaN
// check if string matches the pattern.
matches(str: string, pattern: any, modifiers?: string): boolean;
// convert the input to an integer, or NaN if the input is not an integer.
toInt(input:any, radix?: number): number; // number or NaN
/**************
* Sanitizers *
**************/
// convert the input to a boolean.
toBoolean(input:any, strict?: boolean): boolean;
// remove characters that appear in the blacklist. The characters are used in a RegExp and so you will need
// to escape some chars, e.g. blacklist(input, '\\[\\]').
blacklist(input: string, chars: string): string;
// trim characters (whitespace by default) from both sides of the input.
trim(input: any, chars?: string): string;
// replace <, >, &, ', " and / with HTML entities.
escape(input: string): string;
// trim characters from the left-side of the input.
ltrim(input: any, chars?: string): string;
// trim characters from the left-side of the input.
ltrim(input: any, chars?: string): string;
// trim characters from the right-side of the input.
rtrim(input: any, chars?: string): string;
// canonicalize an email address.
normalizeEmail(email: string, options?: NormalizeEmailOptions): string;
// replace <, >, &, ' and " with HTML entities.
escape(input: string): string;
// trim characters from the right-side of the input.
rtrim(input: any, chars?: string): string;
// remove characters with a numerical value < 32 and 127
stripLow(input: string, keep_new_lines?: boolean): string;
// remove characters with a numerical value < 32 and 127, mostly control characters. If keep_new_lines is true,
// newline characters are preserved (\n and \r, hex 0xA and 0xD). Unicode-safe in JavaScript.
stripLow(input: string, keep_new_lines?: boolean): string;
// remove characters that do not appear in the whitelist.
whitelist(input: string, chars: string): string;
// convert the input to a boolean. Everything except for '0', 'false' and '' returns true. In strict mode only '1'
// and 'true' return true.
toBoolean(input: any, strict?: boolean): boolean;
// remove characters that appear in the blacklist.
blacklist(input: string, chars: string): string;
// convert the input to a date, or null if the input is not a date.
toDate(input: any): Date; // Date or null
// canonicalize an email address.
normalizeEmail(email: string, options?: IEmailoptions): string;
// convert the input to a float, or NaN if the input is not a float.
toFloat(input: any): number; // number or NaN
// convert the input to an integer, or NaN if the input is not an integer.
toInt(input: any, radix?: number): number; // number or NaN
// convert the input to a string.
toString(input: any): string;
// trim characters (whitespace by default) from both sides of the input.
trim(input: any, chars?: string): string;
// remove characters that do not appear in the whitelist. The characters are used in a RegExp and so you will
// need to escape some chars, e.g. whitelist(input, '\\[\\]').
whitelist(input: string, chars: string): string;
/**************
* Extensions *
**************/
// add your own validators.
// Note: that the first argument will be automatically coerced to a string.
extend<T extends Function>(name: string, fn: T): void;
}
// options for IsByteLength
interface IsByteLengthOptions {
min?: number;
max?: number;
}
// options for IsCurrency
interface IsCurrencyOptions {
symbol?: string;
require_symbol?: boolean;
allow_space_after_symbol?: boolean;
symbol_after_digits?: boolean;
allow_negatives?: boolean;
parens_for_negatives?: boolean;
negative_sign_before_digits?: boolean;
negative_sign_after_digits?: boolean;
allow_negative_sign_placeholder?: boolean;
thousands_separator?: string;
decimal_separator?: string;
allow_space_after_digits?: boolean;
}
// options for isEmail
interface IsEmailOptions {
allow_display_name?: boolean;
allow_utf8_local_part?: boolean;
require_tld?: boolean;
}
// options for isFQDN
interface IsFQDNOptions {
require_tld?: boolean;
allow_underscores?: boolean;
allow_trailing_dot?: boolean;
}
// options for IsFloat
interface IsFloatOptions {
min?: number;
max?: number;
}
// options for IsInt
interface IsIntOptions {
min?: number;
max?: number;
}
// options for IsLength
interface IsLengthOptions {
min?: number;
max?: number;
}
// options for isURL
interface IsURLOptions {
protocols?: string[];
require_tld?: boolean;
require_protocol?: boolean;
require_valid_protocol?: boolean;
allow_underscores?: boolean;
host_whitelist?: boolean;
host_blacklist?: boolean;
allow_trailing_dot?: boolean;
allow_protocol_relative_urls?: boolean;
}
// options for normalizeEmail
interface NormalizeEmailOptions {
lowercase?: boolean;
remove_dots?: boolean;
remove_extension?: boolean;
}
}
declare module "validator" {
var validator: IValidatorStatic;
let validator: ValidatorJS.ValidatorStatic;
namespace validator {}
export = validator;
}
// deprecated interfaces for backward compatibility, please use ValidatorJS.* instead the ones
interface IValidatorStatic extends ValidatorJS.ValidatorStatic {}
interface IURLoptions extends ValidatorJS.IsURLOptions {}
interface IFQDNoptions extends ValidatorJS.IsFQDNOptions {}
interface IEmailoptions extends ValidatorJS.NormalizeEmailOptions {}
+54
View File
@@ -413,3 +413,57 @@ plugin = new webpack.ExtendedAPIPlugin();
plugin = new webpack.NoErrorsPlugin();
plugin = new webpack.WatchIgnorePlugin(paths);
//
// http://webpack.github.io/docs/node.js-api.html
//
// returns a Compiler instance
webpack({
// configuration
}, function(err, stats) {
// ...
});
// returns a Compiler instance
var compiler = webpack({
// configuration
});
compiler.run(function(err, stats) {
// ...
});
// or
compiler.watch({ // watch options:
aggregateTimeout: 300, // wait so long for more changes
poll: true // use polling instead of native watchers
// pass a number to set the polling interval
}, function(err, stats) {
// ...
});
declare function handleFatalError(err: Error): void;
declare function handleSoftErrors(errs: string[]): void;
declare function handleWarnings(errs: string[]): void;
declare function successfullyCompiled(): void;
webpack({
// configuration
}, function(err, stats) {
if(err)
return handleFatalError(err);
var jsonStats = stats.toJson();
if(jsonStats.errors.length > 0)
return handleSoftErrors(jsonStats.errors);
if(jsonStats.warnings.length > 0)
handleWarnings(jsonStats.warnings);
successfullyCompiled();
});
declare var fs: any;
compiler = webpack({ });
compiler.outputFileSystem = fs;
compiler.run(function(err, stats) {
// ...
var fileContent = fs.readFileSync("...");
});
+83
View File
@@ -234,6 +234,7 @@ declare module "webpack" {
interface Plugin { }
interface Webpack {
(config: Configuration, callback?: compiler.CompilerCallback): compiler.Compiler;
/**
* optimize namespace
*/
@@ -446,6 +447,88 @@ declare module "webpack" {
new(): Plugin;
}
}
namespace compiler {
interface Compiler {
/** Builds the bundle(s). */
run(callback: CompilerCallback): void;
/**
* Builds the bundle(s) then starts the watcher, which rebuilds bundles whenever their source files change.
* Returns a Watching instance. Note: since this will automatically run an initial build, so you only need to run watch (and not run).
*/
watch(watchOptions: WatchOptions, handler: CompilerCallback): Watching;
//TODO: below are some of the undocumented properties. needs typings
outputFileSystem: any;
name: string;
options: Configuration;
}
interface Watching {
close(callback: () => void): void;
}
interface WatchOptions {
/** After a change the watcher waits that time (in milliseconds) for more changes. Default: 300. */
aggregateTimeout?: number;
/** The watcher uses polling instead of native watchers. true uses the default interval, a number specifies a interval in milliseconds. Default: undefined (automatic). */
poll?: number|boolean;
}
interface Stats {
/** Returns true if there were errors while compiling */
hasErrors(): boolean;
/** Returns true if there were warnings while compiling. */
hasWarnings(): boolean;
/** Return information as json object */
toJson(options?: StatsToJsonOptions): any; //TODO: type this
/** Returns a formatted string of the result. */
toString(options?: StatsToStringOptions): string;
}
interface StatsToJsonOptions {
/** context directory for request shortening */
context?: boolean;
/** add the hash of the compilation */
hash?: boolean;
/** add webpack version information */
version?: boolean;
/** add timing information */
timings?: boolean;
/** add assets information */
assets?: boolean;
/** add chunk information */
chunks?: boolean;
/** add built modules information to chunk information */
chunkModules?: boolean;
/** add built modules information */
modules?: boolean;
/** add children information */
children?: boolean;
/** add also information about cached (not built) modules */
cached?: boolean;
/** add information about the reasons why modules are included */
reasons?: boolean;
/** add the source code of modules */
source?: boolean;
/** add details to errors (like resolving log) */
errorDetails?: boolean;
/** add the origins of chunks and chunk merging info */
chunkOrigins?: boolean;
/** sort the modules by that field */
modulesSort?: string;
/** sort the chunks by that field */
chunksSort?: string;
/** sort the assets by that field */
assetsSort?: string;
}
interface StatsToStringOptions extends StatsToJsonOptions {
/** With console colors */
colors?: boolean;
}
type CompilerCallback = (err: Error, stats: Stats) => void
}
}
var webpack: webpack.Webpack;