Merge remote-tracking branch 'upstream/master'

Conflicts:
	threejs/three.d.ts
This commit is contained in:
Oren Ferrari
2014-08-11 12:40:18 -07:00
128 changed files with 9814 additions and 3276 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
language: node_js
node_js:
- 0.10
- "0.10"
notifications:
email: false
+24 -2
View File
@@ -8,11 +8,13 @@ All definitions files include a header with the author and editors, so at some p
* [Ace Cloud9 Editor](http://ace.ajax.org/) (by [Diullei Gomes](https://github.com/Diullei))
* [Add To Home Screen](http://cubiq.org/add-to-home-screen) (by [James Wilkins](http://www.codeplex.com/site/users/view/jamesnw))
* [AmCharts](http://www.amcharts.com/) (by [Covobonomo](https://github.com/covobonomo/))
* [AngularAgility](https://github.com/AngularAgility/AngularAgility) (by [Roland Zwaga](https://github.com/rolandzwaga)
* [AngularAgility](https://github.com/AngularAgility/AngularAgility) (by [Roland Zwaga](https://github.com/rolandzwaga))
* [AngularBootstrapLightbox](https://github.com/compact/angular-bootstrap-lightbox) (by [Roland Zwaga](https://github.com/rolandzwaga))
* [AngularFire](https://www.firebase.com/docs/angular/reference.html) (by [Dénes Harmath](https://github.com/thSoft))
* [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) ([wiki](https://github.com/borisyankov/DefinitelyTyped/wiki/AngularJS-Definitions-Usage-Notes))
* [angularLocalStorage](https://github.com/agrublev/angularLocalStorage) (by [Hiroki Horiuchi](https://github.com/horiuchi/))
* [AngularUI](http://angular-ui.github.io/) (by [Michel Salib](https://github.com/michelsalib))
* [Angular Hotkeys](https://github.com/chieffancypants/angular-hotkeys/) (by [Jason Zhao](https://github.com/jlz27))
* [Angular Protractor](https://github.com/angular/protractor) (by [Bill Armstrong](https://github.com/BillArmstrong))
* [Angular Translate](http://pascalprecht.github.io/angular-translate/) (by [Michel Salib](https://github.com/michelsalib))
* [Angular UI Bootstrap](http://angular-ui.github.io/bootstrap) (by [Brian Surowiec](https://github.com/xt0rted))
@@ -29,6 +31,7 @@ All definitions files include a header with the author and editors, so at some p
* [Backbone.js](http://backbonejs.org/) (by [Boris Yankov](https://github.com/borisyankov))
* [Backbone Relational](http://backbonerelational.org/) (by [Eirik Hoem](https://github.com/eirikhm))
* [big.js](https://github.com/MikeMcl/big.js) (by [Steve Ognibene](https://github.com/nycdotnet))
* [BigInt](https://github.com/Evgenus/BigInt) (by [Eugene Chernyshov](https://github.com/Evgenus))
* [BigInteger](https://github.com/peterolson/BigInteger.js) (by [Ingo Bürk](https://github.com/Airblader))
* [BigScreen](http://brad.is/coding/BigScreen/) (by [Douglas Eichelberger](https://github.com/dduugg))
* [Bluebird](https://github.com/petkaantonov/bluebird) (by [Bart van der Schoor](https://github.com/Bartvds))
@@ -39,6 +42,7 @@ All definitions files include a header with the author and editors, so at some p
* [Box2DWeb](http://code.google.com/p/box2dweb/) (by [Josh Baldwin](https://github.com/jbaldwin/))
* [Breeze](http://www.breezejs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Browser Harness](https://github.com/scriby/browser-harness) (by [Chris Scribner](https://github.com/scriby))
* [bucks](https://github.com/CyberAgent/bucks.js) (by [Shunsuke Ohtani](https://github.com/zaneli))
* [CasperJS](http://casperjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker))
* [Cheerio](https://github.com/MatthewMueller/cheerio) (by [Bret Little](https://github.com/blittle))
* [Chosen](http://harvesthq.github.com/chosen/) (by [Boris Yankov](https://github.com/borisyankov))
@@ -80,6 +84,7 @@ All definitions files include a header with the author and editors, so at some p
* [File API: Directories and System](http://www.w3.org/TR/file-system-api/) (by [Kon](http://phyzkit.net/))
* [File API: Writer](http://www.w3.org/TR/file-writer-api/) (by [Kon](http://phyzkit.net/))
* [Finch](https://github.com/stoodder/finchjs) (by [David Sichau](https://github.com/DavidSichau/))
* [fingerprintjs](https://github.com/Valve/fingerprintjs) (by [Shunsuke Ohtani](https://github.com/zaneli))
* [Finite State Machine](https://github.com/jakesgordon/javascript-state-machine) (by [Boris Yankov](https://github.com/borisyankov))
* [Firebase](https://www.firebase.com/docs/javascript/firebase) (by [Vincent Bortone](https://github.com/vbortone))
* [Firefox](https://developer.mozilla.org/en-US/docs/Web/API) (by [vvakame](https://github.com/vvakame))
@@ -111,6 +116,7 @@ All definitions files include a header with the author and editors, so at some p
* [Google Url Shortener](https://developers.google.com/url-shortener/) (by [Frank M](https://github.com/sgtfrankieboy))
* [Hammer.js](http://eightmedia.github.com/hammer.js/) (by [Boris Yankov](https://github.com/borisyankov))
* [Handlebars](http://handlebarsjs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [HashMap](https://github.com/flesler/hashmap) (by [Rafał Wrzeszcz](https://wrzasq.pl))
* [HashSet](http://www.timdown.co.uk/jshashtable/jshashset.html) (by [Sergey Gerasimov](https://github.com/gerich-home))
* [Hashtable](http://www.timdown.co.uk/jshashtable/) (by [Sergey Gerasimov](https://github.com/gerich-home))
* [HelloJS](http://adodson.com/hello.js) (by [Pavel Zika](https://github.com/PavelPZ))
@@ -119,17 +125,21 @@ All definitions files include a header with the author and editors, so at some p
* [highlight.js](https://github.com/isagalaev/highlight.js) (by [Niklas Mollenhauer](https://github.com/nikeee))
* [History.js](https://github.com/browserstate/history.js) (by [Boris Yankov](https://github.com/borisyankov))
* [Html2Canvas.js](https://github.com/niklasvh/html2canvas/) (by [Richard Hepburn](https://github.com/rwhepburn))
* [htmlparser2](https://github.com/fb55/htmlparser2/) (by [James Roland Cabresos](https://github.com/staticfunction))
* [http-string-parser](https://github.com/apiaryio/http-string-parser) (by [MIZUNE Pine](https://github.com/pine613))
* [Humane.js](http://wavded.github.com/humane-js/) (by [John Vrbanac](https://github.com/jmvrbanac))
* [i18next](http://i18next.com/) (by [Maarten Docter](https://github.com/mdocter))
* [iCheck](http://damirfoy.com/iCheck/) (by [Dániel Tar](https://github.com/qcz))
* [Impress.js](https://github.com/bartaz/impress.js) (by [Boris Yankov](https://github.com/borisyankov))
* [Imagemagick](http://github.com/rsms/node-imagemagick) (by [Carlos Ballesteros Velasco](https://github.com/soywiz))
* [interact.js](http://github.com/taye/interact.js) (by [Douglas Eichelberger](https://github.com/dduugg))
* [Ion.RangeSlider](https://github.com/IonDen/ion.rangeSlider) (by [Douglas Eichelberger](https://github.com/dduugg))
* [Ionic-Cordova](https://github.com/driftyco/) (by [Hendrik Maus](https://github.com/hendrikmaus))
* [iScroll](http://cubiq.org/iscroll-4) (by [Boris Yankov](https://github.com/borisyankov) and [Christiaan Rakowski](https://github.com/csrakowski))
* [IxJS (Interactive extensions)](https://github.com/Reactive-Extensions/IxJS) (by [Igor Oleinikov](https://github.com/Igorbek))
* [jake](https://github.com/mde/jake) (by [Kon](http://phyzkit.net/))
* [Jasmine](http://pivotal.github.com/jasmine/) (by [Boris Yankov](https://github.com/borisyankov))
* [Jasmine-data_driven_tests](https://github.com/gburghardt/jasmine-data_driven_tests) (by [Anthony MacKinnon](https://github.com/AnthonyMacKinnon))
* [Jasmine-jQuery](https://github.com/velesin/jasmine-jquery) (by [Gregor Stamac](https://github.com/gstamac))
* [jDataView](https://github.com/jDataView/jDataView) (by [Ingvar Stepanyan](https://github.com/RReverser))
* [JointJS](http://www.jointjs.com/) (by [Aidan Reel](http://github.com/areel))
@@ -187,6 +197,7 @@ All definitions files include a header with the author and editors, so at some p
* [js-git](https://github.com/creationix/js-git) (by [Bart van der Schoor](https://github.com/Bartvds))
* [js-url](https://github.com/websanova/js-url) (by [MIZUNE Pine](https://github.com/pine613))
* [js-yaml](https://github.com/nodeca/js-yaml) (by [Bart van der Schoor](https://github.com/Bartvds/))
* [jsbn](http://www-cs-students.stanford.edu/%7Etjw/jsbn/) (by [Eugene Chernyshov](https://github.com/Evgenus))
* [jScrollPane](http://jscrollpane.kelvinluck.com) (by [Dániel Tar](https://github.com/qcz))
* [JSDeferred](http://cho45.stfuawsc.com/jsdeferred/) (by [Daisuke Mino](https://github.com/minodisk))
* [JSONEditorOnline](https://github.com/josdejong/jsoneditoronline) (by [Vincent Bortone](https://github.com/vbortone/))
@@ -238,15 +249,19 @@ All definitions files include a header with the author and editors, so at some p
* [Moment.js](https://github.com/timrwood/moment) (by [Michael Lakerveld](https://github.com/Lakerfield))
* [MongoDB](http://mongodb.github.io/node-mongodb-native/) (from TypeScript samples, updated by [Niklas Mollenhauer](https://github.com/nikeee))
* [mongoose](http://mongoosejs.com/) (by [Hiroki Horiuchi](https://github.com/horiuchi/))
* [morgan](https://github.com/expressjs/morgan/) (by [James Roland Cabresos](https://github.com/staticfunction/))
* [Mousetrap](http://craig.is/killing/mice) (by [Dániel Tar](https://github.com/qcz))
* [msgpack.js](https://github.com/uupaa/msgpack.js) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki))
* [Mustache.js](https://github.com/janl/mustache.js) (by [Boris Yankov](https://github.com/borisyankov))
* [mysql](https://github.com/felixge/node-mysql) (by [William Johnston](https://github.com/wjohnsto))
* [nconf](https://github.com/flatiron/nconf) (by [Jeff Goddard](https://github.com/jedigo))
* [needle](https://github.com/tomas/needle) (by [San Chen](https://github.com/bigsan))
* [noble](https://github.com/sandeepmistry/noble) (by [Seon-Wook Park](https://github.com/swook))
* [nock](https://github.com/pgte/nock) (by [bonnici](https://github.com/bonnici))
* [Node.js](http://nodejs.org/) (from TypeScript samples)
* [node_redis](https://github.com/mranney/node_redis) (by [Boris Yankov](https://github.com/borisyankov))
* [node-ffi](https://github.com/rbranson/node-ffi) (by [Paul Loyd](https://github.com/loyd))
* [node-form](https://github.com/rsamec/form) (by [Roman Samec](https://github.com/rsamec))
* [node-git](https://github.com/christkv/node-git) (by [vvakame](https://github.com/vvakame))
* [nodeunit](https://github.com/caolan/nodeunit) (by [Jeff Goddard](https://github.com/jedigo))
* [node_zeromq](https://github.com/JustinTulloss/zeromq.node) (by [Dave McKeown](https://github.com/davemckeown))
@@ -255,10 +270,12 @@ All definitions files include a header with the author and editors, so at some p
* [notify.js](https://github.com/alexgibson/notify.js) (by [soundTricker](https://github.com/soundTricker))
* [NProgress](https://github.com/rstacruz/nprogress) (by [Judah Gabriel Himango](https://github.com/judahgabriel))
* [Numeral.js](https://github.com/adamwdraper/Numeral-js) (by [Vincent Bortone](https://github.com/vbortone/))
* [object-path](https://github.com/mariocasciaro/object-path) (by [Paulo Cesar](https://github.com/pocesar/))
* [ocLazyLoad](https://github.com/ocombe/ocLazyLoad) (by [Roland Zwaga](https://github.com/rolandzwaga/))
* [OpenLayers](https://github.com/openlayers/openlayers) (by [Ilya Bolkhovsky](https://github.com/bolhovsky/))
* [Optimist](https://github.com/substack/node-optimist) (by [Carlos Ballesteros Velasco](https://github.com/soywiz))
* [Passport](http://passportjs.org/) (by [Hiroki Horiuchi](https://github.com/horiuchi/))
* [passport-facebook](https://github.com/jaredhanson/passport-facebook) (by [James Roland Cabresos](https://github.com/staticfunction/))
* [passport-strategy](https://github.com/jaredhanson/passport-strategy) (by [Lior Mualem](https://github.com/liorm))
* [pathwatcher](http://atom.github.io/node-pathwatcher/) (by [vvakame](https://github.com/vvakame))
* [Parallel.js](https://github.com/adambom/parallel.js) (by [Josh Baldwin](https://github.com/jbaldwin))
@@ -273,10 +290,13 @@ All definitions files include a header with the author and editors, so at some p
* [PouchDB](http://pouchdb.com) (by [Bill Sears](https://github.com/MrBigDog2U/))
* [PreloadJS](http://www.createjs.com/#!/PreloadJS) (by [Pedro Ferreira](https://bitbucket.org/drk4))
* [ProgressJs](http://usablica.github.io/progress.js/) (by [Shunsuke Ohtani](https://github.com/zaneli))
* [promise-pool](https://github.com/vilic/promise-pool) (by [VILIC VANE](https://github.com/vilic))
* [Q](https://github.com/kriskowal/q) (by Barrie Nemetchek, Andrew Gaspar)
* [Q-io](https://github.com/kriskowal/q-io) (by [Bart van der Schoor](https://github.com/Bartvds))
* [q-retry](https://github.com/vilic/q-retry) (by [VILIC VANE](https://github.com/vilic))
* [QUnit](http://qunitjs.com/) (by [Diullei Gomes](https://github.com/Diullei))
* [Raven.js](https://github.com/getsentry/raven-js) (by [Santi Albo](https://github.com/santialbo))
* [Recaptcha.js](https://www.google.com/recaptcha) (by [Brent Jenkins](https://github.com/brentj73))
* [Rickshaw](http://code.shutterstock.com/rickshaw/) (by [Blake Niemyjski](https://github.com/niemyjski))
* [Riot.js](https://github.com/moot/riotjs) (by [vvakame](https://github.com/vvakame))
* [Restify](https://github.com/mcavage/node-restify) (by [Bret Little](https://github.com/blittle))
@@ -287,7 +307,7 @@ All definitions files include a header with the author and editors, so at some p
* [Raphael](http://raphaeljs.com/) (by [CheCoxshall](https://github.com/CheCoxshall))
* [Restangular](https://github.com/mgonto/restangular/) (by [Boris Yankov](https://github.com/borisyankov))
* [require.js](http://requirejs.org/) (by [Josh Baldwin](https://github.com/jbaldwin/))
* [rtree.js] (https://github.com/leaflet-extras/RTree) (by [Omede Firouz](https://github.com/oefirouz))
* [rtree.js](https://github.com/leaflet-extras/RTree) (by [Omede Firouz](https://github.com/oefirouz))
* [Sammy.js](http://sammyjs.org/) (by [Boris Yankov](https://github.com/borisyankov))
* [Select2](http://ivaynberg.github.com/select2/) (by [Boris Yankov](https://github.com/borisyankov))
* [Selenium WebDriverJS](https://code.google.com/p/selenium/) (by [Bill Armstrong](https://github.com/BillArmstrong))
@@ -297,6 +317,7 @@ All definitions files include a header with the author and editors, so at some p
* [SignalR](http://www.asp.net/signalr) (by [Boris Yankov](https://github.com/borisyankov))
* [simple-cw-node](https://github.com/astronaughts/simple-cw-node) (by [vvakame](https://github.com/vvakame))
* [Sinon](http://sinonjs.org/) (by [William Sears](https://github.com/mrbigdog2u))
* [sjcl](http://crypto.stanford.edu/sjcl/) (by [Eugene Chernyshov](https://github.com/Evgenus))
* [SlickGrid](https://github.com/mleibman/SlickGrid) (by [Josh Baldwin](https://github.com/jbaldwin))
* [smoothie](https://github.com/joewalnes/smoothie) (by [Mike H. Hawley](https://github.com/mikehhawley) and [Drew Noakes](https://drewnoakes.com))
* [socket.io](http://socket.io) (by [William Orr](https://github.com/worr))
@@ -317,6 +338,7 @@ All definitions files include a header with the author and editors, so at some p
* [Tags Manager](http://welldonethings.com/tags/manager) (by [Vincent Bortone](https://github.com/vbortone))
* [Teechart](http://www.steema.com) (by [Steema](http://www.steema.com))
* [text-buffer](https://github.com/atom/text-buffer) (by [vvakame](https://github.com/vvakame))
* [text-encoding](https://github.com/inexorabletash/text-encoding) (by [MIZUNE Pine](https://github.com/pine613))
* [three.js](http://mrdoob.github.com/three.js/) (by [Kon](http://phyzkit.net/))
* [TimelineJS](https://github.com/NUKnightLab/TimelineJS) (by [Roland Zwaga](https://github.com/rolandzwaga))
* [timezonecomplete](https://github.com/SpiritIT/timezonecomplete) (by [Rogier Schouten](https://github.com/rogierschouten))
+2 -2
View File
@@ -41,7 +41,7 @@ declare module aa {
[settingName: string]: any;
}
export interface IFormExtensionsProvider extends ng.auto.IProvider {
export interface IFormExtensionsProvider extends ng.IServiceProvider {
defaultLabelStrategy:string;
defaultFieldGroupStrategy:string;
defaultValMsgPlacementStrategy:string;
@@ -88,7 +88,7 @@ declare module aa {
message:string;
}
export interface INotifyConfigProvider extends ng.auto.IProvider {
export interface INotifyConfigProvider extends ng.IServiceProvider {
notifyConfigs:any;
defaultTargetContainerName:string;
defaultNotifyConfig:string;
@@ -0,0 +1,35 @@
///<reference path='angular-bootstrap-lightbox.d.ts'/>
var imageList:angular.bootstrap.lightbox.ILightboxImageInfo[] = [];
imageList.push({
url: 'url1',
width: 100,
height: 100
});
imageList.push({
url: 'url2',
width: 100,
height: 100,
thumbUrl: 'thumbUrl',
caption: 'caption'
});
var lightBox:angular.bootstrap.lightbox.ILightbox = <any> {};
lightBox.openModal(imageList, 0);
var provider:angular.bootstrap.lightbox.ILightBoxProvider = <any> {};
provider.templateUrl = 'templateUrl';
provider.calculateImageDimensionLimits = (dimensions:angular.bootstrap.lightbox.IImageDimensionParameter):angular.bootstrap.lightbox.IImageDimensionLimits=> {
return {
minWidth: 100,
minHeight: 100,
maxWidth: dimensions.windowWidth - 102,
maxHeight: dimensions.windowHeight - 136
};
};
provider.calculateModalDimensions = (dimensions:angular.bootstrap.lightbox.IModalDimensionsParameter):angular.bootstrap.lightbox.IModalDimensions=> {
return {
width: Math.max(500, dimensions.imageDisplayWidth + 42),
height: Math.max(500, dimensions.imageDisplayHeight + 76)
};
};
@@ -0,0 +1,51 @@
// Type definitions for angular-bootstrap-lightbox
// Project: https://github.com/compact/angular-bootstrap-lightbox
// Definitions by: Roland Zwaga <https://github.com/rolandzwaga>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module angular.bootstrap.lightbox {
export interface ILightboxImageInfo {
url: string;
width: number;
height: number;
thumbUrl?: string;
caption?: string;
}
export interface IImageDimensionLimits {
minWidth?: number;
minHeight?: number;
maxWidth?: number;
maxHeight?: number;
}
export interface IImageDimensionParameter {
windowWidth:number;
windowHeight:number;
imageWidth:number;
imageHeight:number;
}
export interface IModalDimensionsParameter {
windowWidth:number;
windowHeight:number;
imageDisplayWidth:number;
imageDisplayHeight:number;
}
export interface IModalDimensions {
width:number;
height:number;
}
export interface ILightbox {
openModal(images:ILightboxImageInfo[], index:number):void;
}
export interface ILightBoxProvider {
templateUrl:string;
calculateImageDimensionLimits:(dimensions:IImageDimensionParameter)=>IImageDimensionLimits;
calculateModalDimensions:(dimensions:IModalDimensionsParameter)=>IModalDimensions;
}
}
+25
View File
@@ -0,0 +1,25 @@
/// <reference path="../angularjs/angular.d.ts" />
/// <reference path="angular-hotkeys.d.ts" />
var scope: ng.IScope;
var hotkeyProvider: ng.hotkeys.HotkeysProvider;
var hotkeyObj: ng.hotkeys.Hotkey;
hotkeyProvider.add("mod+s", "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => {} );
hotkeyProvider.add(hotkeyObj);
hotkeyProvider.bindTo(scope);
hotkeyProvider.del("mod+s");
hotkeyProvider.get("mod+s");
hotkeyProvider.toggleCheatSheet();
hotkeyProvider.add(hotkeyObj.combo, hotkeyObj.description ,hotkeyObj.callback);
hotkeyProvider.bindTo(scope)
.add(hotkeyObj)
.add(hotkeyObj)
.add({
combo: 'w',
description: 'blah blah',
callback: function() {}
});
+40
View File
@@ -0,0 +1,40 @@
// Type definitions for angular-hotkeys
// Project: https://github.com/chieffancypants/angular-hotkeys
// Definitions by: Jason Zhao <https://github.com/jlz27>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module ng.hotkeys {
interface HotkeysProvider {
template: string;
includeCheatSheet: boolean;
cheatSheetHotkey: string;
cheatSheetDescription: string;
add(combo: string, description: string, callback: (event: Event, hotkeys: ng.hotkeys.Hotkey) => void): void;
add(hotkeyObj: ng.hotkeys.Hotkey): void;
bindTo(scope : ng.IScope): ng.hotkeys.HotkeysProviderChained;
del(combo: string): void;
get(combo: string): ng.hotkeys.Hotkey;
toggleCheatSheet(): void;
}
interface HotkeysProviderChained {
add(combo: string, description: string, callback: (event: Event, hotkeys: ng.hotkeys.Hotkey) => void): HotkeysProviderChained;
add(hotkeyObj: ng.hotkeys.Hotkey): HotkeysProviderChained;
}
interface Hotkey {
combo: string;
description?: string;
callback: (event: Event, hotkey: ng.hotkeys.Hotkey) => void;
}
}
+3 -2
View File
@@ -33,13 +33,14 @@ declare module ng.translate {
}
interface ITranslateService {
(key: string, ...params: string[]): ng.IPromise<string>;
(translationId: string, interpolateParams?: any, interpolationId?: string): ng.IPromise<string>;
(translationId: string[], interpolateParams?: any, interpolationId?: string): ng.IPromise<{ [key: string]: string }>;
cloakClassName(): string;
cloakClassName(name: string): ITranslateProvider;
fallbackLanguage(langKey?: string): string;
fallbackLanguage(langKey?: string[]): string;
instant(translationId: string, interpolateParams?: any, interpolationId?: string): string;
instant(translationId: string[], interpolateParams?: any, interpolationId?: string): string;
instant(translationId: string[], interpolateParams?: any, interpolationId?: string): { [key: string]: string };
isPostCompilingEnabled(): boolean;
preferredLanguage(): string;
proposedLanguage(): string;
+1 -3
View File
@@ -33,9 +33,7 @@ declare module ng {
inject(...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works
// see http://docs.angularjs.org/api/angular.mock.module
module(...modules: string[]): any;
module(...modules: Function[]): any;
module(modules: Object): any;
module(...modules: any[]): any;
// see http://docs.angularjs.org/api/angular.mock.TzDate
TzDate(offset: number, timestamp: number): Date;
+346 -28
View File
@@ -7,27 +7,27 @@
* (c) 2012 Witold Szczerba
* License: MIT
*/
angular.module('http-auth-interceptor', [])
.provider('authService', function () {
/**
* Holds all the requests which failed due to 401 response,
* so they can be re-requested in future, once login is completed.
*/
var buffer: { config: ng.IRequestConfig; deferred: ng.IDeferred<any>; }[] = [];
class AuthService {
/**
* Holds all the requests which failed due to 401 response,
* so they can be re-requested in future, once login is completed.
*/
buffer: { config: ng.IRequestConfig; deferred: ng.IDeferred<any>; }[] = [];
/**
* Required by HTTP interceptor.
* Function is attached to provider to be invisible for regular users of this service.
*/
this.pushToBuffer = function (config: ng.IRequestConfig, deferred: ng.IDeferred<any>) {
buffer.push({
config: config,
deferred: deferred
});
}
/**
* Required by HTTP interceptor.
* Function is attached to provider to be invisible for regular users of this service.
*/
pushToBuffer = function(config: ng.IRequestConfig, deferred: ng.IDeferred<any>) {
this.buffer.push({
config: config,
deferred: deferred
});
}
this.$get = ['$rootScope', '$injector', <any>function ($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) {
$get = [
'$rootScope', '$injector', <any>function($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) {
var $http: ng.IHttpService; //initialized later because of circular dependency problem
function retry(config: ng.IRequestConfig, deferred: ng.IDeferred<any>) {
$http = $http || $injector.get('$http');
@@ -36,20 +36,25 @@ angular.module('http-auth-interceptor', [])
});
}
function retryAll() {
for (var i = 0; i < buffer.length; ++i) {
retry(buffer[i].config, buffer[i].deferred);
for (var i = 0; i < this.buffer.length; ++i) {
retry(this.buffer[i].config, this.buffer[i].deferred);
}
buffer = [];
this.buffer = [];
}
return {
return {
loginConfirmed: function () {
$rootScope.$broadcast('event:auth-loginConfirmed');
retryAll();
}
}
}]
})
}
];
}
angular.module('http-auth-interceptor', [])
.provider('authService', AuthService)
/**
* $http interceptor.
@@ -95,6 +100,7 @@ module HttpAndRegularPromiseTests {
theAnswer: number;
letters: string[];
snack: string;
nothing?: string;
}
var someController: Function = ($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) => {
@@ -139,6 +145,12 @@ module HttpAndRegularPromiseTests {
dPromise.then((snack: string) => {
$scope.snack = snack;
});
// $q.when may be called without arguments
var ePromise: ng.IPromise<void> = $q.when();
ePromise.then(() => {
$scope.nothing = "really nothing";
});
}
// Test that we can pass around a type-checked success/error Promise Callback
@@ -176,7 +188,8 @@ mod.factory(My.Namespace);
mod.filter('name', function ($scope: ng.IScope) { })
mod.filter('name', ['$scope', <any>function ($scope: ng.IScope) { }])
mod.filter(My.Namespace);
mod.provider('name', function ($scope: ng.IScope) { })
mod.provider('name', function ($scope: ng.IScope) { return { $get: () => { } } })
mod.provider('name', TestProvider);
mod.provider('name', ['$scope', <any>function ($scope: ng.IScope) { }])
mod.provider(My.Namespace);
mod.service('name', function ($scope: ng.IScope) { })
@@ -189,6 +202,13 @@ mod.value('name', 23);
mod.value('name', "23");
mod.value(My.Namespace);
class TestProvider implements ng.IServiceProvider {
constructor(private $scope: ng.IScope) {
}
$get() {
}
}
// Promise signature tests
var foo: ng.IPromise<number>;
@@ -211,11 +231,11 @@ foo.then((x) => {
}).then((x) => {
// Object is inferred here
x.a = 123;
//Try a promise
//Try a promise
var y: ng.IPromise<number>;
return y;
return y;
}).then((x) => {
// x is infered to be a number, which is the resolved value of a promise
// x is infered to be a number, which is the resolved value of a promise
x.toFixed();
});
@@ -231,6 +251,15 @@ httpFoo.then((x) => {
});
function test_angular_forEach() {
var values: { [key: string]: string } = { name: 'misko', gender: 'male' };
var log: string[] = [];
angular.forEach(values, function (value, key) {
this.push(key + ': ' + value);
}, log);
//expect(log).toEqual(['name: misko', 'gender: male']);
}
// angular.element() tests
var element = angular.element("div.myApp");
var scope: ng.IScope = element.scope();
@@ -251,3 +280,292 @@ test_IAttributes({
},
$attr: {}
});
class SampleDirective implements ng.IDirective {
public restrict = 'A';
name = 'doh';
compile(templateElement: ng.IAugmentedJQuery) {
return {
post: this.link
};
}
static instance():ng.IDirective {
return new SampleDirective();
}
link(scope: ng.IScope) {
}
}
class SampleDirective2 implements ng.IDirective {
public restrict = 'EAC';
compile(templateElement: ng.IAugmentedJQuery) {
return {
pre: this.link
};
}
static instance():ng.IDirective {
return new SampleDirective2();
}
link(scope: ng.IScope) {
}
}
angular.module('SameplDirective', []).directive('sampleDirective', SampleDirective.instance).directive('sameplDirective2', SampleDirective2.instance);
// test from https://docs.angularjs.org/guide/directive
angular.module('docsSimpleDirective', [])
.controller('Controller', ['$scope', function($scope: any) {
$scope.customer = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
}])
.directive('myCustomer', function() {
return {
template: 'Name: {{customer.name}} Address: {{customer.address}}'
};
});
angular.module('docsTemplateUrlDirective', [])
.controller('Controller', ['$scope', function($scope: any) {
$scope.customer = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
}])
.directive('myCustomer', function() {
return {
templateUrl: 'my-customer.html'
};
});
angular.module('docsRestrictDirective', [])
.controller('Controller', ['$scope', function($scope: any) {
$scope.customer = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
}])
.directive('myCustomer', function() {
return {
restrict: 'E',
templateUrl: 'my-customer.html'
};
});
angular.module('docsScopeProblemExample', [])
.controller('NaomiController', ['$scope', function($scope: any) {
$scope.customer = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
}])
.controller('IgorController', ['$scope', function($scope: any) {
$scope.customer = {
name: 'Igor',
address: '123 Somewhere'
};
}])
.directive('myCustomer', function() {
return {
restrict: 'E',
templateUrl: 'my-customer.html'
};
});
angular.module('docsIsolateScopeDirective', [])
.controller('Controller', ['$scope', function($scope: any) {
$scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
$scope.igor = { name: 'Igor', address: '123 Somewhere' };
}])
.directive('myCustomer', function() {
return {
restrict: 'E',
scope: {
customerInfo: '=info'
},
templateUrl: 'my-customer-iso.html'
};
});
angular.module('docsIsolationExample', [])
.controller('Controller', ['$scope', function($scope: any) {
$scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
$scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' };
}])
.directive('myCustomer', function() {
return {
restrict: 'E',
scope: {
customerInfo: '=info'
},
templateUrl: 'my-customer-plus-vojta.html'
};
});
angular.module('docsTimeDirective', [])
.controller('Controller', ['$scope', function($scope: any) {
$scope.format = 'M/d/yy h:mm:ss a';
}])
.directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any) {
return {
link: function(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs:ng.IAttributes) {
var format: any,
timeoutId: any;
function updateTime() {
element.text(dateFilter(new Date(), format));
}
scope.$watch(attrs['myCurrentTime'], function (value: any) {
format = value;
updateTime();
});
element.on('$destroy', function () {
$interval.cancel(timeoutId);
});
// start the UI update process; save the timeoutId for canceling
timeoutId = $interval(function () {
updateTime(); // update DOM
}, 1000);
}
};
}]);
angular.module('docsTransclusionDirective', [])
.controller('Controller', ['$scope', function($scope: any) {
$scope.name = 'Tobias';
}])
.directive('myDialog', function() {
return {
restrict: 'E',
transclude: true,
templateUrl: 'my-dialog.html'
};
});
angular.module('docsTransclusionExample', [])
.controller('Controller', ['$scope', function($scope: any) {
$scope.name = 'Tobias';
}])
.directive('myDialog', function() {
return {
restrict: 'E',
transclude: true,
scope: {},
templateUrl: 'my-dialog.html',
link: function (scope: ng.IScope, element: ng.IAugmentedJQuery) {
scope['name'] = 'Jeff';
}
};
});
angular.module('docsIsoFnBindExample', [])
.controller('Controller', ['$scope', '$timeout', function($scope: any, $timeout: any) {
$scope.name = 'Tobias';
$scope.hideDialog = function () {
$scope.dialogIsHidden = true;
$timeout(function () {
$scope.dialogIsHidden = false;
}, 2000);
};
}])
.directive('myDialog', function() {
return {
restrict: 'E',
transclude: true,
scope: {
'close': '&onClose'
},
templateUrl: 'my-dialog-close.html'
};
});
angular.module('dragModule', [])
.directive('myDraggable', ['$document', function($document: any) {
return function(scope: any, element: any, attr: any) {
var startX = 0, startY = 0, x = 0, y = 0;
element.css({
position: 'relative',
border: '1px solid red',
backgroundColor: 'lightgrey',
cursor: 'pointer'
});
element.on('mousedown', function(event: any) {
// Prevent default dragging of selected content
event.preventDefault();
startX = event.pageX - x;
startY = event.pageY - y;
$document.on('mousemove', mousemove);
$document.on('mouseup', mouseup);
});
function mousemove(event: any) {
y = event.pageY - startY;
x = event.pageX - startX;
element.css({
top: y + 'px',
left: x + 'px'
});
}
function mouseup() {
$document.off('mousemove', mousemove);
$document.off('mouseup', mouseup);
}
};
}]);
angular.module('docsTabsExample', [])
.directive('myTabs', function() {
return {
restrict: 'E',
transclude: true,
scope: {},
controller: function($scope: ng.IScope) {
var panes: any = $scope['panes'] = [];
$scope['select'] = function(pane: any) {
angular.forEach(panes, function(pane: any) {
pane.selected = false;
});
pane.selected = true;
};
this.addPane = function(pane: any) {
if (panes.length === 0) {
$scope['select'](pane);
}
panes.push(pane);
};
},
templateUrl: 'my-tabs.html'
};
})
.directive('myPane', function() {
return {
require: '^myTabs',
restrict: 'E',
transclude: true,
scope: {
title: '@'
},
link: function(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, tabsCtrl: any) {
tabsCtrl.addPane(scope);
},
templateUrl: 'my-pane.html'
};
});
+137 -66
View File
@@ -18,6 +18,15 @@ interface Function {
///////////////////////////////////////////////////////////////////////////////
declare module ng {
// not directly implemented, but ensures that constructed class implements $get
interface IServiceProviderClass {
new(...args: any[]): IServiceProvider;
}
interface IServiceProviderFactory {
(...args: any[]): IServiceProvider;
}
// All service providers extend this interface
interface IServiceProvider {
$get: any;
@@ -37,7 +46,38 @@ declare module ng {
element: IAugmentedJQueryStatic;
equals(value1: any, value2: any): boolean;
extend(destination: any, ...sources: any[]): any;
/**
* Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional.
*
* It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method.
*
* @param obj Object to iterate over.
* @param iterator Iterator function.
* @param context Object to become context (this) for the iterator function.
*/
forEach<T>(obj: T[], iterator: (value: T, key: number) => any, context?: any): any;
/**
* Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional.
*
* It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method.
*
* @param obj Object to iterate over.
* @param iterator Iterator function.
* @param context Object to become context (this) for the iterator function.
*/
forEach<T>(obj: { [index: string]: T; }, iterator: (value: T, key: string) => any, context?: any): any;
/**
* Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional.
*
* It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method.
*
* @param obj Object to iterate over.
* @param iterator Iterator function.
* @param context Object to become context (this) for the iterator function.
*/
forEach(obj: any, iterator: (value: any, key: any) => any, context?: any): any;
fromJson(json: string): any;
identity(arg?: any): any;
injector(modules?: any[]): auto.IInjectorService;
@@ -56,7 +96,7 @@ declare module ng {
* The angular.module is a global place for creating, registering and retrieving Angular modules. All modules (angular core or 3rd party) that should be available to an application must be registered using this mechanism.
*
* When passed two or more arguments, a new module is created. If passed only one argument, an existing module (the name passed as the first argument to module) is retrieved.
*
*
* @param name The name of the module to create or retrieve.
* @param requires The names of modules this module depends on. If specified then new module is being created. If unspecified then the module is being retrieved for further configuration.
* @param configFn Optional configuration function for the module.
@@ -88,19 +128,19 @@ declare module ng {
animation(object: Object): IModule;
/**
* Use this method to register work which needs to be performed on module loading.
*
*
* @param configFn Execute this function on module load. Useful for service configuration.
*/
config(configFn: Function): IModule;
/**
* Use this method to register work which needs to be performed on module loading.
*
*
* @param inlineAnnotatedFunction Execute this function on module load. Useful for service configuration.
*/
config(inlineAnnotatedFunction: any[]): IModule;
/**
* Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator.
*
*
* @param name The name of the constant.
* @param value The constant value.
*/
@@ -108,36 +148,36 @@ declare module ng {
constant(object: Object): IModule;
/**
* The $controller service is used by Angular to create new controllers.
*
*
* This provider allows controller registration via the register method.
*
*
* @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors.
* @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation).
*/
controller(name: string, controllerConstructor: Function): IModule;
/**
* The $controller service is used by Angular to create new controllers.
*
*
* This provider allows controller registration via the register method.
*
*
* @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors.
* @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation).
*/
controller(name: string, inlineAnnotatedConstructor: any[]): IModule;
controller(object : Object): IModule;
directive(name: string, directiveFactory: Function): IModule;
directive(name: string, directiveFactory: IDirectiveFactory): IModule;
directive(name: string, inlineAnnotatedFunction: any[]): IModule;
directive(object: Object): IModule;
/**
* Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider.
*
*
* @param name The name of the instance.
* @param $getFn The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}).
*/
factory(name: string, $getFn: Function): IModule;
/**
* Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider.
*
*
* @param name The name of the instance.
* @param inlineAnnotatedFunction The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}).
*/
@@ -146,9 +186,10 @@ declare module ng {
filter(name: string, filterFactoryFunction: Function): IModule;
filter(name: string, inlineAnnotatedFunction: any[]): IModule;
filter(object: Object): IModule;
provider(name: string, serviceProviderConstructor: Function): IModule;
provider(name: string, serviceProviderFactory: IServiceProviderFactory): IModule;
provider(name: string, serviceProviderConstructor: IServiceProviderClass): IModule;
provider(name: string, inlineAnnotatedConstructor: any[]): IModule;
provider(name: string, providerObject: auto.IProvider): IModule;
provider(name: string, providerObject: IServiceProvider): IModule;
provider(object: Object): IModule;
/**
* Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.
@@ -211,11 +252,17 @@ declare module ng {
$attr: Object;
}
///////////////////////////////////////////////////////////////////////////
// FormController
// see http://docs.angularjs.org/api/ng.directive:form.FormController
///////////////////////////////////////////////////////////////////////////
/**
* form.FormController - type in module ng
* see https://docs.angularjs.org/api/ng/type/form.FormController
*/
interface IFormController {
/**
* Indexer which should return ng.INgModelController for most properties but cannot because of "All named properties must be assignable to string indexer type" constraint - see https://github.com/Microsoft/TypeScript/issues/272
*/
[name: string]: any;
$pristine: boolean;
$dirty: boolean;
$valid: boolean;
@@ -244,6 +291,7 @@ declare module ng {
$parsers: IModelParser[];
$formatters: IModelFormatter[];
$viewChangeListeners: IModelViewChangeListener[];
$error: any;
$pristine: boolean;
$dirty: boolean;
@@ -259,11 +307,15 @@ declare module ng {
(value: any): any;
}
interface IModelViewChangeListener {
(): void;
}
///////////////////////////////////////////////////////////////////////////
// Scope
// see http://docs.angularjs.org/api/ng.$rootScope.Scope
// Scope and RootScope
// see https://docs.angularjs.org/api/ng/type/$rootScope.Scope and http://docs.angularjs.org/api/ng.$rootScope
///////////////////////////////////////////////////////////////////////////
interface IScope {
interface IRootScopeService {
$apply(): any;
$apply(exp: string): any;
$apply(exp: (scope: IScope) => any): any;
@@ -300,6 +352,7 @@ declare module ng {
$parent: IScope;
$root: IRootScopeService;
this: IRootScopeService;
$id: string;
@@ -308,6 +361,10 @@ declare module ng {
$$phase: any;
}
interface IScope extends IRootScopeService {
[index: string]: any;
}
interface IAngularEvent {
targetScope: IScope;
currentScope: IScope;
@@ -527,17 +584,17 @@ declare module ng {
interface IQService {
/**
* Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
*
*
* Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value.
*
*
* @param promises An array or hash of promises.
*/
all(promises: IPromise<any>[]): IPromise<any[]>;
/**
* Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
*
*
* Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value.
*
*
* @param promises An array or hash of promises.
*/
all(promises: { [id: string]: IPromise<any>; }): IPromise<{ [id: string]: any }>;
@@ -547,24 +604,30 @@ declare module ng {
defer<T>(): IDeferred<T>;
/**
* Creates a promise that is resolved as rejected with the specified reason. This api should be used to forward rejection in a chain of promises. If you are dealing with the last promise in a promise chain, you don't need to worry about it.
*
*
* When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of reject as the throw keyword in JavaScript. This also means that if you "catch" an error via a promise error callback and you want to forward the error to the promise derived from the current promise, you have to "rethrow" the error by returning a rejection constructed via reject.
*
*
* @param reason Constant, message, exception or an object representing the rejection reason.
*/
reject(reason?: any): IPromise<void>;
/**
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.
*
*
* @param value Value or a promise
*/
when<T>(value: IPromise<T>): IPromise<T>;
/**
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.
*
*
* @param value Value or a promise
*/
when<T>(value: T): IPromise<T>;
/**
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.
*
* @param value Value or a promise
*/
when(): IPromise<void>;
}
interface IPromise<T> {
@@ -649,7 +712,7 @@ declare module ng {
aHrefSanitizationWhitelist(): RegExp;
aHrefSanitizationWhitelist(regexp: RegExp): ICompileProvider;
imgSrcSanitizationWhitelist(): RegExp;
imgSrcSanitizationWhitelist(regexp: RegExp): ICompileProvider;
}
@@ -689,7 +752,7 @@ declare module ng {
}
/**
* HttpService
* HttpService
* see http://docs.angularjs.org/api/ng/service/$http
*/
interface IHttpService {
@@ -700,7 +763,7 @@ declare module ng {
/**
* Shortcut method to perform GET request.
*
*
* @param url Relative or absolute URL specifying the destination of the request
* @param config Optional configuration object
*/
@@ -708,7 +771,7 @@ declare module ng {
/**
* Shortcut method to perform DELETE request.
*
*
* @param url Relative or absolute URL specifying the destination of the request
* @param config Optional configuration object
*/
@@ -716,7 +779,7 @@ declare module ng {
/**
* Shortcut method to perform HEAD request.
*
*
* @param url Relative or absolute URL specifying the destination of the request
* @param config Optional configuration object
*/
@@ -724,7 +787,7 @@ declare module ng {
/**
* Shortcut method to perform JSONP request.
*
*
* @param url Relative or absolute URL specifying the destination of the request
* @param config Optional configuration object
*/
@@ -732,7 +795,7 @@ declare module ng {
/**
* Shortcut method to perform POST request.
*
*
* @param url Relative or absolute URL specifying the destination of the request
* @param data Request content
* @param config Optional configuration object
@@ -741,7 +804,7 @@ declare module ng {
/**
* Shortcut method to perform PUT request.
*
*
* @param url Relative or absolute URL specifying the destination of the request
* @param data Request content
* @param config Optional configuration object
@@ -761,12 +824,12 @@ declare module ng {
/**
* Object describing the request to be made and how it should be processed.
* see http://docs.angularjs.org/api/ng/service/$http#usage
* see http://docs.angularjs.org/api/ng/service/$http#usage
*/
interface IRequestShortcutConfig {
/**
* {Object.<string|Object>}
* Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified.
* Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified.
*/
params?: any;
@@ -797,7 +860,7 @@ declare module ng {
withCredentials?: boolean;
/**
* {string|Object}
* {string|Object}
* Data to be sent as the request message data.
*/
data?: any;
@@ -828,7 +891,7 @@ declare module ng {
/**
* Object describing the request to be made and how it should be processed.
* see http://docs.angularjs.org/api/ng/service/$http#usage
* see http://docs.angularjs.org/api/ng/service/$http#usage
*/
interface IRequestConfig extends IRequestShortcutConfig {
/**
@@ -904,12 +967,6 @@ declare module ng {
///////////////////////////////////////////////////////////////////////////
interface ITemplateCacheService extends ICacheObject {}
///////////////////////////////////////////////////////////////////////////
// RootScopeService
// see http://docs.angularjs.org/api/ng.$rootScope
///////////////////////////////////////////////////////////////////////////
interface IRootScopeService extends IScope {}
///////////////////////////////////////////////////////////////////////////
// SCEService
// see http://docs.angularjs.org/api/ng.$sce
@@ -969,21 +1026,38 @@ declare module ng {
// and http://docs.angularjs.org/guide/directive
///////////////////////////////////////////////////////////////////////////
interface IDirective{
compile?:
(templateElement: IAugmentedJQuery,
templateAttributes: IAttributes,
transclude: ITranscludeFunction
) => any;
controller?: any;
controllerAs?: string;
link?:
(scope: IScope,
interface IDirectiveFactory {
(...args: any[]): IDirective;
}
interface IDirectiveLinkFn {
(
scope: IScope,
instanceElement: IAugmentedJQuery,
instanceAttributes: IAttributes,
controller: any,
transclude: ITranscludeFunction
) => void;
): void;
}
interface IDirectivePrePost {
pre?: IDirectiveLinkFn;
post?: IDirectiveLinkFn;
}
interface IDirectiveCompileFn {
(
templateElement: IAugmentedJQuery,
templateAttributes: IAttributes,
transclude: ITranscludeFunction
): IDirectivePrePost;
}
interface IDirective {
compile?: IDirectiveCompileFn;
controller?: any;
controllerAs?: string;
link?: IDirectiveLinkFn;
name?: string;
priority?: number;
replace?: boolean;
@@ -1047,9 +1121,6 @@ declare module ng {
// AUTO module (angular.js)
///////////////////////////////////////////////////////////////////////////
export module auto {
interface IProvider {
$get: any;
}
///////////////////////////////////////////////////////////////////////
// InjectorService
@@ -1059,7 +1130,7 @@ declare module ng {
annotate(fn: Function): string[];
annotate(inlineAnnotatedFunction: any[]): string[];
get(name: string): any;
has(name: string): boolean;
has(name: string): boolean;
instantiate(typeConstructor: Function, locals?: any): any;
invoke(inlineAnnotatedFunction: any[]): any;
invoke(func: Function, context?: any, locals?: any): any;
@@ -1075,7 +1146,7 @@ declare module ng {
// constant(name: string, value: any): any;
/**
* Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator.
*
*
* @param name The name of the constant.
* @param value The constant value.
*/
@@ -1083,19 +1154,19 @@ declare module ng {
/**
* Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service.
*
*
* @param name The name of the service to decorate.
* @param decorator This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments:
*
*
* $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to.
*/
decorator(name: string, decorator: Function): void;
/**
* Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service.
*
*
* @param name The name of the service to decorate.
* @param inlineAnnotatedFunction This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments:
*
*
* $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to.
*/
decorator(name: string, inlineAnnotatedFunction: any[]): void;
+3 -2
View File
@@ -26,10 +26,11 @@ async.map(data, asyncProcess, function (err, results) {
var openFiles = ['file1', 'file2'];
var saveFile = function () { }
async.forEach(openFiles, saveFile, function (err) { });
async.each(openFiles, saveFile, function (err) { });
async.eachSeries(openFiles, saveFile, function (err) { });
var documents, requestApi;
async.forEachLimit(documents, 20, requestApi, function (err) { });
async.eachLimit(documents, 20, requestApi, function (err) { });
async.map(['file1', 'file2', 'file3'], fs.stat, function (err, results) { });
+3 -3
View File
@@ -34,9 +34,9 @@ interface AsyncQueue<T> {
interface Async {
// Collections
forEach<T,R>(arr: T[], iterator: AsyncIterator<T, R>, callback: AsyncMultipleResultsCallback<R>): void;
forEachSeries<T, R>(arr: T[], iterator: AsyncIterator<T, R>, callback: AsyncMultipleResultsCallback<R>): void;
forEachLimit<T, R>(arr: T[], limit: number, iterator: AsyncIterator<T, R>, callback: AsyncMultipleResultsCallback<R>): void;
each<T,R>(arr: T[], iterator: AsyncIterator<T, R>, callback: AsyncMultipleResultsCallback<R>): void;
eachSeries<T, R>(arr: T[], iterator: AsyncIterator<T, R>, callback: AsyncMultipleResultsCallback<R>): void;
eachLimit<T, R>(arr: T[], limit: number, iterator: AsyncIterator<T, R>, callback: AsyncMultipleResultsCallback<R>): void;
map<T, R>(arr: T[], iterator: AsyncIterator<T, R>, callback: AsyncMultipleResultsCallback<R>): any;
mapSeries<T, R>(arr: T[], iterator: AsyncIterator<T, R>, callback: AsyncMultipleResultsCallback<R>): any;
filter<T>(arr: T[], iterator: AsyncIterator<T, boolean>, callback: AsyncMultipleResultsCallback<T>): any;
+81
View File
@@ -0,0 +1,81 @@
/// <reference path="./bigint.d.ts" />
var bi: BigInt.BigInt;
var num: number;
var str: string;
var b: boolean;
BigInt.setRandom(() => { return 0; });
bi = BigInt.add(bi, bi);
bi = BigInt.addInt(bi, num);
str = BigInt.bigInt2str(bi, num);
str = BigInt.bigInt2str(bi, str);
num = BigInt.bitSize(bi);
bi = BigInt.dup(bi);
b = BigInt.equals(bi, bi);
b = BigInt.equalsInt(bi, num);
bi = BigInt.expand(bi, num);
var nums: number[] = BigInt.findPrimes(num);
bi = BigInt.GCD(bi, bi);
b = BigInt.greater(bi, bi);
b = BigInt.greaterShift(bi, bi, num);
bi = BigInt.int2bigInt(0);
bi = BigInt.int2bigInt(0, 0);
bi = BigInt.int2bigInt(0, 0, 0);
bi = BigInt.inverseMod(bi, bi);
bi = BigInt.inverseModInt(num, num);
b = BigInt.isZero(bi);
b = BigInt.millerRabin(bi, bi);
b = BigInt.millerRabinInt(num, num);
bi = BigInt.mod(bi, bi);
num = BigInt.modInt(bi, num);
bi = BigInt.mult(bi, bi);
bi = BigInt.multMod(bi, bi, bi);
b = BigInt.negative(bi);
bi = BigInt.powMod(bi, bi, bi);
bi = BigInt.randBigInt(num, num);
bi = BigInt.randTruePrime(num);
bi = BigInt.randProbPrime(num);
bi = BigInt.str2bigInt(str, num);
bi = BigInt.str2bigInt(str, num, 0);
bi = BigInt.str2bigInt(str, num, 0, 0);
bi = BigInt.str2bigInt(str, str);
bi = BigInt.str2bigInt(str, str, 0);
bi = BigInt.str2bigInt(str, str, 0, 0);
bi = BigInt.sub(bi, bi);
bi = BigInt.trim(bi, num);
BigInt.addInt_(bi, num);
BigInt.add_(bi, bi);
BigInt.copy_(bi, bi);
num = BigInt.copyInt_(bi, num);
BigInt.GCD_(bi, bi);
b = BigInt.inverseMod_(bi, bi);
BigInt.mod_(bi, bi);
BigInt.mult_(bi, bi);
BigInt.multMod_(bi, bi, bi);
BigInt.powMod_(bi, bi, bi);
BigInt.randBigInt_(bi, num, num);
BigInt.randTruePrime_(bi, num);
BigInt.sub_(bi, bi);
BigInt.addShift_(bi, bi, num);
BigInt.carry_(bi);
BigInt.divide_(bi, bi, bi, bi);
num = BigInt.divInt_(bi, num);
BigInt.eGCD_(bi, bi, bi, bi, bi);
BigInt.halve_(bi);
BigInt.leftShift_(bi, num);
BigInt.linComb_(bi, bi, num, num);
BigInt.linCombShift_(bi, bi, num, num);
BigInt.mont_(bi, bi, bi, num);
BigInt.multInt_(bi, num);
BigInt.rightShift_(bi, num);
BigInt.squareMod_(bi, bi);
BigInt.subShift_(bi, bi, num);
function someRandomRealCode() {
bi = BigInt.int2bigInt(22, 5);
bi = BigInt.str2bigInt("FFFFFFFFFFFFFFFFC90FDAA2", 16);
str = BigInt.bigInt2str(bi, 16);
}
+371
View File
@@ -0,0 +1,371 @@
// Type definitions for BigInt v5.5.1
// Project: https://github.com/Evgenus/BigInt
// Definitions by: Eugene Chernyshov <https://github.com/Evgenus>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module BigInt {
export interface BigInt extends Array<number> {
}
export interface IRandom {
(): number;
}
export function setRandom(random: IRandom): void;
/**
* bigInt add(x,y)
* return (x+y) for bigInts x and y.
*/
export function add(x: BigInt, y: BigInt): BigInt;
/**
* bigInt addInt(x,n)
* return (x+n) where x is a bigInt and n is an integer.
*/
export function addInt(x: BigInt, n: number): BigInt;
interface bigInt2str_T<T> {
/**
* string bigInt2str(x,base)
* return a string form of bigInt x in a given base, with 2 <= base <= 95
*/
(x: BigInt, base: T): string;
}
interface bigInt2strSignature extends bigInt2str_T<string>, bigInt2str_T<number>{
}
export var bigInt2str: bigInt2strSignature;
/**
* int bitSize(x)
* return how many bits long the bigInt x is, not counting leading zeros
*/
export function bitSize(x: BigInt): number;
/**
* bigInt dup(x)
* return a copy of bigInt x
*/
export function dup(x: BigInt): BigInt;
/**
* boolean equals(x,y)
* is the bigInt x equal to the bigint y?
*/
export function equals(x: BigInt, y: BigInt): boolean;
/**
* boolean equalsInt(x,y)
* is bigint x equal to integer y?
*/
export function equalsInt(x: BigInt, y: number): boolean;
/**
* bigInt expand(x,n)
* return a copy of x with at least n elements, adding leading zeros if needed
*/
export function expand(value: BigInt, n: number): BigInt;
/**
* Array findPrimes(n)
* return array of all primes less than integer n
*/
export function findPrimes(n: number): number[];
/**
* bigInt GCD(x,y)
* return greatest common divisor of bigInts x and y (each with same number of elements).
*/
export function GCD(x: BigInt, y: BigInt): BigInt;
/**
* boolean greater(x,y)
* is x>y? (x and y are nonnegative bigInts)
*/
export function greater(x: BigInt, y: BigInt): boolean;
/**
* boolean greaterShift(x,y,shift)
* is (x <<(shift*bpe)) > y?
*/
export function greaterShift(x: BigInt, y: BigInt, shift: number): boolean;
/**
* bigInt int2bigInt(t,n,m)
* return a bigInt equal to integer t, with at least n bits and m array elements
*/
export function int2bigInt(t: number, n?: number, m?: number): BigInt;
/**
* bigInt inverseMod(x,n)
* return (x**(-1) mod n) for bigInts x and n. If no inverse exists, it returns null
*/
export function inverseMod(x: BigInt, n: BigInt): BigInt;
/**
* int inverseModInt(x,n)
* return x**(-1) mod n, for integers x and n. Return 0 if there is no inverse
*/
export function inverseModInt(x: number, n: number): BigInt;
/**
* boolean isZero(x)
* is the bigInt x equal to zero?
*/
export function isZero(x: BigInt): boolean;
/**
* boolean millerRabin(x,b)
* does one round of Miller-Rabin base integer b say that bigInt x is possibly prime? (b is bigInt, 1<b<x)
*/
export function millerRabin(x: BigInt, b: BigInt): boolean;
/**
* boolean millerRabinInt(x,b)
* does one round of Miller-Rabin base integer b say that bigInt x is possibly prime? (b is int, 1<b<x)
*/
export function millerRabinInt(x: number, b: number): boolean;
/**
* bigInt mod(x,n)
* return a new bigInt equal to (x mod n) for bigInts x and n.
*/
export function mod(x: BigInt, n: BigInt): BigInt;
/**
* int modInt(x,n)
* return x mod n for bigInt x and integer n.
*/
export function modInt(x: BigInt, n: number): number;
/**
* bigInt mult(x,y)
* return x*y for bigInts x and y. This is faster when y<x.
*/
export function mult(x: BigInt, y: BigInt): BigInt;
/**
* bigInt multMod(x,y,n)
* return (x*y mod n) for bigInts x,y,n. For greater speed, let y<x.
*/
export function multMod(x: BigInt, y: BigInt, n: BigInt): BigInt;
/**
* boolean negative(x)
* is bigInt x negative?
*/
export function negative(x: BigInt): boolean;
/**
* bigInt powMod(x,y,n)
* return (x**y mod n) where x,y,n are bigInts and ** is exponentiation. 0**0=1. Faster for odd n.
*/
export function powMod(x: BigInt, y: BigInt, n: BigInt): BigInt;
/**
* bigInt randBigInt(n,s)
* return an n-bit random BigInt (n>=1). If s=1, then the most significant of those n bits is set to 1.
*/
export function randBigInt(n: number, s: number): BigInt;
/**
* bigInt randTruePrime(k)
* return a new, random, k-bit, true prime bigInt using Maurer's algorithm.
*/
export function randTruePrime(k: number): BigInt;
/**
* bigInt randProbPrime(k)
* return a new, random, k-bit, probable prime bigInt (probability it's composite less than 2^-80).
*/
export function randProbPrime(k: number): BigInt;
interface str2bigInt_T<T> {
/**
* bigInt str2bigInt(s,b,n,m)
* return a bigInt for number represented in string s in base b with at least n bits and m array elements
*/
(s: string, b: T, n?: number, m?: number): BigInt;
}
interface str2bigIntSignature extends str2bigInt_T<number>, str2bigInt_T<string> {
}
export var str2bigInt: str2bigIntSignature;
/**
* bigInt sub(x,y)
* return (x-y) for bigInts x and y. Negative answers will be 2s complement
*/
export function sub(x: BigInt, y: BigInt): BigInt;
/**
* bigInt trim(x,k)
* return a copy of x with exactly k leading zero elements
*/
export function trim(x: BigInt, k: number): BigInt;
/**
* void addInt_(x,n)
* do x=x+n where x is a bigInt and n is an integer
*/
export function addInt_(x: BigInt, n: number): void;
/**
* void add_(x,y)
* do x=x+y for bigInts x and y
*/
export function add_(x: BigInt, y: BigInt): void;
/**
* void copy_(x,y)
* do x=y on bigInts x and y
*/
export function copy_(x: BigInt, y: BigInt): void;
/**
* void copyInt_(x,n)
* do x=n on bigInt x and integer n
*/
export function copyInt_(x: BigInt, n: number): number;
/**
* void GCD_(x,y)
* set x to the greatest common divisor of bigInts x and y, (y is destroyed). (This never overflows its array).
*/
export function GCD_(x: BigInt, y: BigInt): void;
/**
* boolean inverseMod_(x,n)
* do x=x**(-1) mod n, for bigInts x and n. Returns 1 (0) if inverse does (doesn't) exist
*/
export function inverseMod_(x: BigInt, n: BigInt): boolean;
/**
* void mod_(x,n)
* do x=x mod n for bigInts x and n. (This never overflows its array).
*/
export function mod_(x: BigInt, n: BigInt): void;
/**
* void mult_(x,y)
* do x=x*y for bigInts x and y.
*/
export function mult_(x: BigInt, y: BigInt): void;
/**
* void multMod_(x,y,n)
* do x=x*y mod n for bigInts x,y,n.
*/
export function multMod_(x: BigInt, y: BigInt, n: BigInt): void;
/**
* void powMod_(x,y,n)
* do x=x**y mod n, where x,y,n are bigInts (n is odd) and ** is exponentiation. 0**0=1.
*/
export function powMod_(x: BigInt, y: BigInt, n: BigInt): void;
/**
* void randBigInt_(b,n,s)
* do b = an n-bit random BigInt. if s=1, then nth bit (most significant bit) is set to 1. n>=1.
*/
export function randBigInt_(b: BigInt, n: number, s: number): void;
/**
* void randTruePrime_(ans,k)
* do ans = a random k-bit true random prime (not just probable prime) with 1 in the msb.
*/
export function randTruePrime_(ans: BigInt, k: number): void;
/**
* void sub_(x,y)
* do x=x-y for bigInts x and y. Negative answers will be 2s complement.
*/
export function sub_(x: BigInt, y: BigInt): void;
/**
* void addShift_(x,y,ys)
* do x=x+(y<<(ys*bpe))
*/
export function addShift_(x: BigInt, y: BigInt, ys: number): void;
/**
* void carry_(x)
* do carries and borrows so each element of the bigInt x fits in bpe bits.
*/
export function carry_(x: BigInt): void;
/**
* void divide_(x,y,q,r)
* divide x by y giving quotient q and remainder r
*/
export function divide_(x: BigInt, y: BigInt, q: BigInt, r: BigInt): void;
/**
* int divInt_(x,n)
* do x=floor(x/n) for bigInt x and integer n, and return the remainder. (This never overflows its array).
*/
export function divInt_(x: BigInt, n: number): number;
/**
* void eGCD_(x,y,d,a,b)
* sets a,b,d to positive bigInts such that d = GCD_(x,y) = a*x-b*y
*/
export function eGCD_(x: BigInt, y: BigInt, d: BigInt, a: BigInt, b: BigInt): void;
/**
* void halve_(x)
* do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement. (This never overflows its array).
*/
export function halve_(x: BigInt): void;
/**
* void leftShift_(x,n)
* left shift bigInt x by n bits. n<bpe.
*/
export function leftShift_(x: BigInt, n: number): void;
/**
* void linComb_(x,y,a,b)
* do x=a*x+b*y for bigInts x and y and integers a and b
*/
export function linComb_(x: BigInt, y: BigInt, a: number, b: number): void;
/**
* void linCombShift_(x,y,b,ys)
* do x=x+b*(y<<(ys*bpe)) for bigInts x and y, and integers b and ys
*/
export function linCombShift_(x: BigInt, y: BigInt, b: number, ys: number): void;
/**
* void mont_(x,y,n,np)
* Montgomery multiplication (see comments where the function is defined)
*/
export function mont_(x: BigInt, y: BigInt, n: BigInt, np: number): void;
/**
* void multInt_(x,n)
* do x=x*n where x is a bigInt and n is an integer.
*/
export function multInt_(x: BigInt, n: number): void;
/**
* void rightShift_(x,n)
* right shift bigInt x by n bits. 0 <= n < bpe. (This never overflows its array).
*/
export function rightShift_(x: BigInt, n: number): void;
/**
* void squareMod_(x,n)
* do x=x*x mod n for bigInts x,n
*/
export function squareMod_(x: BigInt, n: BigInt): void;
/**
* void subShift_(x,y,ys)
* do x=x-(y<<(ys*bpe)). Negative answers will be 2s complement.
*/
export function subShift_(x: BigInt, y: BigInt, ys: number): void;
}
+138
View File
@@ -0,0 +1,138 @@
// Type definitions for body-parser
// Project: http://expressjs.com
// Definitions by: Santi Albo <https://github.com/santialbo/>, VILIC VANE <https://vilic.info>, Jonathan Häberle <https://github.com/dreampulse/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
declare module "body-parser" {
import express = require('express');
/**
* bodyParser: use individual json/urlencoded middlewares
* @deprecated
*/
function bodyParser(options?: {
/**
* if deflated bodies will be inflated. (default: true)
*/
inflate?: boolean;
/**
* maximum request body size. (default: '100kb')
*/
limit?: any;
/**
* function to verify body content, the parsing can be aborted by throwing an error.
*/
verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void;
/**
* only parse objects and arrays. (default: true)
*/
strict?: boolean;
/**
* passed to JSON.parse().
*/
receiver?: (key: string, value: any) => any;
/**
* parse extended syntax with the qs module. (default: true)
*/
extended?: boolean;
}): express.RequestHandler;
module bodyParser {
export function json(options?: {
/**
* if deflated bodies will be inflated. (default: true)
*/
inflate?: boolean;
/**
* maximum request body size. (default: '100kb')
*/
limit?: any;
/**
* request content-type to parse, passed directly to the type-is library. (default: 'json')
*/
type?: any;
/**
* function to verify body content, the parsing can be aborted by throwing an error.
*/
verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void;
/**
* only parse objects and arrays. (default: true)
*/
strict?: boolean;
/**
* passed to JSON.parse().
*/
receiver?: (key: string, value: any) => any;
}): express.RequestHandler;
export function raw(options?: {
/**
* if deflated bodies will be inflated. (default: true)
*/
inflate?: boolean;
/**
* maximum request body size. (default: '100kb')
*/
limit?: any;
/**
* request content-type to parse, passed directly to the type-is library. (default: 'application/octet-stream')
*/
type?: any;
/**
* function to verify body content, the parsing can be aborted by throwing an error.
*/
verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void;
}): express.RequestHandler;
export function text(options?: {
/**
* if deflated bodies will be inflated. (default: true)
*/
inflate?: boolean;
/**
* maximum request body size. (default: '100kb')
*/
limit?: any;
/**
* request content-type to parse, passed directly to the type-is library. (default: 'text/plain')
*/
type?: any;
/**
* function to verify body content, the parsing can be aborted by throwing an error.
*/
verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void;
/**
* the default charset to parse as, if not specified in content-type. (default: 'utf-8')
*/
defaultCharset?: string;
}): express.RequestHandler;
export function urlencoded(options?: {
/**
* if deflated bodies will be inflated. (default: true)
*/
inflate?: boolean;
/**
* maximum request body size. (default: '100kb')
*/
limit?: any;
/**
* request content-type to parse, passed directly to the type-is library. (default: 'urlencoded')
*/
type?: any;
/**
* function to verify body content, the parsing can be aborted by throwing an error.
*/
verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void;
/**
* parse extended syntax with the qs module. (default: true)
*/
extended?: boolean;
}): express.RequestHandler;
}
export = bodyParser;
}
+3 -1
View File
@@ -22,6 +22,8 @@ interface BrowserifyObject extends NodeJS.EventEmitter {
ignore(file: string): BrowserifyObject;
transform(tr: string): BrowserifyObject;
transform(tr: Function): BrowserifyObject;
plugin(plugin: string, opts?: any): BrowserifyObject;
plugin(plugin: Function, opts?: any): BrowserifyObject;
}
declare module "browserify" {
@@ -33,4 +35,4 @@ declare module "browserify" {
}): BrowserifyObject;
export = browserify;
}
}
+222
View File
@@ -0,0 +1,222 @@
/// <reference path="bucks.d.ts"/>
function add_and_end() {
//
// new Bucks object
//
var b = new Bucks();
//
// Add and add several tasks.
//
b.add(function f1(err, res) {
return 'a';
}).add(function f2(err, res, next) {
// res => 'a'
return next(null, 3);
}).add(function f3(err, res, next) {
// res => 3
return next(new Error('error after 3'));
}).add(function f4(err, res, next) {
// err => 'error after 3'
return next(null, "recover 4");
}).add(function f5(err, res) {
// res => 'recover 4'
throw new Error('error in f5');
}).add(function f6(err, res) {
// err => 'error in f5'
throw err;
}).add(function f7(err, res) {
// err => 'error in f5'
// ignore and return
return "recover 7";
}).add(function f8(err, res, next) {
// res => 'recover 7';
throw new Error('error in f8');
}).add(function f9(err, res, next) {
// err => 'Error in f8'
// ignore error
return next(null, 'result of 9');
}).end(function last(err, results) {
// all of results
// are obtained in #end
// err => null
// results => [
// 'a',
// null,
// null,
// 'recover 4',
// null,
// null,
// 'recover 7',
// null,
// 'result of 9'
// ];
});
}
function then() {
var b = new Bucks();
b.then(function start() {
return 'start';
}).then(function second(res, next) {
// res => 'start'
return next(null, 'second')
}).end();
}
function delay() {
var b = new Bucks();
b.add(function (){ /** program */ })
.delay(1 * 1000) // 1ms
.add(function() { /** program */})
.end();
}
function error() {
var b = new Bucks();
b.then(function start() {
throw new Error('error in start');
return 'start';
}).error(function onError(e, next) {
// e => 'error in start'
return next();
}).end();
}
function final_errorback_in_end() {
//
// last error back
//
var b = new Bucks();
b.empty(
// add empty task (#end with no task cause error)
).end(function last(err, res) {
// error in last callback
throw new Error('error in end');
}, function finalErrorback(err) {
// catch uncaught error in last callback
// err => 'error in end'
});
}
function uncaught_error() {
try {
var b = new Bucks();
b.then(function () {
throw new Error('error');
}).end();
} catch(e) {
// e => 'error'
}
}
function waterfall() {
var t1: Bucks.Task = function t1(err, res) {
return 't1';
};
var t2: Bucks.Task = function t2(err, res) {
return 't2';
};
new Bucks().waterfall([t1, t2]).end(function finish(err, ress) {
// ress => ['t1', 't2']
});
// same as
new Bucks().add(t1).add(t2).end(function finish(err, ress) {
// ress => ['t1', 't2']
});
}
function parallel() {
var b = new Bucks();
b.parallel([
function task1(err, res) {
return "task1";
},
function task2(err, res, next) {
return next(null, "task2");
},
function task3(err, res, next) {
return next(new Error('passed error in task3'));
},
function task4(err, res, next) {
throw new Error('thrown error in task4');
}
]).add(function getResults(err, res, next) {
// res => {
// err: [
// null,
// null,
// [Error: passed error in task3],
// [Error: thrown error in task4]
// ],
// res: [
// 'task1',
// 'task2',
// null,
// null
// ]
// }
next();
}).end();
}
function onError() {
var onError = function (e: Error, bucks: Bucks.Bucks) {
console.log("Custom onError");
};
// Bucks.onError!!
Bucks.onError(onError);
var b0 = new Bucks();
b0
.add(function(err, next) {
throw new Error('b0');
})
.end()
;
}
function dispose() {
var b0 = new Bucks();
b0.dispose = function dispose () {
// delete b0.dummy;
}
b0
.add(function(err, next) {
// b0.dummy = "dummy";
next();
})
.end(null, null)
;
}
function debug() {
Bucks.DEBUG = true;
}
+113
View File
@@ -0,0 +1,113 @@
// Type definitions for bucks.js 0.8.3
// Project: https://github.com/CyberAgent/bucks.js
// Definitions by: Shunsuke Ohtani <https://github.com/zaneli>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module Bucks {
interface BucksStatic {
/**
* bucks.js version.
*/
VERSION: string;
/**
* If set `true`, uncaught errors are logged.
*/
DEBUG: boolean;
/**
* Running bucks objects.
*/
running: Bucks[];
/**
* Not yet called `end` bucks object.
*/
living: Bucks[];
/**
* Create bucks object.
*/
new(): Bucks;
/**
* Catch all errors.
* @param onError Function called after catching error
*/
onError(onError: (err:Error, bucks:Bucks)=>any): void;
}
interface Bucks {
/**
* Add a task.
* @param task Function added async chain
*/
add(task: TaskWithNext): Bucks;
/**
* Add a task called only in case of success.
* @param onSuccess Function called only in case of success
*/
then(onSuccess: (res:any, next?:Task)=>any): Bucks;
/**
* Add a empty task.
*/
empty(): Bucks;
/**
* Add a task called only in case of error.
* @param onError Function called only in case of error
*/
error(onError: (err:Error, next?:Task)=>any): Bucks;
/**
* Add tasks in asynchronous way and join their results.
* @param tasks Functions called in asynchronous way and join their results
*/
parallel(tasks: TaskWithNext[]): Bucks;
/**
* Add tasks in asynchronous way and join their results.
* @param tasks Functions added async chain
*/
waterfall(tasks: TaskWithNext[]): Bucks;
/**
* Add delay execution.
* @param ms number millisecond for delaying
*/
delay(ms: number): Bucks;
/**
* Called when destroy async chain.
*/
dispose(): void;
/**
* Destroy this object and call last callback function.
* @param err If specify err and no callback, throw to execute failure callback
*/
destroy(err?: Error): Bucks;
/**
* Complete creating async chain and start executing.
* @param callback Last callback function
* @param errback Handler for occurring error in last callback function
*/
end(callback?: Task, errback?: (err:Error)=>any): void;
}
interface TaskWithNext {
(err?: Error, res?: any, next?: Task): any;
}
interface Task {
(err?: Error, res?: any): any;
}
}
declare var Bucks: Bucks.BucksStatic;
+6 -2
View File
@@ -1,7 +1,6 @@
// Type definitions for Cheerio v0.17.0
// Project: https://github.com/cheeriojs/cheerio
// Definitions by: Bret Little <https://github.com/blittle>
// Definitions by: VILIC VANE <http://vilic.info>
// Definitions by: Bret Little <https://github.com/blittle>, VILIC VANE <http://vilic.info>, Wayne Maurer <https://github.com/wmaurer>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface Cheerio {
@@ -190,6 +189,11 @@ interface CheerioStatic {
root(): Cheerio;
contains(container: CheerioElement, contained: CheerioElement): boolean;
parseHTML(data: string, context?: Document, keepScripts?: boolean): Document[];
html(options?: CheerioOptionsInterface): string;
html(selector: string, options?: CheerioOptionsInterface): string;
html(element: Cheerio, options?: CheerioOptionsInterface): string;
html(element: CheerioElement, options?: CheerioOptionsInterface): string;
}
interface CheerioElement {
+250 -1
View File
@@ -24,4 +24,253 @@ chrome.app.runtime.onLaunched.addListener(function (launchData: runtime.LaunchDa
chrome.app.runtime.onRestarted.addListener(function () { return; });
// Get Current Window
var currentWindow: cwindow.AppWindow = chrome.app.window.current();
var currentWindow: cwindow.AppWindow = chrome.app.window.current();
// Sockets
// https://developer.chrome.com/apps/sockets_tcp
function test_socketsTcp(): void {
var socketId: number;
var properties: chrome.sockets.tcp.SocketProperties = {};
var buffer: ArrayBuffer = new ArrayBuffer(256);
// create
chrome.sockets.tcp.create((info) => {
socketId = info.socketId;
});
chrome.sockets.tcp.create(properties, (info) => {
socketId = info.socketId;
});
// update
chrome.sockets.tcp.update(socketId, properties);
chrome.sockets.tcp.update(socketId, properties, () => { });
// setPaused
chrome.sockets.tcp.setPaused(socketId, true);
chrome.sockets.tcp.setPaused(socketId, true, () => { });
// setKeepAlive
chrome.sockets.tcp.setKeepAlive(socketId, true, (result: number) => { });
chrome.sockets.tcp.setKeepAlive(socketId, true, 0, (result: number) => { });
// setNoDelay
chrome.sockets.tcp.setNoDelay(socketId, true, (result: number) => { });
// connect
chrome.sockets.tcp.connect(socketId, "192.168.0.1", 8080, (result: number) => { });
// disconnect
chrome.sockets.tcp.disconnect(socketId);
chrome.sockets.tcp.disconnect(socketId, () => { });
// send
chrome.sockets.tcp.send(socketId, buffer, (info: chrome.sockets.tcp.SendInfo) => { });
// close
chrome.sockets.tcp.close(socketId);
chrome.sockets.tcp.close(socketId, () => { });
// getInfo
chrome.sockets.tcp.getInfo(socketId, (info: chrome.sockets.tcp.SocketInfo) => { });
// getSockets
chrome.sockets.tcp.getSockets(socketId, (infos: chrome.sockets.tcp.SocketInfo[]) => { });
}
function test_socketsTcpEvents(): void {
chrome.sockets.tcp.onReceive.addListener((info: chrome.sockets.tcp.ReceiveEventArgs) => { });
chrome.sockets.tcp.onReceiveError.addListener((info: chrome.sockets.tcp.ReceiveErrorEventArgs) => { });
}
function testSocketsTcpTypes(): void {
// SocketProperties
var properties: chrome.sockets.tcp.SocketProperties;
properties = {
};
properties = {
persistent: true,
name: "test",
bufferSize: 1024
};
// SocketInfo
var socketInfo: chrome.sockets.tcp.SocketInfo;
socketInfo = {
socketId: 1,
persistent: true,
paused: true,
connected: false
};
socketInfo.name = "test";
socketInfo.bufferSize = 1024;
socketInfo.localAddress = "192.168.0.2";
socketInfo.localPort = 8000;
socketInfo.peerAddress = "192.168.0.3";
socketInfo.peerPort = 1000;
}
// https://developer.chrome.com/apps/sockets_udp
function test_socketsUdp(): void {
var socketId: number;
var properties: chrome.sockets.udp.SocketProperties = {};
var buffer: ArrayBuffer = new ArrayBuffer(256);
// create
chrome.sockets.udp.create((info) => {
socketId = info.socketId;
});
chrome.sockets.udp.create(properties, (info) => {
socketId = info.socketId;
});
// update
chrome.sockets.udp.update(socketId, properties);
chrome.sockets.udp.update(socketId, properties, () => { });
// setPaused
chrome.sockets.udp.setPaused(socketId, true);
chrome.sockets.udp.setPaused(socketId, true, () => { });
// bind
chrome.sockets.udp.bind(socketId, "0.0.0.0", 8080, (result: number) => { });
// send
chrome.sockets.udp.send(socketId, buffer, "172.21.0.1", 10080, (info: chrome.sockets.udp.SendInfo) => { });
// close
chrome.sockets.udp.close(socketId);
chrome.sockets.udp.close(socketId, () => { });
// getInfo
chrome.sockets.udp.getInfo(socketId, (info: chrome.sockets.udp.SocketInfo) => { });
// getSockets
chrome.sockets.udp.getSockets((infos: chrome.sockets.udp.SocketInfo[]) => { });
// joinGroup
chrome.sockets.udp.joinGroup(socketId, "224.0.0.1", (result: number) => { });
// leaveGroup
chrome.sockets.udp.leaveGroup(socketId, "224.0.0.1", (result: number) => { });
// setMulticastTimeToLive
chrome.sockets.udp.setMulticastTimeToLive(socketId, 100, (result: number) => { });
// setMulticastLoopbackMode
chrome.sockets.udp.setMulticastLoopbackMode(socketId, true, (result: number) => { });
// getJoinedGroups
chrome.sockets.udp.getJoinedGroups(socketId, (groups: string[]) => { });
}
function test_socketsUdpEvents(): void {
chrome.sockets.udp.onReceive.addListener((info: chrome.sockets.udp.ReceiveEventArgs) => { });
chrome.sockets.udp.onReceiveError.addListener((info: chrome.sockets.udp.ReceiveErrorEventArgs) => { });
}
function testSocketsUdpTypes(): void {
// SocketProperties
var properties: chrome.sockets.udp.SocketProperties;
properties = {
};
properties = {
persistent: true,
name: "test",
bufferSize: 1024
};
// SocketInfo
var socketInfo: chrome.sockets.udp.SocketInfo;
socketInfo = {
socketId: 1,
persistent: true,
paused: true
};
socketInfo.name = "test";
socketInfo.bufferSize = 1024;
socketInfo.localAddress = "192.168.0.2";
socketInfo.localPort = 8000;
}
// https://developer.chrome.com/apps/sockets_tcpServer
function test_socketsTcpServer(): void {
var socketId: number;
var properties: chrome.sockets.tcpServer.SocketProperties = {};
var buffer: ArrayBuffer = new ArrayBuffer(256);
// create
chrome.sockets.tcpServer.create((info) => {
socketId = info.socketId;
});
chrome.sockets.tcpServer.create(properties, (info) => {
socketId = info.socketId;
});
// update
chrome.sockets.tcpServer.update(socketId, properties);
chrome.sockets.tcpServer.update(socketId, properties, () => { });
// setPaused
chrome.sockets.tcpServer.setPaused(socketId, true);
chrome.sockets.tcpServer.setPaused(socketId, true, () => { });
// listen
chrome.sockets.tcpServer.listen(socketId, "0.0.0.0", 80, (result: number) => { });
chrome.sockets.tcpServer.listen(socketId, "0.0.0.0", 80, 128, (result: number) => { });
// disconnect
chrome.sockets.tcp.disconnect(socketId);
chrome.sockets.tcp.disconnect(socketId, () => { });
// close
chrome.sockets.udp.close(socketId);
chrome.sockets.udp.close(socketId, () => { });
// getInfo
chrome.sockets.udp.getInfo(socketId, (info: chrome.sockets.udp.SocketInfo) => { });
// getSockets
chrome.sockets.tcp.getSockets(socketId, (infos: chrome.sockets.tcp.SocketInfo[]) => { });
}
function test_socketsTcpServerEvents(): void {
chrome.sockets.tcpServer.onAccept.addListener((info: chrome.sockets.tcpServer.AcceptEventArgs) => { });
chrome.sockets.tcpServer.onAcceptError.addListener((info: chrome.sockets.tcpServer.AcceptErrorEventArgs) => { });
}
function testSocketsTcpServerTypes(): void {
// SocketProperties
var properties: chrome.sockets.tcpServer.SocketProperties;
properties = {
};
properties = {
persistent: true,
name: "test"
};
// SocketInfo
var socketInfo: chrome.sockets.tcpServer.SocketInfo;
socketInfo = {
socketId: 1,
persistent: true,
paused: true
};
socketInfo.name = "test";
socketInfo.localAddress = "192.168.0.2";
socketInfo.localPort = 8000;
}
+187 -1
View File
@@ -1,6 +1,6 @@
// Type definitions for Chrome packaged application development
// Project: http://developer.chrome.com/apps/
// Definitions by: Adam Lay <https://github.com/AdamLay>
// Definitions by: Adam Lay <https://github.com/AdamLay>, MIZUNE Pine <https://github.com/pine613>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
////////////////////
@@ -93,3 +93,189 @@ declare module chrome.app.window {
var onMinimized: WindowEvent;
var onRestored: WindowEvent;
}
////////////////////
// Sockets
////////////////////
declare module chrome.sockets.tcp {
interface CreateInfo {
socketId: number;
}
interface SendInfo {
resultCode: number;
bytesSent?: number;
}
interface Event<T> {
addListener(callback: (info: T) => void): void;
}
interface ReceiveEventArgs {
socketId: number;
data: ArrayBuffer;
}
interface ReceiveErrorEventArgs {
socketId: number;
resultCode: number;
}
interface SocketProperties {
persistent?: boolean;
name?: string;
bufferSize?: number;
}
interface SocketInfo {
socketId: number;
persistent: boolean;
name?: string;
bufferSize?: number;
paused: boolean;
connected: boolean;
localAddress?: string;
localPort?: number;
peerAddress?: string;
peerPort?: number;
}
export function create(callback: (createInfo: CreateInfo) => void): void;
export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void;
export function update(socketId: number, properties: SocketProperties, callback?: () => void): void;
export function setPaused(socketId: number, paused: boolean, callback?: () => void): void;
export function setKeepAlive(socketId: number,
enable: boolean, callback: (result: number) => void): void;
export function setKeepAlive(socketId: number,
enable: boolean, delay: number, callback: (result: number) => void): void;
export function setNoDelay(socketId: number, noDelay: boolean, callback: (result: number) => void): void;
export function connect(socketId: number,
peerAddress: string, peerPort: number, callback: (result: number) => void): void;
export function disconnect(socketId: number, callback?: () => void): void;
export function send(socketId: number, data: ArrayBuffer, callback: (sendInfo: SendInfo) => void): void;
export function close(socketId: number, callback?: () => void): void;
export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void;
export function getSockets(socketId: number, callback: (socketInfos: SocketInfo[]) => void): void;
var onReceive: Event<ReceiveEventArgs>;
var onReceiveError: Event<ReceiveErrorEventArgs>;
}
declare module chrome.sockets.udp {
interface CreateInfo {
socketId: number;
}
interface SendInfo {
resultCode: number;
bytesSent?: number;
}
interface Event<T> {
addListener(callback: (info: T) => void): void;
}
interface ReceiveEventArgs {
socketId: number;
data: ArrayBuffer;
remoteAddress: string;
remotePort: number;
}
interface ReceiveErrorEventArgs {
socketId: number;
resultCode: number;
}
interface SocketProperties {
persistent?: boolean;
name?: string;
bufferSize?: number;
}
interface SocketInfo {
socketId: number;
persistent: boolean;
name?: string;
bufferSize?: number;
paused: boolean;
localAddress?: string;
localPort?: number;
}
export function create(callback: (createInfo: CreateInfo) => void): void;
export function create(properties: SocketProperties,
callback: (createInfo: CreateInfo) => void): void;
export function update(socketId: number, properties: SocketProperties, callback?: () => void): void;
export function setPaused(socketId: number, paused: boolean, callback?: () => void): void;
export function bind(socketId: number, address: string, port: number, callback: (result: number) => void): void;
export function send(socketId: number, data: ArrayBuffer, address: string, port: number, callback: (sendInfo: SendInfo) => void): void;
export function close(socketId: number, callback?: () => void): void;
export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void;
export function getSockets(callback: (socketInfos: SocketInfo[]) => void): void;
export function joinGroup(socketId: number, address: string, callback: (result: number) => void): void;
export function leaveGroup(socketId: number, address: string, callback: (result: number) => void): void;
export function setMulticastTimeToLive(socketId: number, ttl: number, callback: (result: number) => void): void;
export function setMulticastLoopbackMode(socketId: number, enabled: boolean, callback: (result: number) => void): void;
export function getJoinedGroups(socketId: number, callback: (groups: string[]) => void): void;
var onReceive: Event<ReceiveEventArgs>;
var onReceiveError: Event<ReceiveErrorEventArgs>;
}
declare module chrome.sockets.tcpServer {
interface CreateInfo {
socketId: number;
}
interface Event<T> {
addListener(callback: (info: T) => void): void;
}
interface AcceptEventArgs {
socketId: number;
clientSocketId: number;
}
interface AcceptErrorEventArgs {
socketId: number;
resultCode: number;
}
interface SocketProperties {
persistent?: boolean;
name?: string;
}
interface SocketInfo {
socketId: number;
persistent: boolean;
name?: string;
paused: boolean;
localAddress?: string;
localPort?: number;
}
export function create(callback: (createInfo: CreateInfo) => void): void;
export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void;
export function update(socketId: number, properties: SocketProperties, callback?: () => void): void;
export function setPaused(socketId: number, paused: boolean, callback?: () => void): void;
export function listen(socketId: number, address: string,
port: number, backlog: number, callback: (result: number) => void): void;
export function listen(socketId: number, address: string,
port: number, callback: (result: number) => void): void;
export function disconnect(socketId: number, callback?: () => void): void;
export function close(socketId: number, callback?: () => void): void;
export function getInfo(socketId: number, callback: (socketInfos: SocketInfo[]) => void): void;
var onAccept: Event<AcceptEventArgs>;
var onAcceptError: Event<AcceptErrorEventArgs>;
}
+10 -2
View File
@@ -843,8 +843,12 @@ declare module chrome.extension {
type?: string;
}
interface LastError {
message?: string;
}
var inIncognitoContext: boolean;
var lastError: Object;
var lastError: LastError;
export function getBackgroundPage(): Window;
export function getURL(path: string): string;
@@ -1487,9 +1491,13 @@ declare module chrome.proxy {
// Runtime
////////////////////
declare module chrome.runtime {
var lastError: Object;
var lastError: LastError;
var id: string;
interface LastError {
message?: string;
}
interface ConnectInfo {
name?: string;
}
+18 -1
View File
@@ -9,7 +9,7 @@ declare function CodeMirror(callback: (host: HTMLElement) => void , options?: Co
declare module CodeMirror {
export var Pass: any;
function fromTextArea(host: HTMLTextAreaElement, options?: EditorConfiguration): CodeMirror.Editor;
function fromTextArea(host: HTMLTextAreaElement, options?: EditorConfiguration): CodeMirror.EditorFromTextArea;
var version: string;
@@ -86,6 +86,11 @@ declare module CodeMirror {
or the line the widget is on require the widget to be redrawn. */
function on(line: LineWidget, eventName: 'redraw', handler: () => void ): void;
function off(line: LineWidget, eventName: 'redraw', handler: () => void ): void;
/** Various CodeMirror-related objects emit events, which allow client code to react to various situations.
Handlers for such events can be registered with the on and off methods on the objects that the event fires on.
To fire your own events, use CodeMirror.signal(target, name, args...), where target is a non-DOM-node object. */
function signal(target: any, name: string, ...args: any[]): void;
interface Editor {
@@ -369,6 +374,18 @@ declare module CodeMirror {
on(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: number, element: HTMLElement) => void ): void;
off(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: number, element: HTMLElement) => void ): void;
}
interface EditorFromTextArea extends Editor {
/** Copy the content of the editor into the textarea. */
save(): void;
/** Remove the editor, and restore the original textarea (with the editor's current content). */
toTextArea(): void;
/** Returns the textarea that the instance was based on. */
getTextArea(): HTMLTextAreaElement;
}
class Doc {
constructor (text: string, mode?: any, firstLineNumber?: number);
+10
View File
@@ -0,0 +1,10 @@
/// <reference path="compression.d.ts" />
import express = require('express');
import compress = require('compression');
var app = express();
app.use(compress());
app.use(compress({
threshold: 512
}));
+20
View File
@@ -0,0 +1,20 @@
// Type definitions for compression
// Project: https://github.com/expressjs/compression
// Definitions by: Santi Albo <https://github.com/santialbo/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
declare module "compression" {
import express = require('express');
module e {
interface CompressionOptions {
threshold?: number;
filter?: Function;
}
}
function e(options?: e.CompressionOptions): express.RequestHandler;
export = e;
}
+7
View File
@@ -0,0 +1,7 @@
/// <reference path="cookie-parser.d.ts" />
import express = require('express');
import cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser('optional secret string'));
+12
View File
@@ -0,0 +1,12 @@
// Type definitions for cookie-parser
// Project: https://github.com/expressjs/cookie-parser
// Definitions by: Santi Albo <https://github.com/santialbo/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
declare module "cookie-parser" {
import express = require('express');
function e(secret?: string, options?: any): express.RequestHandler;
export = e;
}
Vendored Executable → Regular
+69 -172
View File
@@ -243,7 +243,7 @@ declare module D3 {
*
* @param map Array of objects to get the values from
*/
values(map: any[]): any[];
values(map: any): any[];
/**
* List the key-value entries of an associative array.
*
@@ -749,7 +749,7 @@ declare module D3 {
insert: (name: string, before: string) => Selection;
remove: () => Selection;
empty: () => boolean;
data: {
(values: (data: any, index?: number) => any[], key?: (data: any, index?: number) => any): UpdateSelection;
(values: any[], key?: (data: any, index?: number) => any): UpdateSelection;
@@ -848,14 +848,18 @@ declare module D3 {
values(): Array<any>;
entries(): Array<any>;
forEach(func: (key: string, value: any) => void ): void;
empty(): boolean;
size(): number;
}
export interface Set{
export interface Set {
has(value: any): boolean;
add(value: any): any;
add<T>(value: T): T;
remove(value: any): boolean;
values(): Array<any>;
forEach(func: (value: any) => void ): void;
empty(): boolean;
size(): number;
}
export interface Random {
@@ -1159,6 +1163,19 @@ declare module D3 {
*/
(size: Array<number>): TreeLayout;
};
/**
* Gets or sets the available node size
*/
nodeSize: {
/**
* Gets the available node size
*/
(): Array<number>;
/**
* Sets the available node size
*/
(size: Array<number>): TreeLayout;
};
}
export interface PieLayout {
@@ -1479,7 +1496,7 @@ declare module D3 {
/**
* increase lightness by some exponential factor (gamma)
*/
brighter(k: number): Color;
brighter(k?: number): Color;
/**
* decrease lightness by some exponential factor (gamma)
*/
@@ -1720,10 +1737,21 @@ declare module D3 {
(): any[];
(values: any[]): Axis;
};
tickSubdivide(count: number): Axis;
tickSize(major?: number, minor?: number, end?: number): Axis;
tickSize: {
(): number;
(inner: number, outer?: number): Axis;
}
innerTickSize: {
(): number;
(value: number): Axis;
}
outerTickSize: {
(): number;
(value: number): Axis;
}
tickFormat(formatter: (value: any) => string): Axis;
nice(count?: number): Axis;
}
export interface Arc {
@@ -2494,21 +2522,23 @@ declare module D3 {
threshold(): ThresholdScale;
}
export interface Scale {
export interface GenericScale<S> {
(value: any): any;
domain: {
(values: any[]): Scale;
(values: any[]): S;
(): any[];
};
range: {
(values: any[]): Scale;
(values: any[]): S;
(): any[];
};
invertExtent?(y: any): any[];
copy(): Scale;
copy(): S;
}
export interface QuantitiveScale extends Scale {
export interface Scale extends GenericScale<Scale> { }
export interface GenericQuantitativeScale<S> extends GenericScale<S> {
/**
* Get the range value corresponding to a given domain value.
*
@@ -2522,60 +2552,33 @@ declare module D3 {
*/
invert(value: number): number;
/**
* Get or set the scale's input domain.
*/
domain: {
/**
* Set the scale's input domain.
*
* @param value The input domain
*/
(values: any[]): QuantitiveScale;
/**
* Get the scale's input domain.
*/
(): any[];
};
/**
* get or set the scale's output range.
*/
range: {
/**
* Set the scale's output range.
*
* @param value The output range.
*/
(values: any[]): QuantitiveScale;
/**
* Get the scale's output range.
*/
(): any[];
};
/**
* Set the scale's output range, and enable rounding.
*
* @param value The output range.
*/
rangeRound: (values: any[]) => QuantitiveScale;
rangeRound: (values: any[]) => S;
/**
* get or set the scale's output interpolator.
*/
interpolate: {
(): D3.Transition.Interpolate;
(factory: D3.Transition.Interpolate): QuantitiveScale;
(factory: D3.Transition.Interpolate): S;
};
/**
* enable or disable clamping of the output range.
*
* @param clamp Enable or disable
*/
clamp(clamp: boolean): QuantitiveScale;
clamp: {
(): boolean;
(clamp: boolean): S;
}
/**
* extend the scale domain to nice round numbers.
*
*
* @param count Optional number of ticks to exactly fit the domain
*/
nice(count?: number): QuantitiveScale;
nice(count?: number): S;
/**
* get representative values from the input domain.
*
@@ -2587,23 +2590,14 @@ declare module D3 {
*
* @param count Aproximate representative values to return
*/
tickFormat(count: number): (n: number) => string;
/**
* create a new scale from an existing scale..
*/
copy(): QuantitiveScale;
tickFormat(count: number, format?: string): (n: number) => string;
}
export interface LinearScale extends QuantitiveScale {
/**
* Get the range value corresponding to a given domain value.
*
* @param value Domain Value
*/
(value: number): number;
}
export interface QuantitativeScale extends GenericQuantitativeScale<QuantitativeScale> { }
export interface IdentityScale extends Scale {
export interface LinearScale extends GenericQuantitativeScale<LinearScale> { }
export interface IdentityScale extends GenericScale<IdentityScale> {
/**
* Get the range value corresponding to a given domain value.
*
@@ -2630,132 +2624,31 @@ declare module D3 {
tickFormat(count: number): (n: number) => string;
}
export interface SqrtScale extends QuantitiveScale {
/**
* Get the range value corresponding to a given domain value.
*
* @param value Domain Value
*/
(value: number): number;
}
export interface SqrtScale extends GenericQuantitativeScale<SqrtScale> { }
export interface PowScale extends QuantitiveScale {
/**
* Get the range value corresponding to a given domain value.
*
* @param value Domain Value
*/
(value: number): number;
}
export interface PowScale extends GenericQuantitativeScale<PowScale> { }
export interface LogScale extends QuantitiveScale {
/**
* Get the range value corresponding to a given domain value.
*
* @param value Domain Value
*/
(value: number): number;
}
export interface LogScale extends GenericQuantitativeScale<LogScale> { }
export interface OrdinalScale extends Scale {
/**
* Get the range value corresponding to a given domain value.
*
* @param value Domain Value
*/
(value: any): any;
/**
* Get or set the scale's input domain.
*/
domain: {
/**
* Set the scale's input domain.
*
* @param value The input domain
*/
(values: any[]): OrdinalScale;
/**
* Get the scale's input domain.
*/
(): any[];
};
/**
* get or set the scale's output range.
*/
range: {
/**
* Set the scale's output range.
*
* @param value The output range.
*/
(values: any[]): OrdinalScale;
/**
* Get the scale's output range.
*/
(): any[];
};
export interface OrdinalScale extends GenericScale<OrdinalScale> {
rangePoints(interval: any[], padding?: number): OrdinalScale;
rangeBands(interval: any[], padding?: number, outerPadding?: number): OrdinalScale;
rangeRoundBands(interval: any[], padding?: number, outerPadding?: number): OrdinalScale;
rangeBand(): number;
rangeExtent(): any[];
/**
* create a new scale from an existing scale..
*/
copy(): OrdinalScale;
}
export interface QuantizeScale extends Scale {
(value: any): any;
domain: {
(values: number[]): QuantizeScale;
(): any[];
};
range: {
(values: any[]): QuantizeScale;
(): any[];
};
copy(): QuantizeScale;
}
export interface QuantizeScale extends GenericScale<QuantizeScale> { }
export interface ThresholdScale extends Scale {
(value: any): any;
domain: {
(values: number[]): ThresholdScale;
(): any[];
};
range: {
(values: any[]): ThresholdScale;
(): any[];
};
copy(): ThresholdScale;
}
export interface ThresholdScale extends GenericScale<ThresholdScale> { }
export interface QuantileScale extends Scale {
(value: any): any;
domain: {
(values: number[]): QuantileScale;
(): any[];
};
range: {
(values: any[]): QuantileScale;
(): any[];
};
export interface QuantileScale extends GenericScale<QuantileScale> {
quantiles(): any[];
copy(): QuantileScale;
}
export interface TimeScale extends Scale {
export interface TimeScale extends GenericScale<TimeScale> {
(value: Date): number;
invert(value: number): Date;
domain: {
(values: any[]): TimeScale;
(): any[];
};
range: {
(values: any[]): TimeScale;
(): any[];
};
rangeRound: (values: any[]) => TimeScale;
interpolate: {
(): D3.Transition.Interpolate;
@@ -2767,7 +2660,7 @@ declare module D3 {
(range: D3.Time.Range, count: number): any[];
};
tickFormat(count: number): (n: number) => string;
copy(): TimeScale;
nice(count?: number): TimeScale;
}
}
@@ -3417,7 +3310,7 @@ declare module D3 {
*
* @param constant The new constant value.
*/
(constant: number): Voronoi<T>;
(constant: number): Voronoi<T>;
}
clipExtent: {
/**
@@ -3460,3 +3353,7 @@ declare module D3 {
}
declare var d3: D3.Base;
declare module "d3" {
export = d3;
}
+54
View File
@@ -0,0 +1,54 @@
/// <reference path="dropboxjs.d.ts" />
var browserClient = new Dropbox.Client({ key: "your-key-here" });
browserClient.authenticate(function (error, client) {
if (error) {
alert(error);
}
client.onError.addListener(function (error) {
if (window.console) { // Skip the "if" in node.js code.
console.error(error);
}
});
client.getAccountInfo(function (error, accountInfo) {
if (error) {
alert(error); // Something went wrong.
}
alert("Hello, " + accountInfo.name + "!");
});
client.writeFile("hello_world.txt", "Hello, world!\n", function (error, stat) {
if (error) {
alert(error); // Something went wrong.
}
alert("File saved as revision " + stat.versionTag);
});
client.readFile("hello_world.txt", function (error, data) {
if (error) {
alert(error); // Something went wrong.
}
alert(data); // data has the file's contents
});
client.readdir("/", function (error, entries) {
if (error) {
alert(error); // Something went wrong.
}
alert("Your Dropbox contains " + entries.join(", "));
});
});
var serverClient = new Dropbox.Client({
key: "your-key-here",
secret: "your-secret-here"
});
serverClient.authDriver(new Dropbox.AuthDriver.NodeServer(8191));
+101
View File
@@ -0,0 +1,101 @@
// Type definitions for dropbox-js
// Project: https://github.com/dropbox/dropbox-js
// Definitions by: Steve Fenton <https://github.com/Steve-Fenton>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module Dropbox {
export interface DropboxConfig {
key: string;
secret?: string;
}
export interface AccountInfoData {
name: string;
email: string;
countryCode: string;
uid: string;
referralUrl: string;
publicAppUrl: string;
quota: number;
usedQuota: number;
privateBytes: number;
sharedBytes: number;
}
export interface AccountInfo extends AccountInfoData {
parse(accountInfo: string): AccountInfo;
json(): AccountInfoData;
}
export interface ApiError {
INVALID_TOKEN: number;
NOT_FOUND: number;
OVER_QUOTA: number;
RATE_LIMITED: number;
NETWORK_ERROR: number;
INVALID_PARAM: number;
OAUTH_ERROR: number;
INVALID_METHOD: number;
}
export interface FileStatisticsData {
path: string;
name: string;
inAppFolder: boolean;
isFolder: boolean;
isFile: boolean;
isRemoved: boolean;
typeIcon: string;
versionTag: string;
contentHash: string;
mimeType: string;
size: number;
humanSize: string;
hasThumbnail: boolean;
modifiedAt: Date;
clientModifiedAt: Date;
}
export interface FileStatistics extends FileStatisticsData {
parse(stats: string): FileStatistics;
json(): FileStatisticsData;
}
export interface ClientOnError {
addListener(callback: (error: number) => any): void;
}
export interface Client {
new (config: DropboxConfig): Client;
authDriver(authDriver: any): Client;
authenticate(callback: (error: number, client: Client) => any): Client;
credentials(): string;
dropboxUid(): string;
isAuthenticated(): boolean;
onError: ClientOnError;
getAccountInfo(callback: (error: number, accountInfo: AccountInfo) => any): XMLHttpRequest;
getUserInfo(callback: (error: number, accountInfo: AccountInfo) => any): XMLHttpRequest;
signOut(options: {}, callback: (error: number) => any): XMLHttpRequest;
signOff(options: {}, callback: (error: number) => any): XMLHttpRequest;
writeFile(fileName: string, contents: string, options: {}, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest;
writeFile(fileName: string, contents: string, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest;
readFile(fileName: string, options: {}, callback: (error: number, contents: string, stats: FileStatistics) => any): XMLHttpRequest;
readFile(fileName: string, callback: (error: number, contents: string, stats: FileStatistics) => any): XMLHttpRequest;
stat(path: string, options: {}, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest;
stat(path: string, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest;
metadata(path: string, options: {}, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest;
metadata(path: string, callback: (error: number, stats: FileStatistics) => any): XMLHttpRequest;
readdir(path: string, options: {}, callback: (error: number, entries: any[]) => any): XMLHttpRequest;
readdir(path: string, callback: (error: number, entries: any[]) => any): XMLHttpRequest;
}
export module AuthDriver {
export interface NodeServer {
new (port: number): any;
}
export var NodeServer: NodeServer;
}
export var Client: Client;
}
+7
View File
@@ -0,0 +1,7 @@
/// <reference path="errorhandler.d.ts" />
import express = require('express');
import errorhandler = require('errorhandler');
var app = express();
app.use(errorhandler());
+12
View File
@@ -0,0 +1,12 @@
// Type definitions for errorhandler
// Project: https://github.com/expressjs/errorhandler
// Definitions by: Santi Albo <https://github.com/santialbo/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
declare module "errorhandler" {
import express = require('express');
function e(): express.ErrorRequestHandler;
export = e;
}
+165 -153
View File
@@ -1,161 +1,173 @@
// Type definitions for express-validator
// Project: https://github.com/ctavan/express-validator
// Definitions by: Nathan Ridley <https://github.com/axefrog/>
// Definitions by: Nathan Ridley <https://github.com/axefrog/>, Jonathan Häberle <http://dreampulse.de>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module ExpressValidator {
export interface ValidationError {
msg: string;
param: string;
}
/// <reference path="../express/express.d.ts" />
export interface RequestValidation {
check(field: string, message: string): Validator;
assert(field: string, message: string): Validator;
sanitize(field: string): Sanitizer;
onValidationError(func: (msg: string) => void): void;
}
export interface Validator {
/**
* Alias for regex()
*/
is(): Validator;
/**
* Alias for notRegex()
*/
not(): Validator;
isEmail(): Validator;
/**
* Accepts http, https, ftp
*/
isUrl(): Validator;
/**
* Combines isIPv4 and isIPv6
*/
isIP(): Validator;
isIPv4(): Validator;
isIPv6(): Validator;
isAlpha(): Validator;
isAlphanumeric(): Validator;
isNumeric(): Validator;
isHexadecimal(): Validator;
/**
* Accepts valid hexcolors with or without # prefix
*/
isHexColor(): Validator;
/**
* isNumeric accepts zero padded numbers, e.g. '001', isInt doesn't
*/
isInt(): Validator;
isLowercase(): Validator;
isUppercase(): Validator;
isDecimal(): Validator;
/**
* Alias for isDecimal
*/
isFloat(): Validator;
/**
* Check if length is 0
*/
notNull(): Validator;
isNull(): Validator;
/**
* Not just whitespace (input.trim().length !== 0)
*/
notEmpty(): Validator;
equals(equals: any): Validator;
contains(str: string): Validator;
notContains(str: string): Validator;
/**
* Usage: regex(/[a-z]/i) or regex('[a-z]','i')
*/
regex(pattern: string, modifiers: string): Validator;
notRegex(pattern: string, modifiers: string): Validator;
/**
* max is optional
*/
len(min: number, max?: number): Validator;
/**
* Version can be 3, 4 or 5 or empty, see http://en.wikipedia.org/wiki/Universally_unique_identifier
*/
isUUID(version: number): Validator;
/**
* Alias for isUUID(3)
*/
isUUIDv3(): Validator;
/**
* Alias for isUUID(4)
*/
isUUIDv4(): Validator;
/**
* Alias for isUUID(5)
*/
isUUIDv5(): Validator;
/**
* Uses Date.parse() - regex is probably a better choice
*/
isDate(): Validator;
/**
* Argument is optional and defaults to today. Comparison is non-inclusive
*/
isAfter(date: Date): Validator;
/**
* Argument is optional and defaults to today. Comparison is non-inclusive
*/
isBefore(date: Date): Validator;
isIn(options: string): Validator;
isIn(options: string[]): Validator;
notIn(options: string): Validator;
notIn(options: string[]): Validator;
max(val: string): Validator;
min(val: string): Validator;
/**
* Will work against Visa, MasterCard, American Express, Discover, Diners Club, and JCB card numbering formats
*/
isCreditCard(): Validator;
}
interface Sanitizer {
/**
* Trim optional `chars`, default is to trim whitespace (\r\n\t )
*/
trim(...chars: string[]): Sanitizer;
ltrim(...chars: string[]): Sanitizer;
rtrim(...chars: string[]): Sanitizer;
ifNull(replace: any): Sanitizer;
toFloat(): Sanitizer;
toInt(): Sanitizer;
/**
* True unless str = '0', 'false', or str.length == 0
*/
toBoolean(): Sanitizer;
/**
* False unless str = '1' or 'true'
*/
toBooleanStrict(): Sanitizer;
/**
* Decode HTML entities
*/
entityDecode(): Sanitizer;
entityEncode(): Sanitizer;
/**
* Escape &, <, >, and "
*/
escape(): Sanitizer;
/**
* Remove common XSS attack vectors from user-supplied HTML
*/
xss(): Sanitizer;
/**
* Remove common XSS attack vectors from images
*/
xss(fromImages: boolean): Sanitizer;
}
}
declare function ExpressValidator(): void;
declare module "express-validator" {
export = ExpressValidator;
import express = require('express');
module ExpressValidator {
export interface ValidationError {
msg: string;
param: string;
}
export interface RequestValidation {
check(field:string, message:string): Validator;
assert(field:string, message:string): Validator;
sanitize(field:string): Sanitizer;
onValidationError(func:(msg:string) => void): void;
validationErrors() : any;
}
export interface Validator {
/**
* Alias for regex()
*/
is(): Validator;
/**
* Alias for notRegex()
*/
not(): Validator;
isEmail(): Validator;
/**
* Accepts http, https, ftp
*/
isUrl(): Validator;
/**
* Combines isIPv4 and isIPv6
*/
isIP(): Validator;
isIPv4(): Validator;
isIPv6(): Validator;
isAlpha(): Validator;
isAlphanumeric(): Validator;
isNumeric(): Validator;
isHexadecimal(): Validator;
/**
* Accepts valid hexcolors with or without # prefix
*/
isHexColor(): Validator;
/**
* isNumeric accepts zero padded numbers, e.g. '001', isInt doesn't
*/
isInt(): Validator;
isLowercase(): Validator;
isUppercase(): Validator;
isDecimal(): Validator;
/**
* Alias for isDecimal
*/
isFloat(): Validator;
/**
* Check if length is 0
*/
notNull(): Validator;
isNull(): Validator;
/**
* Not just whitespace (input.trim().length !== 0)
*/
notEmpty(): Validator;
equals(equals:any): Validator;
contains(str:string): Validator;
notContains(str:string): Validator;
/**
* Usage: regex(/[a-z]/i) or regex('[a-z]','i')
*/
regex(pattern:string, modifiers:string): Validator;
notRegex(pattern:string, modifiers:string): Validator;
/**
* max is optional
*/
len(min:number, max?:number): Validator;
/**
* Version can be 3, 4 or 5 or empty, see http://en.wikipedia.org/wiki/Universally_unique_identifier
*/
isUUID(version:number): Validator;
/**
* Alias for isUUID(3)
*/
isUUIDv3(): Validator;
/**
* Alias for isUUID(4)
*/
isUUIDv4(): Validator;
/**
* Alias for isUUID(5)
*/
isUUIDv5(): Validator;
/**
* Uses Date.parse() - regex is probably a better choice
*/
isDate(): Validator;
/**
* Argument is optional and defaults to today. Comparison is non-inclusive
*/
isAfter(date:Date): Validator;
/**
* Argument is optional and defaults to today. Comparison is non-inclusive
*/
isBefore(date:Date): Validator;
isIn(options:string): Validator;
isIn(options:string[]): Validator;
notIn(options:string): Validator;
notIn(options:string[]): Validator;
max(val:string): Validator;
min(val:string): Validator;
/**
* Will work against Visa, MasterCard, American Express, Discover, Diners Club, and JCB card numbering formats
*/
isCreditCard(): Validator;
}
interface Sanitizer {
/**
* Trim optional `chars`, default is to trim whitespace (\r\n\t )
*/
trim(...chars:string[]): Sanitizer;
ltrim(...chars:string[]): Sanitizer;
rtrim(...chars:string[]): Sanitizer;
ifNull(replace:any): Sanitizer;
toFloat(): Sanitizer;
toInt(): Sanitizer;
/**
* True unless str = '0', 'false', or str.length == 0
*/
toBoolean(): Sanitizer;
/**
* False unless str = '1' or 'true'
*/
toBooleanStrict(): Sanitizer;
/**
* Decode HTML entities
*/
entityDecode(): Sanitizer;
entityEncode(): Sanitizer;
/**
* Escape &, <, >, and "
*/
escape(): Sanitizer;
/**
* Remove common XSS attack vectors from user-supplied HTML
*/
xss(): Sanitizer;
/**
* Remove common XSS attack vectors from images
*/
xss(fromImages:boolean): Sanitizer;
}
}
/**
*
* @middlewareOptions see: https://github.com/ctavan/express-validator#middleware-options
*/
function ExpressValidator(middlewareOptions?:any):express.RequestHandler;
export = ExpressValidator;
}
+20 -1482
View File
File diff suppressed because it is too large Load Diff
+57 -841
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -335,6 +335,7 @@ declare module fabric {
drawBorders(context: CanvasRenderingContext2D): IObject;
drawCorners(context: CanvasRenderingContext2D): IObject;
get (property: string): any;
getBoundingRect(): {left:number; top:number; width:number; height:number};
getBoundingRectHeight(): number;
getBoundingRectWidth(): number;
getSvgStyles(): string;
+53
View File
@@ -0,0 +1,53 @@
/// <reference path="fingerprint.d.ts"/>
function test_no_option() {
var fingerprint = new Fingerprint().get();
}
function test_set_canvas_enabled() {
var fingerprint = new Fingerprint({canvas: true}).get();
}
function test_set_screen_resolution_enabled() {
var fingerprint = new Fingerprint({screen_resolution: true}).get();
}
function test_set_ie_activex_enabled() {
var fingerprint = new Fingerprint({ie_activex: true}).get();
}
function test_set_hasher_in_option() {
var my_hasher = (value: string, seed: number) => { return value.length % seed; };
var fingerprint = new Fingerprint({hasher: my_hasher}).get();
var fingerprint = new Fingerprint({hasher: (value, seed) => { return value.length % seed; }}).get();
}
function test_set_hasher_in_constructor() {
var my_hasher = (value: string, seed: number) => { return value.length % seed; };
var fingerprint = new Fingerprint(my_hasher).get();
var fingerprint = new Fingerprint((value, seed) => { return value.length % seed; }).get();
}
function test_call_methods() {
var f = new Fingerprint();
f.murmurhash3_32_gc("abcde", 123);
if (f.hasLocalStorage()) {
alert("LocalStorage");
}
if (f.hasSessionStorage()) {
alert("SessionStorage");
}
if (f.isCanvasSupported()) {
alert("CanvasSupported");
}
if (f.isIE()) {
alert("IE");
}
f.getPluginsString();
f.getRegularPluginsString();
f.getIEPluginsString();
f.getScreenResolution();
f.getCanvasFingerprint();
}
+99
View File
@@ -0,0 +1,99 @@
// Type definitions for fingerprintjs 0.5.4
// Project: https://github.com/Valve/fingerprintjs
// Definitions by: Shunsuke Ohtani <https://github.com/zaneli>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module FingerprintJs {
interface FingerprintStatic {
/**
* Create Fingerprint object.
*/
new(hasher: (key: string, seed: number) => number): Fingerprint;
new(option: FingerprintOption): Fingerprint;
new(): Fingerprint;
}
interface Fingerprint {
/**
* Generate fingerprint number.
*/
get(): number;
/**
* Generate fingerprint number using Murmur hashing.
* @param key ASCII only
* @param seed Positive integer only
*/
murmurhash3_32_gc(key: string, seed: number): number;
/**
* Check whether or not the browser has local storage.
*/
hasLocalStorage(): boolean;
/**
* Check whether or not the browser has session storage.
*/
hasSessionStorage(): boolean;
/**
* Check whether or not the browser supports canvas.
*/
isCanvasSupported(): boolean;
/**
* Check whether or not the browser is IE.
*/
isIE(): boolean;
/**
* Get plugins string.
*/
getPluginsString(): string;
/**
* Get plugins string from navigator plugins.
*/
getRegularPluginsString(): string;
/**
* Get plugins string from ActiveXObject.
*/
getIEPluginsString(): string;
/**
* Get screen height and width.
*/
getScreenResolution(): number[];
/**
* Get canvas data url string.
*/
getCanvasFingerprint(): string;
}
interface FingerprintOption {
/**
* If you want to use canvas fingerprinting, set true.
*/
canvas?: boolean;
/**
* If you want to use the screen resolution in calculating the fingerprint, set true.
*/
screen_resolution?: boolean;
/**
* If you want to query the IE plugins info to further diversify the fingerprinting process, set true.
*/
ie_activex?: boolean;
/**
* If you want to use custom hashing function, set function.
*/
hasher?: (key: string, seed: number) => number;
}
}
declare var Fingerprint: FingerprintJs.FingerprintStatic;
+1
View File
@@ -91,6 +91,7 @@ interface GlobalizeCulture {
isRTL: boolean;
language: string;
numberFormat: GlobalizeNumberFormat;
calendar: GlobalizeCalendar;
calendars: GlobalizeCalendars;
messages: any;
}
+1 -1
View File
@@ -7,7 +7,7 @@
// Version 1.1 (TypeScript 0.9)
interface IDispatcher {
addEventListener(type:string, callback:Function, scope:Object, useParam:boolean, priority:number):void;
addEventListener(type:string, callback:Function, scope?:Object, useParam?:boolean, priority?:number):void;
removeEventListener(type:string, callback:Function):void;
}
+43
View File
@@ -73,3 +73,46 @@ exports = (grunt: IGrunt) => {
fileMaps[0].src.length;
fileMaps[0].dest;
};
// Official grunt task template from
// https://github.com/gruntjs/grunt-init-gruntplugin/blob/master/root/tasks/name.js
exports.exports = function(grunt: IGrunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask('taskName', 'task description', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
punctuation: '.',
separator: ', '
});
// Iterate over all specified file groups.
this.files.forEach(function(f: grunt.file.IFilesConfig) {
// Concat specified files.
var src = f.src.filter(function(filepath: string) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
}).map(function(filepath) {
// Read file source.
return grunt.file.read(filepath);
}).join(grunt.util.normalizelf(options.separator));
// Handle options.
src += options.punctuation;
// Write the destination file.
grunt.file.write(f.dest, src);
// Print a success message.
grunt.log.writeln('File "' + f.dest + '" created.');
});
});
};
+5
View File
@@ -690,6 +690,11 @@ declare module grunt {
* Log a list of obj properties (good for debugging flags).
*/
writeflags(obj: any): T
/**
* Log an warning with grunt.log.warn
*/
warn(msg: string): T
}
/**
+6 -2
View File
@@ -37,9 +37,13 @@ interface HandlebarsStatic extends HandlebarsCommon {
compile(input: any, options?: any): HandlebarsTemplateDelegate;
}
interface HandlebarsRuntimeStatic extends HandlebarsCommon {
interface HandlebarsTemplates {
[index: string]: HandlebarsTemplateDelegate;
}
interface HandlebarsRuntimeStatic extends HandlebarsCommon {
// Handlebars.templates is the default template namespace in precompiler.
templates: { (s: string): HandlebarsTemplateDelegate }[];
templates: HandlebarsTemplates;
}
declare class SafeString {
+24
View File
@@ -0,0 +1,24 @@
/// <reference path="hashmap.d.ts"/>
var map : HashMap<string, number> = new HashMap<string, number>();
map.set("foo", 123);
var value : number = map.get("foo");
map.has("foo");
map.remove("foo");
var keys : string[] = map.keys();
var values : number[] = map.values();
var count : number = map.count();
map.forEach(function(value : number, key : string) : void {
console.log(key);
console.log(value);
});
map.clear();
+71
View File
@@ -0,0 +1,71 @@
// Type definitions for HashMap 1.1.0
// Project: https://github.com/flesler/hashmap
// Definitions by: Rafał Wrzeszcz <http://wrzasq.pl>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare class HashMap<KeyType, ValueType> {
/**
* Return value from hashmap.
*
* @param key Key.
* @return Value stored under given key.
*/
get(key : KeyType) : ValueType;
/**
* Store value in hashmap.
*
* @param key Key.
* @param value Value.
*/
set(key : KeyType, value : ValueType) : void;
/**
* Checks if given key exists in hashmap.
*
* @param key Key.
* @return Whether given key exists in hashmap.
*/
has(key : KeyType) : boolean;
/**
* Removes given key from hashmap.
*
* @param key Key.
*/
remove(key : KeyType) : void;
/**
* Returns all contained keys.
*
* @return List of keys.
*/
keys() : KeyType[];
/**
* Returns all container values.
*
* @return List of values.
*/
values() : ValueType[];
/**
* Returns size of hashmap (number of entries).
*
* @return Number of entries in hashmap.
*/
count() : number;
/**
* Clears hashmap.
*/
clear() : void;
/**
* Iterates over hashmap.
*
* @param callback Function to be invoked for every hashmap entry.
*/
forEach(callback : (value : ValueType, key : KeyType) => void) : void;
}
+24
View File
@@ -0,0 +1,24 @@
/// <reference path="htmlparser2.d.ts"/>
/**
* Created by staticfunction on 8/4/14.
*/
import htmlparser = require("htmlparser2");
var parser = new htmlparser.Parser({
onopentag: (name:string, attribs:{[s:string]:string}) => {
if(name === "script" && attribs['type'] === "text/javascript"){
console.log("JS! Hooray!");
}
},
ontext: (text: string) => {
console.log("-->", text);
},
onclosetag: (tagname:string) => {
if(tagname === "script"){
console.log("That's it?!");
}
}
});
parser.write("Xyz <script type='text/javascript'>var foo = '<<bar>>';</script>");
parser.end();
+89
View File
@@ -0,0 +1,89 @@
// Type definitions for htmlparser2 v3.7.x
// Project: https://github.com/fb55/htmlparser2/
// Definitions by: James Roland Cabresos <https://github.com/staticfunction/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "htmlparser2" {
export interface Handler {
onopentag?:(name:string, attribs:{[type:string]: string}) => void;
onopentagname?:(name:string) => void;
onattribute?:(name:string, value:string) => void;
ontext?:(text:string) => void;
onclosetag?: (text:string) => void;
onprocessinginstruction?:(name:string, data:string) => void;
oncomment?:(data:string) => void;
oncommentend?:() => void;
oncdatastart?:() => void;
oncdataend?:() => void;
onerror?:(error:Error) => void;
onreset?:() => void;
onend?:() => void;
}
export interface Options {
/***
* Indicates whether special tags (<script> and <style>) should get special treatment
* and if "empty" tags (eg. <br>) can have children. If false, the content of special tags
* will be text only. For feeds and other XML content (documents that don't consist of HTML),
* set this to true. Default: false.
*/
xmlMode?:boolean;
/***
* If set to true, entities within the document will be decoded. Defaults to false.
*/
decodeEntities?:boolean;
/***
* If set to true, all tags will be lowercased. If xmlMode is disabled, this defaults to true.
*/
lowerCaseTags?:boolean;
/***
* If set to true, all attribute names will be lowercased. This has noticeable impact on speed, so it defaults to false.
*/
lowerCaseAttributeNames?:boolean;
/***
* If set to true, CDATA sections will be recognized as text even if the xmlMode option is not enabled.
* NOTE: If xmlMode is set to true then CDATA sections will always be recognized as text.
*/
recognizeCDATA?:boolean;
/***
* If set to true, self-closing tags will trigger the onclosetag event even if xmlMode is not set to true.
* NOTE: If xmlMode is set to true then self-closing tags will always be recognized.
*/
recognizeSelfClosing?:boolean;
}
export class Parser {
constructor(handler: Handler);
/***
* Parses a chunk of data and calls the corresponding callbacks.
* @param input
*/
write(input:string):void;
/***
* Parses the end of the buffer and clears the stack, calls onend.
*/
end():void;
/***
* Resets the parser, parses the data & calls end.
* @param input
*/
parseComplete(input:string):void;
/***
* Resets buffer & stack, calls onreset.
*/
reset():void;
}
}
@@ -0,0 +1,42 @@
/// <reference path="http-string-parser.d.ts" />
import parser = require("http-string-parser");
function test_request(): void {
var result = parser.parseRequest("HTTP/1.1 GET /\r\nHost: www.example.com\r\n\r\n");
var body: string = result.body;
var headers: { [key: string]: string } = result.headers;
var method: string = result.method;
var uri: string = result.uri;
}
function test_response(): void {
var response = parser.parseResponse("HTTP/1.1 200 OK\r\n\r\n");
var body: string = response.body;
var headers: { [key: string]: string } = response.headers;
var statusCode: string = response.statusCode;
var statusMessage: string = response.statusMessage;
}
function test_requestLine(): void {
var result = parser.parseRequestLine("HTTP/1.1 GET /");
var method: string = result.method;
var protocol: string = result.protocol;
var uri: string = result.uri;
}
function test_statusLine(): void {
var result = parser.parseStatusLine("HTTP/1.1 200 OK");
var protocol: string = result.protocol;
var statusCode: string = result.statusCode;
var statusMessage: string = result.statusMessage;
}
function test_headers(): void {
var result: { [key: string]: string } =
parser.parseHeaders("Content-Type: text/html; charset=utf-8\r\nContent-Length: 256\r\n");
}
+38
View File
@@ -0,0 +1,38 @@
// Type definitions for http-string-parser
// Project: https://github.com/apiaryio/http-string-parser
// Definitions by: MIZUNE Pine <https://github.com/pine613>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "http-string-parser" {
interface ParseRequestResult {
method: string;
uri: string;
headers: { [key: string]: string };
body: string;
}
interface ParseResponseResult {
statusCode: string;
statusMessage: string;
headers: { [key: string]: string };
body: string;
}
interface ParseRequestLineResult {
method: string;
uri: string;
protocol: string;
}
interface ParseStatusLineResult {
protocol: string;
statusCode: string;
statusMessage: string;
}
export function parseRequest(requestString: string): ParseRequestResult;
export function parseResponse(responseString: string): ParseResponseResult;
export function parseRequestLine(requestLineString: string): ParseRequestLineResult;
export function parseStatusLine(statusLine: string): ParseStatusLineResult;
export function parseHeaders(headerLines: string): { [key: string]: string };
}
+38
View File
@@ -0,0 +1,38 @@
/// <reference path="../jquery/jquery.d.ts"/>
/// <reference path="ion.rangeSlider.d.ts"/>
var sliderInputElement = $('<input />');
sliderInputElement.ionRangeSlider({
min: 10,
max: 100,
from: 30,
to: 80,
type: "single",
step: 10,
prefix: "$",
postfix: ".00",
maxPostfix: "+",
hasGrid: true,
hideMinMax: true,
hideFromTo: true,
prettify: true,
disable: false,
values: ["a", "b", "c"],
onLoad: function (obj) {
console.log(obj);
},
onChange: function (obj) {
console.log(obj);
},
onFinish: function (obj) {
console.log(obj);
}
});
sliderInputElement.ionRangeSlider("update", {
min: 20,
max: 90,
from: 40,
to: 70,
step: 5
});
sliderInputElement.ionRangeSlider("remove");
+51
View File
@@ -0,0 +1,51 @@
// Type definitions for for Ion.RangeSlider 1.9.1
// Project: https://github.com/IonDen/ion.rangeSlider/
// Definitions by: Douglas Eichelberger <https://github.com/dduugg>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// API documentation: http://ionden.com/a/plugins/ion.rangeSlider/en.html
interface JQuery {
ionRangeSlider(): JQuery;
ionRangeSlider(options: IonRangeSliderOptions): JQuery;
ionRangeSlider(method: string): JQuery;
ionRangeSlider(method: string, options: IonRangeSliderOptions): JQuery;
}
interface IonRangeSliderOptions {
disable?: boolean;
from?: number;
hasGrid?: boolean;
hideFromTo?: boolean;
hideMinMax?: boolean;
max?: number;
maxPostfix?: string;
min?: number;
onChange?: (obj: IonRangeSliderEvent) => void;
onFinish?: (obj: IonRangeSliderEvent) => void;
onLoad?: (obj: IonRangeSliderEvent) => void;
postfix?: string;
prefix?: string;
prettify?: boolean;
step?: number;
to?: number;
type?: string;
values?: any[];
}
interface IonRangeSliderEvent {
fromNumber: number;
fromPers: number;
fromValue?: any;
fromX: number;
fromX_pure?: number;
input: JQuery;
max: number;
min: number;
slider: JQuery;
toNumber: number;
toPers: number;
toValue?: number;
toX: number;
toX_pure?: number;
}
@@ -0,0 +1,54 @@
/// <reference path="jasmine-data_driven_tests.d.ts" />
/// <reference path="../jasmine/jasmine.d.ts" />
all("A data driven test is a suite with multiple specs",
['a', 'b', 'c'],
(value: string) => {
expect(value).not.toBe('d');
}
);
all("A data driven test can have many arguments",
[
[1, 2, 3],
[2, 4, 6]
],
(a: number, b: number, c: number) => {
expect(c - (a + b)).toBe(0);
}
);
all("A data driven test can be asynchronous",
[
[3, 1],
[5, 2]
],
(a: number, b: number, done: () => void) => {
setTimeout(() => {
expect(a - b > 0).toBe(true);
done();
}, 50);
}
);
xall("A data driven test can be pending",
[1, 2, 3],
(value: number) => {
expect(value < 4).toBe(true);
}
);
describe("A suite", () => {
var a: number;
beforeEach(() => {
a = 5;
});
all("can contain data driven tests",
[1, 2, 3],
(b: number) => {
expect(a - b > 0).toBe(true);
}
);
});
@@ -0,0 +1,7 @@
// Type definitions for Jasmine Data Driven Tests
// Project: https://github.com/gburghardt/jasmine-data_driven_tests
// Definitions by: Anthony MacKinnon <https://github.com/AnthonyMacKinnon>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare function all(description: string, dataset: any[], assertion: (...args: any[]) => void): void;
declare function xall(description: string, dataset: any[], assertion: (...args: any[]) => void): void;
+1 -5
View File
@@ -1,6 +1,6 @@
// Type definitions for jQuery 1.10.x / 2.0.x
// Project: http://jquery.com/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, Christian Hoffmeister <https://github.com/choffmeister>, Steve Fenton <https://github.com/Steve-Fenton>, Diullei Gomes <https://github.com/Diullei>, Tass Iliopoulos <https://github.com/tasoili>, Jason Swearingen <https://github.com/jasons-novaleaf>, Sean Hill <https://github.com/seanski>, Guus Goossens <https://github.com/Guuz>, Kelly Summerlin <https://github.com/ksummerlin>, Basarat Ali Syed <https://github.com/basarat>, Nicholas Wolverson <https://github.com/nwolverson>, Derek Cicerone <https://github.com/derekcicerone>, Andrew Gaspar <https://github.com/AndrewGaspar>, James Harrison Fisher <https://github.com/jameshfisher>, Seikichi Kondo <https://github.com/seikichi>, Benjamin Jackman <https://github.com/benjaminjackman>, Poul Sorensen <https://github.com/s093294>, Josh Strobl <https://github.com/JoshStrobl>, John Reilly <https://github.com/johnnyreilly/>
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, Christian Hoffmeister <https://github.com/choffmeister>, Steve Fenton <https://github.com/Steve-Fenton>, Diullei Gomes <https://github.com/Diullei>, Tass Iliopoulos <https://github.com/tasoili>, Jason Swearingen <https://github.com/jasons-novaleaf>, Sean Hill <https://github.com/seanski>, Guus Goossens <https://github.com/Guuz>, Kelly Summerlin <https://github.com/ksummerlin>, Basarat Ali Syed <https://github.com/basarat>, Nicholas Wolverson <https://github.com/nwolverson>, Derek Cicerone <https://github.com/derekcicerone>, Andrew Gaspar <https://github.com/AndrewGaspar>, James Harrison Fisher <https://github.com/jameshfisher>, Seikichi Kondo <https://github.com/seikichi>, Benjamin Jackman <https://github.com/benjaminjackman>, Poul Sorensen <https://github.com/s093294>, Josh Strobl <https://github.com/JoshStrobl>, John Reilly <https://github.com/johnnyreilly/>, Dick van den Brink <https://github.com/DickvdBrink>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/* *****************************************************************************
@@ -525,10 +525,6 @@ interface JQueryDeferred<T> extends JQueryPromise<T> {
* @param args An optional array of arguments that are passed to the doneCallbacks.
*/
resolveWith(context: any, ...args: any[]): JQueryDeferred<T>;
/**
* Determine the current state of a Deferred object.
*/
state(): string;
/**
* Return a Deferred's Promise object.
+5 -1
View File
@@ -3,7 +3,7 @@
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module 'js-yaml' {
declare module jsyaml {
export function safeLoad(str: string, opts?: LoadOptions): any;
export function load(str: string, opts?: LoadOptions): any;
@@ -46,3 +46,7 @@ declare module 'js-yaml' {
// all supported YAML types.
export var DEFAULT_FULL_SCHEMA: any;
}
declare module 'js-yaml' {
export = jsyaml;
}
+93
View File
@@ -0,0 +1,93 @@
/// <reference path="jsbn.d.ts" />
var BigInteger = jsbn.BigInteger;
// constructor tests
var x = new BigInteger("AABB", 16);
x = new BigInteger("75643564363473453456342378564387956906736546456235345");
// method tests
var isBigInteger: jsbn.BigInteger;
var isNumber: number;
var isBoolean: boolean;
var isString: string;
var isDivmod: jsbn.BigInteger[];
var isByteArray: number[];
x.copyTo(x);
x.fromInt(0);
x.fromString("CAFEBABE", 16);
x.clamp();
isString = x.toString();
isString = x.toString(16);
isBigInteger = x.negate();
isBigInteger = x.abs();
isNumber = x.compareTo(x);
isNumber = x.bitLength();
x.dlShiftTo(0, isBigInteger);
x.drShiftTo(0, isBigInteger);
x.lShiftTo(0, isBigInteger);
x.rShiftTo(0, isBigInteger);
x.subTo(x, isBigInteger);
x.multiplyTo(x, isBigInteger);
x.squareTo(isBigInteger);
x.divRemTo(x, isBigInteger, isBigInteger);
isBigInteger = x.mod(x);
isNumber = x.invDigit();
isBoolean = x.isEven();
isBigInteger = x.exp(0, {
convert: (x) => x,
revert: (x) => x,
reduce: (x) => x,
mulTo: (x) => x,
sqrTo: (x) => x
});
isBigInteger = x.modPowInt(0, x);
isBigInteger = x.clone();
isNumber = x.intValue();
isNumber = x.byteValue();
isNumber = x.shortValue();
isNumber = x.chunkSize(0);
isNumber = x.signum();
isString = x.toRadix(10);
x.fromRadix("123", 10);
x.fromNumber(1);
x.fromNumber(1, 2);
x.fromNumber(1, 2, 3);
isByteArray = x.toByteArray();
isBoolean = x.equals(x);
isBigInteger = x.min(x);
isBigInteger = x.max(x);
x.bitwiseTo(x, (x, y) => x + y, isBigInteger);
isBigInteger = x.and(x);
isBigInteger = x.or(x);
isBigInteger = x.xor(x);
isBigInteger = x.andNot(x);
isBigInteger = x.not();
isBigInteger = x.shiftLeft(0);
isBigInteger = x.shiftRight(0);
isNumber = x.getLowestSetBit();
isNumber = x.bitCount();
isBoolean = x.testBit(0);
isBigInteger = x.changeBit(0, (x, y) => x * y);
isBigInteger = x.setBit(0);
isBigInteger = x.clearBit(0);
isBigInteger = x.flipBit(0);
x.addTo(x, isBigInteger);
isBigInteger = x.add(x);
isBigInteger = x.subtract(x);
isBigInteger = x.multiply(x);
isBigInteger = x.square();
isBigInteger = x.divide(x);
isBigInteger = x.remainder(x);
isDivmod = x.divideAndRemainder(x);
x.dMultiply(0);
x.dAddOffset(0, 0);
isBigInteger = x.pow(0);
x.multiplyLowerTo(x, 0, isBigInteger);
x.multiplyUpperTo(x, 0, isBigInteger);
isBigInteger = x.modPow(x, x);
isBigInteger = x.gcd(x);
isNumber = x.modInt(0);
isBigInteger = x.modInverse(x);
isBoolean = x.isProbablePrime(0);
isBoolean = x.millerRabin(0);
+250
View File
@@ -0,0 +1,250 @@
// Type definitions for jsbn v1.2
// Project: http://www-cs-students.stanford.edu/%7Etjw/jsbn/
// Definitions by: Eugene Chernyshov <https://github.com/Evgenus>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module jsbn {
interface RandomGenerator {
nextBytes(bytes: number[]): void;
}
export class BigInteger {
constructor(a: number, c: RandomGenerator);
constructor(a: number, b: number, c: RandomGenerator);
constructor(a: string, b?: number);
constructor(a: number[], b?: number);
constructor(a: BigInteger);
s: number;
t: number;
data: number[]; // forge specific
DB: number;
DM: number;
DV: number;
FV: number;
F1: number;
F2: number;
// am: Compute w_j += (x*this_i), propagate carries,
am(i: number, x: number, w: BigInteger, j: number, c: number, n: number): number;
// (protected) copy this to r
copyTo(r: BigInteger): void;
// (protected) set from integer value x, -DV <= x < DV
fromInt(x: number): void;
// (protected) set from string and radix
fromString(x: string, b: number): void;
// (protected) clamp off excess high words
clamp(): void;
// (public) return string representation in given radix
toString(b?: number): string;
// (public) -this
negate(): BigInteger;
// (public) |this|
abs(): BigInteger;
// (public) return + if this > a, - if this < a, 0 if equal
compareTo(a: BigInteger): number;
// (public) return the number of bits in "this"
bitLength(): number;
// (protected) r = this << n*DB
dlShiftTo(n: number, r: BigInteger): void;
// (protected) r = this >> n*DB
drShiftTo(n: number, r: BigInteger): void;
// (protected) r = this << n
lShiftTo(n: number, r: BigInteger): void;
// (protected) r = this >> n
rShiftTo(n: number, r: BigInteger): void;
// (protected) r = this - a
subTo(a: BigInteger, r: BigInteger): void;
// (protected) r = this * a, r != this,a (HAC 14.12)
multiplyTo(a: BigInteger, r: BigInteger): void;
// (protected) r = this^2, r != this (HAC 14.16)
squareTo(r: BigInteger): void;
// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
// r != q, this != m. q or r may be null.
divRemTo(m: BigInteger, q: BigInteger, r: BigInteger): void;
// (public) this mod a
mod(a: BigInteger): BigInteger;
// (protected) return "-1/this % 2^DB"; useful for Mont. reduction
invDigit(): number;
// (protected) true iff this is even
isEven(): boolean;
// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
exp(e: number, z: Reduction): BigInteger;
// (public) this^e % m, 0 <= e < 2^32
modPowInt(e: number, m: BigInteger): BigInteger;
// (public)
clone(): BigInteger;
// (public) return value as integer
intValue(): number;
// (public) return value as byte
byteValue(): number;
// (public) return value as short (assumes DB>=16)
shortValue(): number;
// (protected) return x s.t. r^x < DV
chunkSize(r: number): number;
// (public) 0 if this == 0, 1 if this > 0
signum(): number;
// (protected) convert to radix string
toRadix(b: number): string;
// (protected) convert from radix string
fromRadix(s: string, b: number): void;
// (protected) alternate constructor
fromNumber(a: number, b?: number, c?: number): void;
// (public) convert to bigendian byte array
toByteArray(): number[];
equals(a: BigInteger): boolean;
min(a: BigInteger): BigInteger;
max(a: BigInteger): BigInteger;
// (protected) r = this op a (bitwise)
bitwiseTo(a: BigInteger, op: (x: number, y: number) => number, r: BigInteger): void;
// (public) this & a
and(a: BigInteger): BigInteger;
// (public) this | a
or(a: BigInteger): BigInteger;
// (public) this ^ a
xor(a: BigInteger): BigInteger;
// (public) this & ~a
andNot(a: BigInteger): BigInteger;
// (public) ~this
not(): BigInteger;
// (public) this << n
shiftLeft(n: number): BigInteger;
// (public) this >> n
shiftRight(n: number): BigInteger;
// (public) returns index of lowest 1-bit (or -1 if none)
getLowestSetBit(): number;
// (public) return number of set bits
bitCount(): number;
// (public) true iff nth bit is set
testBit(n: number): boolean;
// (protected) this op (1<<n)
changeBit(n: number, op: (x: number, y: number) => number): BigInteger;
// (protected) this op (1<<n)
setBit(n: number): BigInteger;
// (public) this & ~(1<<n)
clearBit(n: number): BigInteger
// (public) this ^ (1<<n)
flipBit(n: number): BigInteger
// (protected) r = this + a
addTo(a: BigInteger, r: BigInteger): void;
// (public) this + a
add(a: BigInteger): BigInteger;
// (public) this - a
subtract(a: BigInteger): BigInteger;
// (public) this * a
multiply(a: BigInteger): BigInteger;
// (public) this^2
square(): BigInteger;
// (public) this / a
divide(a: BigInteger): BigInteger;
// (public) this % a
remainder(a: BigInteger): BigInteger;
// (public) [this/a,this%a]
divideAndRemainder(a: BigInteger): BigInteger[]; // Array of 2 items
// (protected) this *= n, this >= 0, 1 < n < DV
dMultiply(n: number): void;
// (protected) this += n << w words, this >= 0
dAddOffset(n: number, w: number): void;
// (public) this^e
pow(e: number): BigInteger;
// (protected) r = lower n words of "this * a", a.t <= n
multiplyLowerTo(a: BigInteger, n: number, r: BigInteger): void;
// (protected) r = "this * a" without lower n words, n > 0
multiplyUpperTo(a: BigInteger, n: number, r: BigInteger): void;
// (public) this^e % m (HAC 14.85)
modPow(e: BigInteger, m: BigInteger): BigInteger;
// (public) gcd(this,a) (HAC 14.54)
gcd(a: BigInteger): BigInteger;
// (protected) this % n, n < 2^26
modInt(n: number): number;
// (public) 1/this % m (HAC 14.61)
modInverse(m: BigInteger): BigInteger;
// (public) test primality with certainty >= 1-.5^t
isProbablePrime(t: number): boolean;
// (protected) true if probably prime (HAC 4.24, Miller-Rabin)
millerRabin(t: number): boolean;
static ZERO: BigInteger;
static ONE: BigInteger;
}
interface Reduction {
convert(x: BigInteger): BigInteger;
revert(x: BigInteger): BigInteger;
reduce(x: BigInteger): void;
mulTo(x: BigInteger, y: BigInteger, r: BigInteger): void;
sqrTo(x: BigInteger, r: BigInteger): void;
}
}
+301
View File
@@ -0,0 +1,301 @@
/// <reference path="leaflet.d.ts" />
// initialize the map on the "map" div with a given center and zoom
var div = document.getElementById('map');
var map : L.Map = L.map(div, {
center: L.latLng([51.505, -0.09]),
zoom: 13,
minZoom: 3,
maxZoom: 8,
maxBounds: L.latLngBounds([L.latLng(-60, -60), L.latLng(60, 60)]),
dragging: true,
touchZoom: true,
scrollWheelZoom: true,
boxZoom: true,
tap: true,
tapTolerance: 30,
trackResize: true,
worldCopyJump: false,
closePopupOnClick: true,
bounceAtZoomLimits: true,
keyboard: true,
keyboardPanOffset: 80,
keyboardZoomOffset: 1,
inertia: true,
inertiaDeceleration: 3000,
inertiaMaxSpeed: 1500,
inertiaThreshold: 32,
zoomControl: true,
attributionControl: true,
fadeAnimation: true,
zoomAnimation: true,
zoomAnimationThreshold: 4,
markerZoomAnimation: true
});
map.dragging.enable();
map.touchZoom.enable();
map.scrollWheelZoom.enable();
map.doubleClickZoom.enable();
map.boxZoom.enable();
map.tap.enable();
map.setView(new L.LatLng(42, 51));
map.setView(L.latLng(42, 51));
map.setView(L.latLng(42, 51), 12);
map.setView(L.latLng(42, 51), 12, {
reset: true,
pan: {
animate: true,
duration: 0.25,
easeLinearity: 0.25,
noMoveStart: false
},
zoom: {
animate: true
}
});
map.setZoom(50);
map.setZoom(50, {});
map.zoomIn();
map.zoomOut();
map.zoomIn(2);
map.zoomOut(2);
map.zoomIn(2, { animate: true });
map.zoomOut(2, { animate: true });
map.setZoomAround(L.latLng(42, 51), 8, { animate: false });
map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20)));
map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20)), {
paddingTopLeft: L.point(20, 20),
paddingBottomRight: L.point(20, 20),
padding: L.point(0, 0),
maxZoom: null
});
map.fitWorld();
map.fitWorld({
animate: false
});
map.panTo(L.latLng(42, 42));
map.panTo(L.latLng(42, 42), {
animate: true
});
map.invalidateSize(true);
map.invalidateSize({ reset: true });
map.setMaxBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20)));
map.locate();
map.locate({
watch: false,
setView: false,
maxZoom: 18,
timeout: 10000,
maximumAge: 0,
enableHighAccuracy: false
});
map.stopLocate();
map.remove();
var center : L.LatLng = map.getCenter();
var zoom : number = map.getZoom();
var minZoom: number = map.getMinZoom();
var maxZoom: number = map.getMaxZoom();
var bounds: L.LatLngBounds = map.getBounds();
var boundsZoom: number = map.getBoundsZoom(bounds, true);
var size: L.Point = map.getSize();
var pixelBounds: L.Bounds = map.getPixelBounds();
var pixelOrigin: L.Point = map.getPixelOrigin();
var layer = L.tileLayer("http://{s}.example.net/{x}/{y}/{z}.png");
map.addLayer(layer);
map.addLayer(layer, false);
map.removeLayer(layer);
map.hasLayer(layer);
map.openPopup("canard", L.latLng(42, 51));
var popup = L.popup({
autoPan: true
});
map.openPopup(popup);
map.closePopup(popup);
map.closePopup();
map.addControl(L.control.attribution({position: 'bottomright'}));
map.removeControl(L.control.attribution({ position: 'bottomright' }));
map.latLngToLayerPoint(map.layerPointToLatLng(L.point(0, 0)));
map.latLngToContainerPoint(map.containerPointToLatLng(L.point(0, 0)));
map.containerPointToLayerPoint(L.point(0, 0));
map.layerPointToContainerPoint(L.point(0, 0));
map.project(map.unproject(L.point(10, 20)));
map.project(map.unproject(L.point(10, 20), 12), 12);
var mouseEvent: L.LeafletMouseEvent;
map.mouseEventToContainerPoint(mouseEvent);
map.mouseEventToLayerPoint(mouseEvent);
map.mouseEventToLatLng(mouseEvent);
map.getContainer().classList.add('roger');
map.getPanes().mapPane.classList.add('roger');
map.getPanes().markerPane.classList.add('roger');
map.getPanes().objectsPane.classList.add('roger');
map.getPanes().overlayPane.classList.add('roger');
map.getPanes().popupPane.classList.add('roger');
map.getPanes().shadowPane.classList.add('roger');
map.getPanes().tilePane.classList.add('roger');
map.whenReady((m: L.Map) => {
m.zoomOut();
});
map.on('click', () => {
map.zoomOut();
});
map.off('dblclick', L.Util.falseFn);
map.once('contextmenu', (e: L.LeafletMouseEvent) => {
map.openPopup('contextmenu', e.latlng);
});
var marker = L.marker(L.latLng(42, 51), {
icon: L.icon({
iconURl: 'roger.png',
iconRetinaUrl: 'roger-retina.png',
iconSize: L.point(40, 40),
iconAnchor: L.point(20, 0),
shadowUrl: 'roger-shadow.png',
shadowRetinaUrl: 'roger-shadow-retina.png',
shadowSize: L.point(44, 44),
shadowAnchor: L.point(22, 0),
popupAnchor: L.point(0, 0),
className: 'roger-icon'
}),
clickable: true,
draggable: false,
keyboard: true,
title: 'this is an icon',
alt: '',
zIndexOffset: 0,
opacity: 1.0,
riseOnHover: false,
riseOffset: 250
});
marker.addTo(map);
marker.on('click', (e: L.LeafletMouseEvent) => {
map.setView(e.latlng);
});
marker.once('mouseover', () => {
marker.openPopup();
})
marker.setLatLng(marker.getLatLng());
marker.setIcon(L.icon({}));
marker.setZIndexOffset(30);
marker.setOpacity(0.8);
marker.bindPopup(popup);
marker.unbindPopup();
marker.bindPopup('hello', {
closeOnClick: true
});
marker.openPopup();
marker.closePopup();
marker.togglePopup();
marker.togglePopup();
marker.setPopupContent('hello 3')
marker.getPopup().setContent('hello 2');
marker.update();
marker.toGeoJSON();
marker.dragging.enable();
popup = L.popup({
maxWidth: 300,
minWidth: 50,
maxHeight: null,
autoPan: true,
keepInView: false,
closeButton: true,
offset: L.point(0, 6),
autoPanPaddingTopLeft: null,
autoPanPaddingBottomRight: L.point(20, 20),
autoPanPadding: L.point(5, 5),
zoomAnimation: true,
closeOnClick: null,
className: 'roger'
});
popup.setLatLng(L.latLng(12, 54)).setContent('this is nice popup').openOn(map);
popup.update();
var tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}', {
foo: 'bar',
minZoom: 0,
maxZoom: 18,
maxNativeZoom: 17,
tileSize: 256,
subdomains: ['a','b','c'],
errorTileUrl: '',
attribution: '',
tms: false,
continuousWorld: false,
noWrap: false,
zoomOffset: 0,
zoomReverse: false,
opacity: 1.0,
zIndex: null,
unloadInvisibleTiles: false,
updateWhenIdle: false,
detectRetina: true,
reuseTiles: true,
bounds: null
});
tileLayer.on('loading', L.Util.falseFn)
.off('loading', L.Util.falseFn)
.once('tileload', L.Util.falseFn);
tileLayer.addTo(map);
tileLayer.bringToBack()
.bringToFront()
.setOpacity(0.7)
.setZIndex(9)
.redraw()
.setUrl('http://perdu.com')
.getContainer();
+164 -9
View File
@@ -1,4 +1,4 @@
// Type definitions for Leaflet.js 0.6.4
// Type definitions for Leaflet.js 0.7.3
// Project: https://github.com/Leaflet/Leaflet
// Definitions by: Vladimir Zotov <https://github.com/rgripper>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -570,11 +570,13 @@ declare module L {
* inside the listener will point to context, or to the element if not specified.
*/
static addListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent;
static on(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent;
/**
* Removes an event listener from the element.
*/
static removeListener(el: HTMLElement, type: string, fn: (e: Event) => void): DomEvent;
static removeListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent;
static off(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent;
/**
* Stop the given event from propagation to parent elements. Used inside the
@@ -870,6 +872,13 @@ declare module L {
* Default value: [0, 0].
*/
padding?: Point;
/**
* The maximum possible zoom to use.
*
* Default value: null
*/
maxZoom?: number;
}
}
@@ -1128,6 +1137,11 @@ declare module L {
* Mercator-based CRS.
*/
scale(zoom: number): number;
/**
* Returns the size of the world in pixels for a particular zoom.
*/
getSize(zoom: number): Point;
}
}
@@ -1231,6 +1245,10 @@ declare module L {
*/
enabled(): boolean;
}
export class Handler extends Class {
initialize(map: Map): void;
}
}
declare module L {
@@ -1251,6 +1269,15 @@ declare module L {
onRemove(map: Map): void;
}
}
declare module L {
export module Mixin {
export interface LeafletMixinEvents extends IEventPowered<LeafletMixinEvents> {
}
export var Events: LeafletMixinEvents;
}
}
declare module L {
@@ -1277,6 +1304,11 @@ declare module L {
* Sets the opacity of the overlay.
*/
setOpacity(opacity: number): ImageOverlay;
/**
* Changes the URL of the image.
*/
setUrl(imageUrl: string): ImageOverlay;
/**
* Brings the layer to the top of all overlays.
@@ -1802,6 +1834,17 @@ declare module L {
popup: Popup;
}
}
declare module L {
export interface LeafletDragEndEvent extends LeafletEvent {
/**
* The distance in pixels the draggable element was moved by.
*/
distance: number;
}
}
declare module L {
@@ -1960,7 +2003,7 @@ declare module L {
* Sets the view of the map (geographical center and zoom) with the given
* animation options.
*/
setView(center: LatLng, zoom: number, options?: ZoomPanOptions): Map;
setView(center: LatLng, zoom?: number, options?: ZoomPanOptions): Map;
/**
* Sets the zoom of the map.
@@ -2142,7 +2185,7 @@ declare module L {
/**
* Closes the popup previously opened with openPopup (or the given one).
*/
closePopup(): Map;
closePopup(popup?: Popup): Map;
/**
* Adds the given control to the map.
@@ -2370,17 +2413,26 @@ declare module L {
/**
* Whether the map can be zoomed by using the mouse wheel.
* If passed 'center', it will zoom to the center of the view regardless of
* where the mouse was.
*
* Default value: true.
*/
scrollWheelZoom?: boolean;
scrollWheelZoom?: any;
//scrollWheelZoom?: boolean;
//scrollWheelZoom?: string;
/**
* Whether the map can be zoomed in by double clicking on it.
* Whether the map can be zoomed in by double clicking on it and zoomed out
* by double clicking while holding shift.
* If passed 'center', double-click zoom will zoom to the center of the view
* regardless of where the mouse was.
*
* Default value: true.
*/
doubleClickZoom?: boolean;
doubleClickZoom?: string;
//doubleClickZoom?: boolean;
//doubleClickZoom?: string;
/**
* Whether the map can be zoomed to a rectangular area specified by dragging
@@ -2529,6 +2581,14 @@ declare module L {
* in all browsers that support CSS3 Transitions except Android.
*/
markerZoomAnimation?: boolean;
/**
* Set it to false if you don't want the map to zoom beyond min/max zoom
* and then bounce back when pinch-zooming.
*
* Default value: true.
*/
bounceAtZoomLimits?: boolean;
}
}
@@ -2652,6 +2712,11 @@ declare module L {
* Opens the popup previously bound by the bindPopup method.
*/
openPopup(): Marker;
/**
* Returns the popup previously bound by the bindPopup method.
*/
getPopup(): Popup;
/**
* Closes the bound popup of the marker if it's opened.
@@ -2676,7 +2741,12 @@ declare module L {
/**
* Returns a GeoJSON representation of the marker (GeoJSON Point Feature).
*/
toGeoJSON(popup: Popup, options?: PopupOptions): any;
toGeoJSON(): any;
/**
* Marker dragging handler (by both mouse and touch).
*/
dragging: IHandler;
////////////
////////////
@@ -2752,6 +2822,13 @@ declare module L {
* Default value: ''.
*/
title?: string;
/**
* Text for the alt attribute of the icon image (useful for accessibility).
*
* Default value: ''.
*/
alt?: string;
/**
* By default, marker images zIndex is set automatically based on its latitude.
@@ -2814,6 +2891,11 @@ declare module L {
*/
getLatLngs(): LatLng[][];
/**
* Opens the popup previously bound by bindPopup.
*/
openPopup(): MultiPolygon;
/**
* Returns a GeoJSON representation of the multipolygon (GeoJSON MultiPolygon Feature).
*/
@@ -2848,6 +2930,11 @@ declare module L {
*/
getLatLngs(): LatLng[][];
/**
* Opens the popup previously bound by bindPopup.
*/
openPopup(): MultiPolyline;
/**
* Returns a GeoJSON representation of the multipolyline (GeoJSON MultiLineString Feature).
*/
@@ -3076,6 +3163,20 @@ declare module L {
* layers (e.g. Android 2).
*/
dashArray?: string;
/**
* A string that defines shape to be used at the end of the stroke.
*
* Default: null.
*/
lineCap?: string;
/**
* A string that defines shape to be used at the corners of the stroke.
*
* Default: null.
*/
lineJoin?: string;
/**
* If false, the vector will not emit mouse events and will act as a part of the
@@ -3089,6 +3190,13 @@ declare module L {
* Sets the pointer-events attribute on the path if SVG backend is used.
*/
pointerEvents?: boolean;
/**
* Custom class name set on an element.
*
* Default value: ''.
*/
className?: string;
}
}
@@ -3308,7 +3416,12 @@ declare module L {
* Sets the geographical point where the popup will open.
*/
setLatLng(latlng: LatLng): Popup;
/**
* Returns the geographical point of popup.
*/
getLatLng(): LatLng;
/**
* Sets the HTML content of the popup.
*/
@@ -3319,6 +3432,12 @@ declare module L {
*/
setContent(el: HTMLElement): Popup;
/**
* Returns the content of the popup.
*/
getContent(): HTMLElement;
//getContent(): string;
////////////
////////////
/**
@@ -3333,6 +3452,12 @@ declare module L {
* the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer).
*/
onRemove(map: Map): void;
/**
* Updates the popup content, layout and position. Useful for updating the popup after
* something inside changed, e.g. image loaded.
*/
update(): Popup;
}
}
@@ -3382,6 +3507,22 @@ declare module L {
* Default value: new Point(0, 6).
*/
offset?: Point;
/**
* The margin between the popup and the top left corner of the map view after
* autopanning was performed.
*
* Default value: null.
*/
autoPanPaddingTopLeft?: Point;
/**
* The margin between the popup and the bottom right corner of the map view after
* autopanning was performed.
*
* Default value: null.
*/
autoPanPaddingBottomRight?: Point;
/**
* The margin between the popup and the edges of the map view after autopanning
@@ -3695,6 +3836,15 @@ declare module L {
* Default value: 18.
*/
maxZoom?: number;
/**
* Maximum zoom number the tiles source has available. If it is specified,
* the tiles on all zoom levels higher than maxNativeZoom will be loaded from
* maxZoom level and auto-scaled.
*
* Default value: null.
*/
maxNativeZoom?: number;
/**
* Tile size (width and height in pixels, assuming tiles are square).
@@ -3997,6 +4147,11 @@ declare module L {
* An equivalent of passing animate to both zoom and pan options (see below).
*/
animate?: boolean;
/**
* If true, it will delay moveend event so that it doesn't happen many times in a row.
*/
debounceMoveend?: boolean;
}
}
+1
View File
@@ -13,6 +13,7 @@
//////////////////////////////////////////////////////////////////////
declare module L.mapbox {
var accessToken: string;
/**
* Create and automatically configure a map with layers, markers, and interactivity.
+23 -1
View File
@@ -57,13 +57,35 @@ declare module Backbone {
// Backbone.Wreqr
module Wreqr {
module radio {
function channel(channelName: string): Channel;
}
class Channel {
constructor(channelName: string);
vent: Backbone.Wreqr.EventAggregator;
reqres: Backbone.Wreqr.RequestResponse;
commands: Backbone.Wreqr.Commands;
channelName: string;
reset(): Channel;
connectEvents(hash: string, context: any): Channel;
connectCommands(hash: string, context: any): Channel;
connectRequests(hash: string, context: any): Channel;
}
class Handlers extends Backbone.Events {
constructor(options?: any);
options: any;
setHandler(name: string, handler: any, context: any): void;
setHandler(name: string, handler: any, context?: any): void;
hasHandler(name: string): boolean;
getHandler(name: string): Function;
removeHandler(name: string);
+15
View File
@@ -0,0 +1,15 @@
/// <reference path="method-override.d.ts" />
import express = require('express');
import methodOverride = require('method-override');
var app = express();
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(methodOverride((req: express.Request, res: express.Response) => {
if (req.body && typeof req.body === 'object' && '_method' in req.body) {
// look in urlencoded POST bodies and delete it
var method = req.body._method
delete req.body._method
return method
}
}));
+24
View File
@@ -0,0 +1,24 @@
// Type definitions for method-override
// Project: https://github.com/expressjs/method-override
// Definitions by: Santi Albo <https://github.com/santialbo/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
declare module Express {
export interface Request {
originalMethod?: string;
}
}
declare module "method-override" {
import express = require('express');
module e {
interface MethodOverrideOptions {
methods: string[];
}
}
function e(getter: string, options?: any): express.RequestHandler;
function e(getter: (req: express.Request, res: express.Response) => string, options?: any): express.RequestHandler;
export = e;
}
+6 -6
View File
@@ -1,6 +1,6 @@
// Type definitions for Moment.js 2.5.0
// Project: https://github.com/timrwood/moment
// Definitions by: Michael Lakerveld <https://github.com/Lakerfield>, Aaron King <https://github.com/kingdango>, Hiroki Horiuchi <https://github.com/horiuchi>
// Definitions by: Michael Lakerveld <https://github.com/Lakerfield>, Aaron King <https://github.com/kingdango>, Hiroki Horiuchi <https://github.com/horiuchi>, Dick van den Brink <https://github.com/DickvdBrink>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface MomentInput {
@@ -203,9 +203,9 @@ interface Moment {
isSame(b: Date, granularity: string): boolean;
isSame(b: number[], granularity: string): boolean;
lang(language: string): void;
lang(reset: boolean): void;
lang(): string;
lang(language: string): Moment;
lang(reset: boolean): Moment;
lang(): MomentLanguage;
max(date: Date): Moment;
max(date: number): Moment;
@@ -313,8 +313,8 @@ interface MomentStatic {
isMoment(): boolean;
isMoment(m: any): boolean;
lang(language: string): any;
lang(language: string, definition: MomentLanguage): any;
lang(language?: string): string;
lang(language?: string, definition?: MomentLanguage): string;
longDateFormat: any;
relativeTime: any;
meridiem: (hour: number, minute: number, isLowercase: boolean) => string;
+29
View File
@@ -0,0 +1,29 @@
/// <reference path="morgan.d.ts"/>
/**
* Created by staticfunction on 8/3/14.
*/
import morgan = require('morgan');
// a pre-defined name
morgan('combined')
morgan('common')
morgan('short')
morgan('tiny')
// a format string
morgan(':remote-addr :method :url')
// a custom function
morgan(function (req, res) {
return req.method + ' ' + req.url
})
morgan('combined', {
buffer: true,
immediate: true,
skip: function (req, res) { return res.statusCode < 400 },
stream: (str: string) => {
console.log(str);
}
});
+93
View File
@@ -0,0 +1,93 @@
// Type definitions for morgan 1.2.2
// Project: https://github.com/expressjs/morgan
// Definitions by: James Roland Cabresos <https://github.com/staticfunction>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
declare module "morgan" {
import express = require('express');
module morgan {
export function token<T>(name: string, callback: (req: express.Request, res: express.Response) => T): express.RequestHandler;
/***
* Morgan accepts these properties in the options object.
*/
export interface Options {
/***
* Buffer duration before writing logs to the stream, defaults to false. When set to true, defaults to 1000 ms.
*/
buffer?: boolean;
/***
* Write log line on request instead of response. This means that a requests will be logged even if the server crashes, but data from the response cannot be logged (like the response code).
*/
immediate?: boolean;
/***
* Function to determine if logging is skipped, defaults to false. This function will be called as skip(req, res).
*/
skip?: (req: express.Request, res: express.Response) => boolean;
/***
* Output stream for writing log lines, defaults to process.stdout.
* @param str
*/
stream?: (str: string) => void;
}
}
/***
* Create a new morgan logger middleware function using the given format and options. The format argument may be a string of a predefined name (see below for the names), a string of a format string, or a function that will produce a log entry.
* @param format
* @param options
*/
function morgan(format: string, options?: morgan.Options): express.RequestHandler;
/***
* Standard Apache combined log output.
* :remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
* @param format
* @param options
*/
function morgan(format: 'combined', options?: morgan.Options): express.RequestHandler;
/***
* Standard Apache common log output.
* :remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length]
* @param format
* @param options
*/
function morgan(format: 'common', options?: morgan.Options): express.RequestHandler;
/***
* Concise output colored by response status for development use. The :status token will be colored red for server error codes, yellow for client error codes, cyan for redirection codes, and uncolored for all other codes.
* :method :url :status :response-time ms - :res[content-length]
* @param format
* @param options
*/
function morgan(format: 'dev', options?: morgan.Options): express.RequestHandler;
/***
* Shorter than default, also including response time.
* :remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms
* @param format
* @param options
*/
function morgan(format: 'short', options?: morgan.Options): express.RequestHandler;
/***
* The minimal output.
* :method :url :status :res[content-length] - :response-time ms
* @param format
* @param options
*/
function morgan(format: 'tiny', options?: morgan.Options): express.RequestHandler;
function morgan(custom: (req: express.Request, res: express.Response) => string): express.RequestHandler
export = morgan;
}
+381
View File
@@ -0,0 +1,381 @@
/// <reference path="mysql.d.ts" />
import mysql = require('mysql');
/// Connections
var connection = mysql.createConnection({
host: 'localhost',
user: 'me',
password: 'secret'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function (err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
connection = mysql.createConnection({
host: 'example.org',
user: 'bob',
password: 'secret'
});
connection.connect(function (err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
connection.query('SELECT 1', function (err, rows) {
// connected! (unless `err` is set)
});
connection = mysql.createConnection({
host: 'localhost',
ssl: {
ca: ''
}
});
connection = mysql.createConnection({
host: 'localhost',
ssl: {
// DO NOT DO THIS
// set up your ca correctly to trust the connection
rejectUnauthorized: false
}
});
connection.end(function (err) {
// The connection is terminated now
});
connection.destroy();
connection.changeUser({ user: 'john' }, function (err) {
if (err) throw err;
});
var userId = 'some user provided value';
var sql = 'SELECT * FROM users WHERE id = ' + connection.escape(userId);
connection.query(sql, function (err, results) {
// ...
});
connection.query('SELECT * FROM users WHERE id = ?', [userId], function (err, results) {
// ...
});
var post = { id: 1, title: 'Hello MySQL' };
var query = connection.query('INSERT INTO posts SET ?', post, function (err, result) {
// Neat!
});
console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
var queryStr = "SELECT * FROM posts WHERE title=" + mysql.escape("Hello MySQL");
console.log(queryStr); // SELECT * FROM posts WHERE title='Hello MySQL'
var sorter = 'date';
var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId(sorter);
connection.query(sql, function (err, results) {
// ...
});
var sorter = 'date';
var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId('posts.' + sorter);
connection.query(sql, function (err, results) {
// ...
});
var userIdNum = 1;
var columns = ['username', 'email'];
var query = connection.query('SELECT ?? FROM ?? WHERE id = ?', [columns, 'users', userIdNum], function (err, results) {
// ...
});
console.log(query.sql); // SELECT `username`, `email` FROM `users` WHERE id = 1
var sql = "SELECT * FROM ?? WHERE ?? = ?";
var inserts = ['users', 'id', userId];
sql = mysql.format(sql, inserts);
connection.config.queryFormat = function (query, values) {
if (!values) return query;
return query.replace(/\:(\w+)/g, function (txt: string, key: string) {
if (values.hasOwnProperty(key)) {
return this.escape(values[key]);
}
return txt;
}.bind(this));
};
connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });
connection.query('INSERT INTO posts SET ?', { title: 'test' }, function (err, result) {
if (err) throw err;
console.log(result.insertId);
});
connection.query('DELETE FROM posts WHERE title = "wrong"', function (err, result) {
if (err) throw err;
console.log('deleted ' + result.affectedRows + ' rows');
});
connection.query('UPDATE posts SET ...', function (err, result) {
if (err) throw err;
console.log('changed ' + result.changedRows + ' rows');
});
connection.connect(function (err) {
if (err) throw err;
console.log('connected as id ' + connection.threadId);
});
/// Pools
var poolConfig = {
connectionLimit: 10,
host: 'example.org',
user: 'bob',
password: 'secret'
};
var pool = mysql.createPool(poolConfig);
pool.query('SELECT 1 + 1 AS solution', function (err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
pool = mysql.createPool({
host: 'example.org',
user: 'bob',
password: 'secret'
});
pool.getConnection(function (err, connection) {
// connected! (unless `err` is set)
});
pool.on('connection', function (connection) {
connection.query('SET SESSION auto_increment_increment=1')
});
pool.getConnection(function (err, connection) {
// Use the connection
connection.query('SELECT something FROM sometable', function (err, rows) {
// And done with the connection.
connection.release();
// Don't use the connection here, it has been returned to the pool.
});
});
/// PoolClusters
// create
var poolCluster = mysql.createPoolCluster();
poolCluster.add(poolConfig); // anonymous group
poolCluster.add('MASTER', poolConfig);
poolCluster.add('SLAVE1', poolConfig);
poolCluster.add('SLAVE2', poolConfig);
// Target Group : ALL(anonymous, MASTER, SLAVE1-2), Selector : round-robin(default)
poolCluster.getConnection(function (err, connection) { });
// Target Group : MASTER, Selector : round-robin
poolCluster.getConnection('MASTER', function (err, connection) { });
// Target Group : SLAVE1-2, Selector : order
// If can't connect to SLAVE1, return SLAVE2. (remove SLAVE1 in the cluster)
poolCluster.on('remove', function (nodeId) {
console.log('REMOVED NODE : ' + nodeId); // nodeId = SLAVE1
});
poolCluster.getConnection('SLAVE*', 'ORDER', function (err, connection) { });
// of namespace : of(pattern, selector)
poolCluster.of('*').getConnection(function (err, connection) { });
var pool = poolCluster.of('SLAVE*', 'RANDOM');
pool.getConnection(function (err, connection) { });
pool.getConnection(function (err, connection) { });
// destroy
poolCluster.end();
/// Queries
var query = connection.query('SELECT * FROM posts');
query
.on('error', function (err) {
// Handle error, an 'end' event will be emitted after this as well
})
.on('fields', function (fields) {
// the field packets for the rows to follow
})
.on('result', function (row) {
// Pausing the connnection is useful if your processing involves I/O
connection.pause();
var processRow = (row: any, cb: () => void) => {
cb();
};
processRow(row, function () {
connection.resume();
});
})
.on('end', function () {
// all rows have been received
});
connection.query('SELECT * FROM posts')
.stream({ highWaterMark: 5 })
.pipe(() => { });
connection = mysql.createConnection({ multipleStatements: true });
connection.query('SELECT 1; SELECT 2', function (err, results) {
if (err) throw err;
// `results` is an array with one element for every statement in the query:
console.log(results[0]); // [{1: 1}]
console.log(results[1]); // [{2: 2}]
});
var query = connection.query('SELECT 1; SELECT 2');
query
.on('fields', function (fields, index) {
// the fields for the result rows that follow
})
.on('result', function (row, index) {
// index refers to the statement this result belongs to (starts at 0)
});
var options = { sql: '...', nestTables: true };
connection.query(options, function (err, results) {
/* results will be an array like this now:
[{
table1: {
fieldA: '...',
fieldB: '...',
},
table2: {
fieldA: '...',
fieldB: '...',
},
}, ...]
*/
});
connection.beginTransaction(function (err) {
var title = 'title';
if (err) { throw err; }
connection.query('INSERT INTO posts SET title=?', title, function (err, result) {
if (err) {
connection.rollback(function () {
throw err;
});
}
var log = 'Post ' + result.insertId + ' added';
connection.query('INSERT INTO log SET data=?', log, function (err, result) {
if (err) {
connection.rollback(function () {
throw err;
});
}
connection.commit(function (err) {
if (err) {
connection.rollback(function () {
throw err;
});
}
console.log('success!');
});
});
});
});
// Kill query after 60s
connection.query({ sql: 'SELECT COUNT(*) AS count FROM big_table', timeout: 60000 }, function (err, rows) {
if (err && err.code === 'PROTOCOL_SEQUENCE_TIMEOUT') {
throw new Error('too long to count table rows!');
}
if (err) {
throw err;
}
console.log(rows[0].count + ' rows');
});
connection = mysql.createConnection({
port: 84943, // WRONG PORT
});
connection.connect(function (err) {
console.log(err.code); // 'ECONNREFUSED'
console.log(err.fatal); // true
});
connection.query('SELECT 1', function (err) {
console.log(err.code); // 'ECONNREFUSED'
console.log(err.fatal); // true
});
connection.query('USE name_of_db_that_does_not_exist', function (err, rows) {
console.log(err.code); // 'ER_BAD_DB_ERROR'
});
connection.query('SELECT 1', function (err, rows) {
console.log(err); // null
console.log(rows.length); // 1
});
connection.on('error', function (err) {
console.log(err.code); // 'ER_BAD_DB_ERROR'
});
connection.query('USE name_of_db_that_does_not_exist');
// I am Chuck Norris:
connection.on('error', function () { });
connection = mysql.createConnection({ typeCast: false });
var query = connection.query({ sql: '...', typeCast: false }, function (err, results) {
});
connection.query({
sql: '...',
typeCast: function (field: any, next: Function) {
if (field.type == 'TINY' && field.length == 1) {
return (field.string() == '1'); // 1 = true, 0 = false
}
return next();
}
});
connection = mysql.createConnection("mysql://localhost/test?flags=-FOUND_ROWS");
connection = mysql.createConnection({ debug: true });
connection = mysql.createConnection({ debug: ['ComQueryPacket', 'RowDataPacket'] });
+487
View File
@@ -0,0 +1,487 @@
// Type definitions for node-mysql
// Project: https://github.com/felixge/node-mysql
// Definitions by: William Johnston <https://github.com/wjohnsto>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module mysql {
export interface IMySql {
createConnection(connectionUri: string): IConnection;
createConnection(config: IConnectionConfig): IConnection;
createPool(config: IPoolConfig): IPool;
createPoolCluster(config?: IPoolClusterConfig): IPoolCluster;
escape(value: any): string;
format(sql: string): string;
format(sql: string, values: Array<any>): string;
}
export interface IConnectionStatic {
createQuery(sql: string): IQuery;
createQuery(sql: string, callback: (err: IError, ...args: any[]) => void): IQuery;
createQuery(sql: string, values: Array<any>): IQuery;
createQuery(sql: string, values: Array<any>, callback: (err: IError, ...args: any[]) => void): IQuery;
}
export interface IConnection {
config: IConnectionConfig;
threadId: number;
beginTransaction(callback: (err: IError) => void): void;
connect(): void;
connect(callback: (err: IError, ...args: any[]) => void): void;
connect(options: any, callback?: (err: IError, ...args: any[]) => void): void;
commit(callback: (err: IError) => void): void;
changeUser(options: IConnectionOptions): void;
changeUser(options: IConnectionOptions, callback: (err: IError) => void): void;
query: IQueryFunction;
end(): void;
end(callback: (err: IError, ...args: any[]) => void): void;
end(options: any, callback: (err: IError, ...args: any[]) => void): void;
destroy(): void;
pause(): void;
release(): void;
resume(): void;
escape(value: any): string;
escapeId(value: string): string;
escapeId(values: Array<string>): string;
format(sql: string): string;
format(sql: string, values: Array<any>): string;
on(ev: string, callback: (...args: any[]) => void): IConnection;
on(ev: 'error', callback: (err: IError) => void): IConnection;
rollback(callback: () => void): void;
}
export interface IPool {
config: IPoolConfig;
getConnection(callback: (err: IError, connection: IConnection) => void): void;
query: IQueryFunction;
on(ev: string, callback: (...args: any[]) => void): IPool;
on(ev: 'connection', callback: (connection: IConnection) => void): IPool;
on(ev: 'error', callback: (err: IError) => void): IPool;
}
export interface IPoolCluster {
config: IPoolClusterConfig;
add(config: IPoolConfig): void;
add(group: string, config: IPoolConfig): void;
end(): void;
getConnection(callback: (err: IError, connection: IConnection) => void): void;
getConnection(group: string, callback: (err: IError, connection: IConnection) => void): void;
getConnection(group: string, selector: string, callback: (err: IError, connection: IConnection) => void): void;
of(pattern: string): IPool;
of(pattern: string, selector: string): IPool;
on(ev: string, callback: (...args: any[]) => void): IPoolCluster;
on(ev: 'remove', callback: (nodeId: number) => void): IPoolCluster;
on(ev: 'connection', callback: (connection: IConnection) => void): IPoolCluster;
on(ev: 'error', callback: (err: IError) => void): IPoolCluster;
}
export interface IQuery {
/**
* The SQL for a constructed query
*/
sql: string;
/**
* Emits a query packet to start the query
*/
start(): void;
/**
* Determines the packet class to use given the first byte of the packet.
*
* @param firstByte The first byte of the packet
* @param parser The packet parser
*/
determinePacket(firstByte: number, parser: any): any;
/**
* Creates a Readable stream with the given options
*
* @param options The options for the stream.
*/
stream(options: IStreamOptions): IQuery;
/**
* Pipes a stream downstream, providing automatic pause/resume based on the
* options sent to the stream.
*
* @param options The options for the stream.
*/
pipe(callback: (...args: any[]) => void): IQuery;
on(ev: string, callback: (...args: any[]) => void): IQuery;
on(ev: 'error', callback: (err: IError) => void): IQuery;
on(ev: 'fields', callback: (fields: any, index: number) => void): IQuery;
on(ev: 'result', callback: (row: any, index: number) => void): IQuery;
on(ev: 'end', callback: () => void): IQuery;
}
export interface IQueryFunction {
(sql: string): IQuery;
(sql: string, callback: (err: IError, ...args: any[]) => void): IQuery;
(sql: string, values: Array<any>): IQuery;
(sql: string, values: Array<any>, callback: (err: IError, ...args: any[]) => void): IQuery;
(sql: string, values: any): IQuery;
(sql: string, values: any, callback: (err: IError, ...args: any[]) => void): IQuery;
(options: IQueryOptions): IQuery;
(options: IQueryOptions, callback: (err: IError, ...args: any[]) => void): IQuery;
(options: IQueryOptions, values: Array<any>): IQuery;
(options: IQueryOptions, values: Array<any>, callback: (err: IError, ...args: any[]) => void): IQuery;
(options: IQueryOptions, values: any): IQuery;
(options: IQueryOptions, values: any, callback: (err: IError, ...args: any[]) => void): IQuery;
}
export interface IQueryOptions {
/**
* The SQL for the query
*/
sql: string;
/**
* Every operation takes an optional inactivity timeout option. This allows you to specify appropriate timeouts for
* operations. It is important to note that these timeouts are not part of the MySQL protocol, and rather timeout
* operations through the client. This means that when a timeout is reached, the connection it occurred on will be
* destroyed and no further operations can be performed.
*/
timeout?: number;
/**
* Either a boolean or string. If true, tables will be nested objects. If string (e.g. '_'), tables will be
* nested as tableName_fieldName
*/
nestTables?: any;
/**
* Determines if column values should be converted to native JavaScript types. It is not recommended (and may go away / change in the future)
* to disable type casting, but you can currently do so on either the connection or query level. (Default: true)
*
* You can also specify a function (field: any, next: () => void) => {} to do the type casting yourself.
*
* WARNING: YOU MUST INVOKE the parser using one of these three field functions in your custom typeCast callback. They can only be called once.
*
* field.string()
* field.buffer()
* field.geometry()
*
* are aliases for
*
* parser.parseLengthCodedString()
* parser.parseLengthCodedBuffer()
* parser.parseGeometryValue()
*
* You can find which field function you need to use by looking at: RowDataPacket.prototype._typeCast
*/
typeCast?: any;
}
export interface IStreamOptions {
/**
* Sets the max buffer size in objects of a stream
*/
highWaterMark?: number;
/**
* The object mode of the stream (Default: true)
*/
objectMode?: any;
}
export interface IConnectionOptions {
/**
* The MySQL user to authenticate as
*/
user?: string;
/**
* The password of that MySQL user
*/
password?: string;
/**
* Name of the database to use for this connection
*/
database?: string;
/**
* The charset for the connection. This is called "collation" in the SQL-level of MySQL (like utf8_general_ci).
* If a SQL-level charset is specified (like utf8mb4) then the default collation for that charset is used.
* (Default: 'UTF8_GENERAL_CI')
*/
charset?: string;
}
export interface IConnectionConfig extends IConnectionOptions {
/**
* The hostname of the database you are connecting to. (Default: localhost)
*/
host?: string;
/**
* The port number to connect to. (Default: 3306)
*/
port?: number;
/**
* The source IP address to use for TCP connection
*/
localAddress?: string;
/**
* The path to a unix domain socket to connect to. When used host and port are ignored
*/
socketPath?: string;
/**
* The timezone used to store local dates. (Default: 'local')
*/
timezone?: string;
/**
* The milliseconds before a timeout occurs during the initial connection to the MySQL server. (Default: 10 seconds)
*/
connectTimeout?: number;
/**
* Stringify objects instead of converting to values. (Default: 'false')
*/
stringifyObjects?: boolean;
/**
* Allow connecting to MySQL instances that ask for the old (insecure) authentication method. (Default: false)
*/
insecureAuth?: boolean;
/**
* Determines if column values should be converted to native JavaScript types. It is not recommended (and may go away / change in the future)
* to disable type casting, but you can currently do so on either the connection or query level. (Default: true)
*
* You can also specify a function (field: any, next: () => void) => {} to do the type casting yourself.
*
* WARNING: YOU MUST INVOKE the parser using one of these three field functions in your custom typeCast callback. They can only be called once.
*
* field.string()
* field.buffer()
* field.geometry()
*
* are aliases for
*
* parser.parseLengthCodedString()
* parser.parseLengthCodedBuffer()
* parser.parseGeometryValue()
*
* You can find which field function you need to use by looking at: RowDataPacket.prototype._typeCast
*/
typeCast?: any;
/**
* A custom query format function
*/
queryFormat?: (query: string, values: any) => void;
/**
* When dealing with big numbers (BIGINT and DECIMAL columns) in the database, you should enable this option
* (Default: false)
*/
supportBigNumbers?: boolean;
/**
* Enabling both supportBigNumbers and bigNumberStrings forces big numbers (BIGINT and DECIMAL columns) to be
* always returned as JavaScript String objects (Default: false). Enabling supportBigNumbers but leaving
* bigNumberStrings disabled will return big numbers as String objects only when they cannot be accurately
* represented with [JavaScript Number objects] (http://ecma262-5.com/ELS5_HTML.htm#Section_8.5)
* (which happens when they exceed the [-2^53, +2^53] range), otherwise they will be returned as Number objects.
* This option is ignored if supportBigNumbers is disabled.
*/
bigNumberStrings?: boolean;
/**
* Force date types (TIMESTAMP, DATETIME, DATE) to be returned as strings rather then inflated into JavaScript Date
* objects. (Default: false)
*/
dateStrings?: boolean;
/**
* This will print all incoming and outgoing packets on stdout.
* You can also restrict debugging to packet types by passing an array of types (strings) to debug;
*
* (Default: false)
*/
debug?: any;
/**
* Generates stack traces on Error to include call site of library entrance ("long stack traces"). Slight
* performance penalty for most calls. (Default: true)
*/
trace?: boolean;
/**
* Allow multiple mysql statements per query. Be careful with this, it exposes you to SQL injection attacks. (Default: false)
*/
multipleStatements?: boolean;
/**
* List of connection flags to use other than the default ones. It is also possible to blacklist default ones
*/
flags?: Array<string>;
/**
* object with ssl parameters or a string containing name of ssl profile
*/
ssl?: any;
}
export interface IPoolConfig extends IConnectionConfig {
/**
* The milliseconds before a timeout occurs during the connection acquisition. This is slightly different from connectTimeout,
* because acquiring a pool connection does not always involve making a connection. (Default: 10 seconds)
*/
acquireTimeout?: number;
/**
* Determines the pool's action when no connections are available and the limit has been reached. If true, the pool will queue
* the connection request and call it when one becomes available. If false, the pool will immediately call back with an error.
* (Default: true)
*/
waitForConnections?: boolean;
/**
* The maximum number of connections to create at once. (Default: 10)
*/
connectionLimit?: number;
/**
* The maximum number of connection requests the pool will queue before returning an error from getConnection. If set to 0, there
* is no limit to the number of queued connection requests. (Default: 0)
*/
queueLimit?: number;
}
export interface IPoolClusterConfig {
/**
* If true, PoolCluster will attempt to reconnect when connection fails. (Default: true)
*/
canRetry?: boolean;
/**
* If connection fails, node's errorCount increases. When errorCount is greater than removeNodeErrorCount,
* remove a node in the PoolCluster. (Default: 5)
*/
removeNodeErrorCount?: number;
/**
* The default selector. (Default: RR)
* RR: Select one alternately. (Round-Robin)
* RANDOM: Select the node by random function.
* ORDER: Select the first node available unconditionally.
*/
defaultSelector?: string;
}
export interface ISslCredentials {
/**
* A string or buffer holding the PFX or PKCS12 encoded private key, certificate and CA certificates
*/
pfx?: string;
/**
* A string holding the PEM encoded private key
*/
key?: string;
/**
* A string of passphrase for the private key or pfx
*/
passphrase?: string;
/**
* A string holding the PEM encoded certificate
*/
cert?: string;
/**
* Either a string or list of strings of PEM encoded CA certificates to trust.
*/
ca?: Array<string>;
/**
* Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List)
*/
crl?: Array<string>;
/**
* A string describing the ciphers to use or exclude
*/
ciphers?: string;
}
export interface IError extends Error {
/**
* Either a MySQL server error (e.g. 'ER_ACCESS_DENIED_ERROR'),
* a node.js error (e.g. 'ECONNREFUSED') or an internal error
* (e.g. 'PROTOCOL_CONNECTION_LOST').
*/
code: string;
/**
* The error number for the error code
*/
errno: number;
/**
* The sql state marker
*/
sqlStateMarker?: string;
/**
* The sql state
*/
sqlState?: string;
/**
* The field count
*/
fieldCount?: number;
/**
* The stack trace for the error
*/
stack?: string;
/**
* Boolean, indicating if this error is terminal to the connection object.
*/
fatal: boolean;
}
}
declare module 'mysql' {
var mysql: mysql.IMySql;
export = mysql;
}
+108
View File
@@ -0,0 +1,108 @@
/// <reference path="needle.d.ts" />
import needle = require("needle");
function Usage() {
// using callback
needle.get('http://ifconfig.me/all.json', function (error, response) {
if (!error)
console.log(response.body.ip_addr); // JSON decoding magic. :)
});
// using streams
var out: any; // = fs.createWriteStream('logo.png');
needle.get('https://google.com/images/logo.png').pipe(out);
}
function ResponsePipeline() {
needle.get('http://stackoverflow.com/feeds', { compressed: true }, function (err, resp) {
console.log(resp.body); // this little guy won't be a Gzipped binary blob
// but a nice object containing all the latest entries
});
var options = {
compressed: true,
follow: true,
rejectUnauthorized: true
};
// in this case, we'll ask Needle to follow redirects (disabled by default),
// but also to verify their SSL certificates when connecting.
var stream = needle.get('https://backend.server.com/everything.html', options);
stream.on('readable', function () {
var data: any;
while (data = this.read()) {
console.log(data.toString());
}
});
}
function API_head() {
var options = {
timeout: 5000 // if we don't get a response in 5 seconds, boom.
};
needle.head('https://my.backend.server.com', function (err, resp) {
if (err) {
console.log('Shoot! Something is wrong: ' + err.message);
}
else {
console.log('Yup, still alive.');
}
});
}
function API_get() {
needle.get('google.com/search?q=syd+barrett', function (err, resp) {
// if no http:// is found, Needle will automagically prepend it.
});
}
function API_post() {
var options = {
headers: { 'X-Custom-Header': 'Bumbaway atuna' }
};
needle.post('https://my.app.com/endpoint', 'foo=bar', options, function (err, resp) {
// you can pass params as a string or as an object.
});
}
function API_put() {
var nested = {
params: {
are: {
also: 'supported'
}
}
};
needle.put('https://api.app.com/v2', nested, function (err, resp) {
console.log('Got ' + resp.bytes + ' bytes.') // another nice treat from this handsome fella.
});
}
function API_delete() {
var options = {
username: 'fidelio',
password: 'x'
};
needle.delete('https://api.app.com/messages/123', null, options, function (err, resp) {
// in this case, data may be null, but you need to explicity pass it.
});
}
function API_request() {
var data = {
q: 'a very smart query',
page: 2,
format: 'json'
};
needle.request('get', 'forum.com/search', data, function (err, resp) {
if (!err && resp.statusCode == 200)
console.log(resp.body); // here you go, mister.
});
}
+88
View File
@@ -0,0 +1,88 @@
// Type definitions for needle 0.7.8
// Project: https://github.com/tomas/needle
// Definitions by: San Chen <https://github.com/bigsan>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module Needle {
interface ReadableStream extends NodeJS.ReadableStream {
}
interface Callback {
(error: Error, response: any, body: any): void;
}
interface RequestOptions {
timeout?: number;
follow?: any; // number | string
multipart?: boolean;
proxy?: string;
agent?: string;
headers?: any;
auth?: string; // auto | digest | basic (default)
json?: boolean;
}
interface ResponseOptions {
decode?: boolean;
parse?: boolean;
output?: any;
}
interface HttpHeaderOptions {
compressed?: boolean;
username?: string;
password?: string;
accept?: string;
connection?: string;
user_agent?: string;
}
interface TLSOptions {
pfx?: any;
key?: any;
passphrase?: string;
cert?: any;
ca?: any;
ciphers?: any;
rejectUnauthorized?: boolean;
secureProtocol?: any;
}
interface NeedleOptions extends RequestOptions, ResponseOptions, HttpHeaderOptions, TLSOptions {
}
interface NeedleStatic {
defaults(options?: any): void;
head(url: string): ReadableStream;
head(url: string, callback?: Callback): ReadableStream;
head(url: string, options?: RequestOptions, callback?: Callback): ReadableStream;
get(url: string): ReadableStream;
get(url: string, callback?: Callback): ReadableStream;
get(url: string, options?: RequestOptions, callback?: Callback): ReadableStream;
post(url: string, data: any): ReadableStream;
post(url: string, data: any, callback?: Callback): ReadableStream;
post(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream;
put(url: string, data: any): ReadableStream;
put(url: string, data: any, callback?: Callback): ReadableStream;
put(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream;
delete(url: string, data: any): ReadableStream;
delete(url: string, data: any, callback?: Callback): ReadableStream;
delete(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream;
request(method: string, url: string, data: any): ReadableStream;
request(method: string, url: string, data: any, callback?: Callback): ReadableStream;
request(method: string, url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream;
}
}
declare module "needle" {
var needle: Needle.NeedleStatic;
export = needle;
}
+31
View File
@@ -0,0 +1,31 @@
/// <reference path="node-form.d.ts" />
/// <reference path="../underscore/underscore.d.ts" />
/// <reference path="../q/Q.d.ts" />
/// <reference path="../moment/moment.d.ts" />
export interface IPerson{
Checked:boolean;
FirstName:string;
LastName:string;
Email:string;
}
//create custom composite validator
var personValidator = new Validation.AbstractValidator<IPerson>();
//create field validators
var required = new Validation.RequiredValidator();
var email = new Validation.EmailValidator();
var maxLength = new Validation.MaxLengthValidator();
maxLength.MaxLength = 15;
personValidator.RuleFor("FirstName", required);
personValidator.RuleFor("FirstName", maxLength);
personValidator.RuleFor("LastName", required);
personValidator.RuleFor("LastName", maxLength);
personValidator.RuleFor("Email", required);
personValidator.RuleFor("Email", email);
+710
View File
@@ -0,0 +1,710 @@
// Type definitions for node-form v1.0.13
// Project: https://github.com/rsamec/form
// Definitions by: Roman Samec <https://github.com/rsamec>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../underscore/underscore.d.ts" />
/// <reference path="../q/Q.d.ts" />
/// <reference path="../moment/moment.d.ts" />
declare module Validation {
/**
* Custom message functions.
*/
interface IErrorCustomMessage {
(config: any, args: any): string;
}
/**
* It represents a property validator for atomic object.
*/
interface IPropertyValidator {
isAcceptable(s: any): boolean;
customMessage?: IErrorCustomMessage;
tagName?: string;
}
/**
* It represents a property validator for simple string value.
*/
interface IStringValidator extends IPropertyValidator {
isAcceptable(s: string): boolean;
}
/**
* It represents an async property validator for atomic object.
*/
interface IAsyncPropertyValidator {
isAcceptable(s: any): Q.Promise<boolean>;
customMessage?: IErrorCustomMessage;
isAsync: boolean;
tagName?: string;
}
/**
* It represents an async property validator for simple string value.
*/
interface IAsyncStringPropertyValidator extends IAsyncPropertyValidator {
isAcceptable(s: string): Q.Promise<boolean>;
}
/**
* It defines compare operators.
*/
enum CompareOperator {
LessThan = 0,
LessThanEqual = 1,
Equal = 2,
NotEqual = 3,
GreaterThanEqual = 4,
GreaterThan = 5,
}
class StringFce {
static format(s: string, args: any): string;
}
class NumberFce {
static GetNegDigits(value: string): number;
}
class LettersOnlyValidator implements IStringValidator {
public isAcceptable(s: string): boolean;
public tagName: string;
}
class ZipCodeValidator implements IStringValidator {
public isAcceptable(s: string): boolean;
public tagName: string;
}
class EmailValidator implements IStringValidator {
public isAcceptable(s: string): boolean;
public tagName: string;
}
class UrlValidator implements IStringValidator {
public isAcceptable(s: string): boolean;
public tagName: string;
}
class RequiredValidator implements IStringValidator {
public isAcceptable(s: string): boolean;
public tagName: string;
}
class DateValidator implements IStringValidator {
public isAcceptable(s: string): boolean;
public tagName: string;
}
class DateISOValidator implements IStringValidator {
public isAcceptable(s: string): boolean;
public tagName: string;
}
class NumberValidator implements IStringValidator {
public isAcceptable(s: string): boolean;
public tagName: string;
}
class DigitValidator implements IStringValidator {
public isAcceptable(s: string): boolean;
public tagName: string;
}
class SignedDigitValidator implements IStringValidator {
public isAcceptable(s: string): boolean;
public tagName: string;
}
class MinLengthValidator implements IStringValidator {
public MinLength: number;
constructor(MinLength?: number);
public isAcceptable(s: string): boolean;
public tagName: string;
}
class MaxLengthValidator implements IStringValidator {
public MaxLength: number;
constructor(MaxLength?: number);
public isAcceptable(s: string): boolean;
public tagName: string;
}
class RangeLengthValidator implements IStringValidator {
public RangeLength: number[];
constructor(RangeLength?: number[]);
public isAcceptable(s: string): boolean;
public MinLength : number;
public MaxLength : number;
public tagName: string;
}
class MinValidator implements IPropertyValidator {
public Min: number;
constructor(Min?: number);
public isAcceptable(s: any): boolean;
public tagName: string;
}
class MaxValidator implements IPropertyValidator {
public Max: number;
constructor(Max?: number);
public isAcceptable(s: any): boolean;
public tagName: string;
}
class RangeValidator implements IPropertyValidator {
public Range: number[];
constructor(Range?: number[]);
public isAcceptable(s: any): boolean;
public Min : number;
public Max : number;
public tagName: string;
}
class StepValidator implements IPropertyValidator {
public Step: string;
constructor(Step?: string);
public isAcceptable(s: any): boolean;
public tagName: string;
}
class PatternValidator implements IStringValidator {
public Pattern: string;
constructor(Pattern?: string);
public isAcceptable(s: string): boolean;
public tagName: string;
}
class ContainsValidator implements IAsyncPropertyValidator {
public Options: Q.Promise<any[]>;
constructor(Options: Q.Promise<any[]>);
public isAcceptable(s: string): Q.Promise<boolean>;
public isAsync: boolean;
public tagName: string;
}
}
declare module Validation {
/**
* basic error structure
*/
interface IError {
HasError: boolean;
ErrorMessage: string;
TranslateArgs?: IErrorTranslateArgs;
}
/**
* support for localization of error messages
*/
interface IErrorTranslateArgs {
TranslateId: string;
MessageArgs: any;
CustomMessage?: IErrorCustomMessage;
}
/**
* It defines conditional function.
*/
interface IOptional {
(): boolean;
}
/**
* It represents the validation result.
*/
interface IValidationFailure extends IError {
IsAsync: boolean;
Error: IError;
}
/**
* This class provides unit of information about error.
* Implements composite design pattern to enable nesting of error information.
*/
interface IValidationResult {
/**
* The name of error collection.
*/
Name: string;
/**
* Add error information to child collection of errors.
* @param validationResult - error information to be added.
*/
Add(validationResult: IValidationResult): void;
/**
* Remove error information from child collection of errors.
* @param index - index of error information to be removed.
*/
Remove(index: number): void;
/**
* Return collections of child errors information.
*/
Children: IValidationResult[];
/**
* Return true if there is any error.
*/
HasErrors: boolean;
/**
* Return true if there is any error and hasw dirty state.
*/
HasErrorsDirty: boolean;
/**
* Return error message, if there is no error, return empty string.
*/
ErrorMessage: string;
/**
* Return number of errors.
*/
ErrorCount: number;
/**
* It enables to have errors optional.
*/
Optional?: IOptional;
/**
* It enables support for localization of error messages.
*/
TranslateArgs?: IErrorTranslateArgs[];
}
/**
*
* @ngdoc object
* @name Error
* @module Validation
*
*
* @description
* It represents basic error structure.
*/
class Error implements IError {
public HasError: boolean;
public ErrorMessage: string;
constructor();
}
/**
*
* @ngdoc object
* @name ValidationFailure
* @module Validation
*
*
* @description
* It represents validation failure.
*/
class ValidationFailure implements IError {
public Error: IError;
public IsAsync: boolean;
constructor(Error: IError, IsAsync: boolean);
public HasError : boolean;
public ErrorMessage : string;
public TranslateArgs : IErrorTranslateArgs;
}
/**
*
* @ngdoc object
* @name ValidationResult
* @module Validation
*
*
* @description
* It represents simple abstract error object.
*/
class ValidationResult implements IValidationResult {
public Name: string;
constructor(Name: string);
public IsDirty: boolean;
public Children : IValidationResult[];
public Add(error: IValidationResult): void;
public Remove(index: number): void;
public Optional: IOptional;
public TranslateArgs: IErrorTranslateArgs[];
public HasErrorsDirty : boolean;
public HasErrors : boolean;
public ErrorCount : number;
public ErrorMessage : string;
}
/**
*
* @ngdoc object
* @name CompositeValidationResult
* @module Validation
*
*
* @description
* It represents composite error object.
*/
class CompositeValidationResult implements IValidationResult {
public Name: string;
public Children: IValidationResult[];
constructor(Name: string);
public Optional: IOptional;
public AddFirst(error: IValidationResult): void;
public Add(error: IValidationResult): void;
public Remove(index: number): void;
public HasErrorsDirty : boolean;
public HasErrors : boolean;
public ErrorCount : number;
public ErrorMessage : string;
public TranslateArgs : IErrorTranslateArgs[];
public LogErrors(headerMessage?: string): void;
public Errors : {
[name: string]: IValidationResult;
};
private FlattenErros;
public SetDirty(): void;
public SetPristine(): void;
private SetDirtyEx(node, dirty);
private flattenErrors(node, errorCollection);
private traverse(node, indent);
}
}
declare module Validation {
/**
* @ngdoc module
* @name Validation
*
*
* @description
* # Validation (core module)
* The module itself contains the essential components for an validation engine to function. The table below
* lists a high level breakdown of each of the components (object, functions) available within this core module.
*
* <div doc-module-components="Validation"></div>
*/
/**
* It defines validation function.
*/
interface IValidate {
(args: IError): void;
}
/**
* It defines async validation function.
*/
interface IAsyncValidate {
(args: IError): Q.Promise<any>;
}
/**
* It represents named validation function.
*/
interface IValidatorFce {
Name: string;
ValidationFce?: IValidate;
AsyncValidationFce?: IAsyncValidate;
}
/**
* This class represents custom validator.
*/
interface IValidator {
Validate(context: any): IValidationFailure;
ValidateAsync(context: any): Q.Promise<IValidationFailure>;
Error: IError;
}
/**
* It represents abstract validator for type of <T>.
*/
interface IAbstractValidator<T> {
RuleFor(prop: string, validator: IPropertyValidator): any;
ValidationFor(prop: string, validator: IValidatorFce): any;
ValidatorFor<K>(prop: string, validator: IAbstractValidator<K>): any;
/**
* It creates new concrete validation rule and assigned data context to this rule.
* @param name of the rule
* @constructor
*/
CreateRule(name: string): IAbstractValidationRule<any>;
CreateAbstractRule(name: string): IAbstractValidationRule<any>;
CreateAbstractListRule(name: string): IAbstractValidationRule<any>;
/**
* return true if this validation rule is intended for list of items, otherwise true
*/
ForList: boolean;
}
/**
* It represents concrete validation rule for type of <T>.
*/
interface IAbstractValidationRule<T> {
/**
* Performs validation using a validation context and returns a collection of Validation Failures.
*/
Validate(context: T): IValidationResult;
/**
* Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy.
*/
ValidateAsync(context: T): Q.Promise<IValidationResult>;
/**
* Performs validation and async validation using a validation context.
*/
ValidateAll(context: T): void;
/**
* Performs validation and async validation using a validation context for a passed field.
*/
ValidateField(context: T, propName: string): void;
/**
* Return validation results.
*/
ValidationResult: IValidationResult;
Rules: {
[name: string]: IPropertyValidationRule<T>;
};
Validators: {
[name: string]: IValidator;
};
Children: {
[name: string]: AbstractValidationRule<any>;
};
}
/**
* It represents property validation rule for type of <T>.
*/
interface IPropertyValidationRule<T> {
/**
*The validators that are grouped under this rule.
*/
Validators: {
[name: string]: any;
};
/**
* Performs validation using a validation context and returns a collection of Validation Failures.
*/
Validate(context: IValidationContext<T>): IValidationFailure[];
/**
* Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy.
*/
ValidateAsync(context: IValidationContext<T>): Q.Promise<IValidationFailure[]>;
}
/**
* It represents a data context for validation rule.
*/
interface IValidationContext<T> {
/**
* Return current value.
*/
Value: string;
/**
* Return property name for current data context.
*/
Key: string;
/**
* Data context for validation rule.
*/
Data: T;
}
/**
*
* @ngdoc object
* @name AbstractValidator
* @module Validation
*
*
* @description
* It enables to create custom validator for your own abstract object (class) and to assign validation rules to its properties.
* You can assigned these rules
*
* + property validation rules - use _RuleFor_ property
* + property async validation rules - use _RuleFor_ property
* + shared validation rules - use _ValidationFor_ property
* + custom object validator - use _ValidatorFor_ property - enables composition of child custom validators
*/
class AbstractValidator<T> implements IAbstractValidator<T> {
public Validators: {
[name: string]: IPropertyValidator[];
};
public AbstractValidators: {
[name: string]: IAbstractValidator<any>;
};
public ValidationFunctions: {
[name: string]: IValidatorFce[];
};
public RuleFor(prop: string, validator: IPropertyValidator): void;
public ValidationFor(prop: string, fce: IValidatorFce): void;
public ValidatorFor<K>(prop: string, validator: IAbstractValidator<K>, forList?: boolean): void;
public CreateAbstractRule(name: string): AbstractValidationRule<T>;
public CreateAbstractListRule(name: string): AbstractListValidationRule<T>;
public CreateRule(name: string): AbstractValidationRule<T>;
/**
* Return true if this validation rule is intended for list of items, otherwise true.
*/
public ForList: boolean;
}
/**
*
* @ngdoc object
* @name AbstractValidationRule
* @module Validation
*
*
* @description
* It represents concreate validator for custom object. It enables to assign validation rules to custom object properties.
*/
class AbstractValidationRule<T> implements IAbstractValidationRule<T> {
public Name: string;
public validator: AbstractValidator<T>;
public ValidationResult: IValidationResult;
public Rules: {
[name: string]: IPropertyValidationRule<T>;
};
public Validators: {
[name: string]: IValidator;
};
public Children: {
[name: string]: AbstractValidationRule<any>;
};
/**
* Return true if this validation rule is intended for list of items, otherwise true.
*/
public ForList: boolean;
constructor(Name: string, validator: AbstractValidator<T>, forList?: boolean);
public addChildren(): void;
public SetOptional(fce: IOptional): void;
private createRuleFor(prop);
/**
* Performs validation using a validation context and returns a collection of Validation Failures.
*/
public Validate(context: T): IValidationResult;
/**
* Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy.
*/
public ValidateAsync(context: T): Q.Promise<IValidationResult>;
public ValidateAll(context: T): void;
public ValidateField(context: T, propName: string): void;
}
/**
*
* @ngdoc object
* @name AbstractListValidationRule
* @module Validation
*
*
* @description
* It represents an validator for custom object. It enables to assign rules to custom object properties.
*/
class AbstractListValidationRule<T> extends AbstractValidationRule<T> {
public Name: string;
public validator: AbstractValidator<T>;
constructor(Name: string, validator: AbstractValidator<T>);
/**
* Performs validation using a validation context and returns a collection of Validation Failures.
*/
public Validate(context: any): IValidationResult;
/**
* Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy.
*/
public ValidateAsync(context: any): Q.Promise<IValidationResult>;
private getValidationRule(i);
private getIndexedKey(i);
public NotifyListChanged(list: any[]): void;
}
/**
*
* @ngdoc object
* @name ValidationContext
* @module Validation
*
*
* @description
* It represents a data context for validation rule.
*/
class ValidationContext<T> implements IValidationContext<T> {
public Key: string;
public Data: T;
constructor(Key: string, Data: T);
public Value : any;
}
class MessageLocalization {
static customMsg: string;
static defaultMessages: {
"required": string;
"remote": string;
"email": string;
"url": string;
"date": string;
"dateISO": string;
"number": string;
"digits": string;
"signedDigits": string;
"creditcard": string;
"equalTo": string;
"maxlength": string;
"minlength": string;
"rangelength": string;
"range": string;
"max": string;
"min": string;
"step": string;
"contains": string;
"mask": string;
"custom": string;
};
static ValidationMessages: {
"required": string;
"remote": string;
"email": string;
"url": string;
"date": string;
"dateISO": string;
"number": string;
"digits": string;
"signedDigits": string;
"creditcard": string;
"equalTo": string;
"maxlength": string;
"minlength": string;
"rangelength": string;
"range": string;
"max": string;
"min": string;
"step": string;
"contains": string;
"mask": string;
"custom": string;
};
static GetValidationMessage(validator: any): string;
}
/**
*
* @ngdoc object
* @name PropertyValidationRule
* @module Validation
*
*
* @description
* It represents a property validation rule. The property has assigned collection of property validators.
*/
class PropertyValidationRule<T> extends ValidationResult implements IPropertyValidationRule<T> {
public Name: string;
public Validators: {
[name: string]: any;
};
public ValidationFailures: {
[name: string]: IValidationFailure;
};
constructor(Name: string, validatorsToAdd?: IPropertyValidator[]);
public AddValidator(validator: any): void;
public Errors : {
[name: string]: IValidationFailure;
};
public HasErrors : boolean;
public ErrorCount : number;
public ErrorMessage : string;
public TranslateArgs : IErrorTranslateArgs[];
/**
* Performs validation using a validation context and returns a collection of Validation Failures.
*/
public Validate(context: IValidationContext<T>): IValidationFailure[];
public ValidateEx(value: any): IValidationFailure[];
/**
* Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy.
*/
public ValidateAsync(context: IValidationContext<T>): Q.Promise<IValidationFailure[]>;
/**
* Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy.
*/
public ValidateAsyncEx(value: string): Q.Promise<IValidationFailure[]>;
}
/**
*
* @ngdoc object
* @name Validator
* @module Validation
*
*
* @description
* It represents a custom validator. It enables to define your own shared validation rules
*/
class Validator extends ValidationResult implements IValidator {
public Name: string;
private ValidateFce;
private AsyncValidationFce;
public Error: IError;
public ValidationFailures: {
[name: string]: IValidationFailure;
};
constructor(Name: string, ValidateFce?: IValidate, AsyncValidationFce?: IAsyncValidate);
public Optional: IOptional;
public Validate(context: any): IValidationFailure;
public ValidateAsync(context: any): Q.Promise<IValidationFailure>;
public HasError : boolean;
public Errors : {
[name: string]: IValidationFailure;
};
public HasErrors : boolean;
public ErrorCount : number;
public ErrorMessage : string;
public TranslateArgs : IErrorTranslateArgs[];
}
}
declare module "node-form"{
export = Validation;
}
+203
View File
@@ -0,0 +1,203 @@
///<reference path="../node/node.d.ts"/>
///<reference path="node-webkit.d.ts"/>
// Load native UI library
var gui: typeof nw.gui;
/* WINDOW */
// Get the current window
var win = gui.Window.get();
// Listen to the minimize event
win.on('minimize', function() {
console.log('Window is minimized');
});
// Minimize the window
win.minimize();
// Unlisten the minimize event
win.removeAllListeners('minimize');
// Create a new window and get it
var new_win = gui.Window.get(
window.open('https://github.com')
);
// And listen to new window's focus event
new_win.on('focus', function() {
console.log('New window is focused');
});
// Get the current window
var win = gui.Window.get();
// Create a new window and get it
var new_win = gui.Window.get(
window.open('https://github.com')
);
// png as base64string
win.capturePage(function(base64string:string){
// do something with the base64string
}, { format : 'png', datatype : 'raw'} );
// png as node buffer
win.capturePage(function(buffer:Buffer){
// do something with the buffer
}, { format : 'png', datatype : 'buffer'} );
// Open a new window.
var win = gui.Window.get(
window.open('popup.html')
);
// Release the 'win' object here after the new window is closed.
win.on('closed', function() {
win = null;
});
// Listen to main window's close event
gui.Window.get().on('close', function() {
// Hide the window to give user the feeling of closing immediately
this.hide();
// If the new window is still open then close it.
if (win != null)
win.close(true);
// After closing the new window, close the main window.
this.close(true);
});
/* MENU */
// Create an empty menu
var menu = new gui.Menu();
// Add some items
menu.append(new gui.MenuItem({ label: 'Item A' }));
menu.append(new gui.MenuItem({ label: 'Item B' }));
menu.append(new gui.MenuItem({ type: 'separator' }));
menu.append(new gui.MenuItem({ label: 'Item C' }));
// Remove one item
menu.removeAt(1);
// Popup as context menu
menu.popup(10, 10);
// Iterate menu's items
for (var i = 0; i < menu.items.length; ++i) {
console.log(menu.items[i]);
}
var win = gui.Window.get();
var nativeMenuBar = new gui.Menu({ type: "menubar" });
nativeMenuBar.createMacBuiltin("My App");
win.menu = nativeMenuBar;
nativeMenuBar.createMacBuiltin("My App", {
hideEdit: true,
hideWindow: true
});
/* MENU ITEM */
var itemc:nw.gui.MenuItem;
// Create a separator
itemc = new gui.MenuItem({ type: 'separator' });
// Create a normal item with label and icon
itemc = new gui.MenuItem({
type: "normal",
label: "I'm a menu item",
icon: "img/icon.png"
});
// Or you can omit the 'type' field for normal items
itemc = new gui.MenuItem({ label: 'Simple item' });
// Bind a callback to item
itemc = new gui.MenuItem({
label: "Click me",
click: function() {
console.log("I'm clicked");
},
key: "s",
modifiers: "ctrl-alt",
});
// You can have submenu!
var submenu = new gui.Menu();
submenu.append(new gui.MenuItem({ label: 'Item 1' }));
submenu.append(new gui.MenuItem({ label: 'Item 2' }));
submenu.append(new gui.MenuItem({ label: 'Item 3' }));
itemc.submenu = submenu;
// And everything can be changed at runtime
itemc.label = 'New label';
itemc.click = function() { console.log('New click callback'); };
/* APP */
// Print arguments
console.log(gui.App.argv);
// Quit current app
gui.App.quit();
// Get the name field in manifest
gui.App.manifest.name
gui.App.addOriginAccessWhitelistEntry('http://github.com/', 'app', 'myapp', true);
/* CLIPBOARD */
// We can not create a clipboard, we have to receive the system clipboard
var clipboard = gui.Clipboard.get();
// Read from clipboard
var text = clipboard.get('text');
console.log(text);
// Or write something
clipboard.set('I love node-webkit :)', 'text');
// And clear it!
clipboard.clear();
/* TRAY */
// Create a tray icon
var tray = new gui.Tray({ title: 'Tray', icon: 'img/icon.png' });
// Give it a menu
var menu = new gui.Menu();
menu.append(new gui.MenuItem({ type: 'checkbox', label: 'box1' }));
tray.menu = menu;
// Remove the tray
tray.remove();
tray = null;
/* SHELL */
// Open URL with default browser.
gui.Shell.openExternal('https://github.com/rogerwang/node-webkit');
// Open a text file with default text editor.
gui.Shell.openItem('test.txt');
// Open a file in file explorer.
gui.Shell.showItemInFolder('test.txt');
+221
View File
@@ -0,0 +1,221 @@
// Type definitions for node-webkit
// Project: https://github.com/rogerwang/node-webkit
// Definitions by: Pedro Casaubon <https://github.com/xperiments>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module nw.gui {
interface IEventEmitter {
addListener(event: string, listener: Function): EventEmitter;
on(event: string, listener: Function): EventEmitter;
once(event: string, listener: Function): EventEmitter;
removeListener(event: string, listener: Function): EventEmitter;
removeAllListeners(event?: string): EventEmitter;
setMaxListeners(n: number): void;
listeners(event: string): Function[];
emit(event: string, ...args: any[]): boolean;
}
class EventEmitter implements IEventEmitter {
addListener(event: string, listener: Function): EventEmitter;
on(event: string, listener: Function): EventEmitter;
once(event: string, listener: Function): EventEmitter;
removeListener(event: string, listener: Function): EventEmitter;
removeAllListeners(event?: string): EventEmitter;
setMaxListeners(n: number): void;
listeners(event: string): Function[];
emit(event: string, ...args: any[]): boolean;
}
export interface MenuConfig {
type?: string;
}
export interface HideMenusOptions {
hideEdit: boolean;
hideWindow: boolean;
}
export interface MenuItemConfig {
label?: string;
click?: Function;
type?: string;
submenu?: Menu;
icon?: string;
tooltip?: string;
checked?: boolean;
enabled?: boolean;
key?: string;
modifiers?: string;
}
export class MenuItem extends EventEmitter implements MenuItemConfig {
constructor(config: MenuItemConfig);
label: string;
click: Function;
type: string;
submenu: Menu;
icon: string;
tooltip: string;
checked: boolean;
enabled: boolean;
key: string;
modifiers: string;
}
export class Menu {
constructor(config?: MenuConfig);
items: MenuItem[];
append(item: MenuItem): void;
remove(item: MenuItem): void;
insert(item: MenuItem, atPosition: number): void;
removeAt(index: number): void;
popup(x: number, y: number): void;
// since v0.10.0-rc1
createMacBuiltin(appname: string, options?: HideMenusOptions): void;
}
export interface ShortcutOption {
key: string;
active: Function;
failed: Function;
}
export class Shortcut extends EventEmitter {
constructor(option: ShortcutOption);
key: string;
active: Function;
failed: Function;
}
export interface WindowManifestOptions {
title?: string;
icon?: string;
toolbar?: boolean;
frame?: boolean;
width?: number;
height?: number;
position?: string;
min_width?: number;
min_height?: number;
max_width?: number;
max_height?: number;
}
export class Window extends EventEmitter {
static get(windowObject?: any): Window;
static open(url: string, options?: WindowManifestOptions): Window;
x: number;
y: number;
width: number;
height: number;
title: string;
menu: Menu;
isFullScreen: boolean;
isKioskMode: boolean;
zoomLevel: number;
moveTo(x: number, y: number): void;
moveBy(x: number, y: number): void;
resizeTo(width: number, height: number): void;
resizeBy(width: number, height: number): void;
focus(): void;
blur(): void;
show(): void;
hide(): void;
close(force?: boolean): void;
reload(): void;
reloadIgnoringCache(): void;
maximize(): void;
unmaximize(): void;
minimize(): void;
restore(): void;
enterFullscreen(): void;
leaveFullscreen(): void;
toggleFullscreen(): void;
enterKioskMode(): void;
leaveKioskMode(): void;
toggleKioskMode(): void;
showDevTools(id?: string, headless?: boolean): void;
showDevTools(id: HTMLIFrameElement, headless?: boolean): void;
closeDevTools(): void;
isDevToolsOpen(): boolean;
setMaximumSize(width: number, height: number): void;
setMinimumSize(width: number, height: number): void;
setResizable(resizable: boolean): void;
setAlwaysOnTop(top: boolean): void;
setPosition(position: string): void;
setShowInTaskbar(show: boolean): void;
requestAttention(attention: boolean): void;
requestAttention(attention: number): void;
capturePage(callback: Function, imageformat?: string): void;
capturePage(callback: Function, config_object: { format: string; datatype: string }): void;
setProgressBar(progress: number): void;
setBadgeLabel(label: string): void;
eval(frame: HTMLIFrameElement, script: string): void;
}
export interface App {
argv: any;
fullArgv: any;
dataPath: string;
manifest: any;
clearCache(): void;
closeAllWindows(): void;
crashBrowser(): void;
crashRenderer(): void;
getProxyForURL(url: string): void;
quit(): void;
setCrashDumpDir(dir: string): void;
addOriginAccessWhitelistEntry(
sourceOrigin: string
, destinationProtocol: string
, destinationHost: string
, allowDestinationSubdomains: boolean
): void;
removeOriginAccessWhitelistEntry(
sourceOrigin: string
, destinationProtocol: string
, destinationHost: string
, allowDestinationSubdomains: boolean
): void;
registerGlobalHotKey(shortcut: Shortcut): void;
unregisterGlobalHotKey(shortcut: Shortcut): void;
}
export class Clipboard {
static get(): Clipboard;
get(type?: string): string;
set(data: string, type?: string): void;
clear(): void;
}
export interface TrayOption {
title?: string;
tooltip?: string;
icon?: string;
alticon?: string;
menu?: Menu;
}
export class Tray implements TrayOption {
constructor(option: TrayOption);
title: string;
tooltip: string;
icon: string;
alticon: string;
menu: Menu;
remove(): void;
}
interface Shell {
openExternal(uri: string): void;
openItem(file_path: string): void;
showItemInFolder(file_path: string): void;
}
export var App: App;
export var Shell: Shell;
}
+14 -12
View File
@@ -50,6 +50,7 @@ declare var exports: any;
declare var SlowBuffer: {
new (str: string, encoding?: string): Buffer;
new (size: number): Buffer;
new (size: Uint8Array): Buffer;
new (array: any[]): Buffer;
prototype: Buffer;
isBuffer(obj: any): boolean;
@@ -63,6 +64,7 @@ interface Buffer extends NodeBuffer {}
declare var Buffer: {
new (str: string, encoding?: string): Buffer;
new (size: number): Buffer;
new (size: Uint8Array): Buffer;
new (array: any[]): Buffer;
prototype: Buffer;
isBuffer(obj: any): boolean;
@@ -760,18 +762,18 @@ declare module "net" {
declare module "dgram" {
import events = require("events");
interface RemoteInfo {
address: string;
port: number;
size: number;
}
interface AddressInfo {
address: string;
family: string;
port: number;
}
interface RemoteInfo {
address: string;
port: number;
size: number;
}
interface AddressInfo {
address: string;
family: string;
port: number;
}
export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket;
interface Socket extends events.EventEmitter {
+68
View File
@@ -0,0 +1,68 @@
/// <reference path="object-path.d.ts" />
var
object = {
one: 1,
two: {
three: 3,
four: ['4']
}
},
array: any[] = [],
Null:any = null;
objectPath.del<string[]>(array) === ['12'];
objectPath.del<typeof object>(object) === object;
objectPath.del(object) === object;
objectPath.del() === void 0;
objectPath.del(object, ['1','2','3']);
objectPath.del(object, [1,2,3]);
objectPath.del(object, 1);
objectPath.del(object, 'one').one === 1;
objectPath.coalesce(object, ['1','2']) === void 0;
objectPath.coalesce(object, ['1',['2','1']]) === void 0;
objectPath.coalesce(object, ['1',['2','1']], 1) === 1;
objectPath.coalesce(object, [1,1], 1) === 1;
objectPath.coalesce(object, <Array<number[]>>[1,[1,1]], 1) === 1;
objectPath.ensureExists(object, '1.2', 2);
objectPath.ensureExists(object, 1, 2);
objectPath.ensureExists(object, [1,2], 2);
objectPath.ensureExists(object, ['1','2'], 2);
objectPath.ensureExists<typeof object, number>(object, ['1','2'], 2) === 3;
objectPath.ensureExists<typeof object, any[][]>(object, ['1','2'], 2) === [[]];
objectPath.push(object, 1, 1,2,3,4);
objectPath.push(object, 1, 1,'2', 3, false);
objectPath.push(object, 'one.four', 1,'2', 3, false);
objectPath.push(object, ['one','two'], [1,'2', 3, false]);
objectPath.get(array) === array;
objectPath.get(Null) === Null;
objectPath.get() === void 0;
objectPath.get(object, 'one') === 1;
objectPath.get(object, ['two','three']) === 3;
objectPath.get(object, ['three'], 3) === 3;
objectPath.get(object, 'three', 3) === 3;
objectPath.get(object, 0, 3) === 3;
objectPath.get(object, 0, '3') === '3';
objectPath.get<typeof object, string[]>(object, 0, ['1','2']) === ['1','2'];
objectPath.get<typeof object, number>(object, 0) === 10;
objectPath.set(object, '1.2', true);
objectPath.set(object, ['1','2'], true);
objectPath.set(object, [1, 2], true);
objectPath.set(object, '1.2', true, true);
objectPath.set(object, '1.2', true, false);
objectPath.set<typeof object, string[]>(object, '1.2', true, false) === ['string'];
objectPath.set<typeof object, typeof object>(object, '1.2', true, false) === object;
objectPath.insert(object, '1.2', 1);
objectPath.insert(object, ['1','2'], 1);
objectPath.insert(object, 1, 1);
objectPath.insert(object, [1,2], 1);
objectPath.insert(object, '1.2', 1, 2);
objectPath.insert(object, ['1.2'], 1, 6);
+238
View File
@@ -0,0 +1,238 @@
// Type definitions for objectPath v0.6.0
// Project: https://github.com/mariocasciaro/object-path
// Definitions by: Paulo Cesar <https://github.com/pocesar/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare var objectPath: objectPath.IObjectPathStatic;
declare module objectPath {
interface IStringArray {
[index: number]: string;
}
interface INumberArray {
[index: number]: number;
}
interface IObjectPathStatic {
/*======== Del =========*/
/**
* Deletes a member from object or array
* @param {object} object
* @param {string[]|string} path
* @return object
*/
del<T extends {}>(object: T, path: IStringArray): T;
/**
* @see objectPath.del
*/
del<T extends {}>(object: T, path: INumberArray): T;
/**
* @see objectPath.del
*/
del<T extends {}>(object: T, path: number): T;
/**
* @see objectPath.del
*/
del<T extends {}>(object: T, path: string): T;
/**
* @see objectPath.del
*/
del<T extends {}>(object: T): T;
/**
* @see objectPath.del
*/
del():void;
/*======== Get =========*/
/**
* Get a path from an object
* @param {object} object
* @param {string|string[]|number|number[]} path
* @param {*} [defaultValue=undefined]
*/
get<T extends {}, TResult>(object: T, path: string, defaultValue?: TResult): TResult;
/**
* @see objectPath.get
*/
get<T extends {}, TResult>(object: T, path: IStringArray, defaultValue?: TResult): TResult;
/**
* @see objectPath.get
*/
get<T extends {}, TResult>(object: T, path: number, defaultValue?: TResult): TResult;
/**
* @see objectPath.get
*/
get<T extends {}, TResult>(object: T, path: INumberArray, defaultValue?: TResult): TResult;
/**
* @see objectPath.get
*/
get<T extends {}>(object: T): T;
/**
* @see objectPath.get
*/
get():void;
/*======== Set =========*/
/**
* Set a path to a value
* @param {object} object
* @param {string|string[]|number|number[]} path
* @param {*} value
* @param {boolean} [doNotReplace=false]
* @return Any existing value on the path if any
*/
set<T extends {}, TExisting>(object: T, path: string, value: any, doNotReplace?:boolean): TExisting;
/**
* @see objectPath.set
*/
set<T extends {}, TExisting>(object: T, path: number, value: any, doNotReplace?:boolean): TExisting;
/**
* @see objectPath.set
*/
set<T extends {}, TExisting>(object: T, path: IStringArray, value: any, doNotReplace?:boolean): TExisting;
/**
* @see objectPath.set
*/
set<T extends {}, TExisting>(object: T, path: INumberArray, value: any, doNotReplace?:boolean): TExisting;
/**
* @see objectPath.set
*/
set<T extends {}>(object: T): T;
/**
* @see objectPath.set
*/
set():void;
/*======== Push =========*/
/**
* Create (if path isn't an array) and push the value to it. Can push unlimited number of values
* @param {object} object
*/
push<T extends {}>(object: T, path: INumberArray, ...args:any[]):void;
/**
* @see objectPath.push
*/
push<T extends {}>(object: T, path: IStringArray, ...args:any[]):void;
/**
* @see objectPath.push
*/
push<T extends {}>(object: T, path: number, ...args:any[]):void;
/**
* @see objectPath.push
*/
push<T extends {}>(object: T, path: string, ...args:any[]):void;
/**
* @see objectPath.push
*/
push():void;
/*======== Coalesce =========*/
/**
* Get the first non undefined property
* @param {object} object
* @param {string[]|string[][]|number[]|number[][]} paths
* @param {*} defaultValue
* @return {*}
*/
coalesce<T extends {}, TResult>(object: T, paths: IStringArray, defaultValue?: any):TResult;
/**
* @see objectPath.coalesce
*/
coalesce<T extends {}, TResult>(object: T, paths: INumberArray, defaultValue?: any):TResult;
/**
* @see objectPath.coalesce
*/
coalesce<T extends {}, TResult>(object: T, paths: IStringArray[], defaultValue?: any):TResult;
/**
* @see objectPath.coalesce
*/
coalesce<T extends {}, TResult>(object: T, paths: INumberArray[], defaultValue?: any):TResult;
/*======== Empty =========*/
/**
* Empty a path. Arrays are set to length 0, objects have all elements deleted, strings
* are set to empty, numbers to 0, everything else is set to null
* @param {object} object
* @param {string|string[]|number[]} path
*/
empty<T extends {}, TResult>(object: T, path: string):TResult;
/**
* @see objectPath.empty
*/
empty<T extends {}, TResult>(object: T, path: INumberArray):TResult;
/**
* @see objectPath.empty
*/
empty<T extends {}, TResult>(object: T, path: IStringArray):TResult;
/**
* @see objectPath.empty
*/
empty<T extends {}, TResult>(object: T, path: number):TResult;
/**
* @see objectPath.empty
*/
empty<T extends {}>(object: T):T;
/**
* @see objectPath.empty
*/
empty():void;
/*======== EnsureExists =========*/
/**
* Set a value if it doesn't exist, do nothing if it does
* @param {object} object
* @param {string|string[]|number|number[]} path
*/
ensureExists<T extends {}, TResult>(object: T, path: string, value: any):TResult;
/**
* @see objectPath.ensureExists
*/
ensureExists<T extends {}, TResult>(object: T, path: number, value: any):TResult;
/**
* @see objectPath.ensureExists
*/
ensureExists<T extends {}, TResult>(object: T, path: INumberArray, value: any):TResult;
/**
* @see objectPath.ensureExists
*/
ensureExists<T extends {}, TResult>(object: T, path: IStringArray, value: any):TResult;
/**
* @see objectPath.ensureExists
*/
ensureExists<T extends {}>(object: T): T;
/**
* @see objectPath.ensureExists
*/
ensureExists():void;
/*======== Insert =========*/
/**
* Insert an item in an array path
* @param {object} object
* @param {string|string[]|number|number[]} path
* @param {*} value
* @param {number} [at=0]
*/
insert<T extends {}>(object: T, path: string, value: any, at?: number):void;
/**
* @see objectPath.insert
*/
insert<T extends {}>(object: T, path: INumberArray, value: any, at?: number):void;
/**
* @see objectPath.insert
*/
insert<T extends {}>(object: T, path: IStringArray, value: any, at?: number):void;
/**
* @see objectPath.insert
*/
insert<T extends {}>(object: T, path: number, value: any, at?: number):void;
}
}
declare module 'objectPath' {
export = objectPath;
}
+6
View File
@@ -5,6 +5,12 @@
/// <reference path="../express/express.d.ts" />
declare module Express {
export interface Request {
session?: any;
}
}
declare module 'passport' {
import express = require('express');
+32 -2
View File
@@ -1,6 +1,6 @@
// Type definitions for PhoneGap 2.3
// Project: http://phonegap.com
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, Dick van den Brink <https://github.com/DickvdBrink>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface GeolocationError {
@@ -367,7 +367,7 @@ interface FileUploadResult {
interface Flags {
create: boolean;
exclusive: boolean;
exclusive?: boolean;
}
/*
@@ -575,6 +575,36 @@ interface LocalStorage {
}
*/
interface StatusBar {
isVisible: boolean;
overlaysWebView(doOverlay: boolean): void;
styleDefault(): void;
styleLightContent(): void;
styleBlackTranslucent(): void;
styleBlackOpaque(): void;
backgroundColorByName(colorname: string): void;
backgroundColorByHexString(hexString: string): void;
hide(): void;
show(): void;
}
declare var StatusBar: StatusBar;
interface Keyboard {
automaticScrollToTopOnHiding: boolean;
isVisible: boolean;
onshow: Function;
onhide: Function;
onshowing: Function;
onhiding: Function;
disableScrollingInShrinkView(disable: boolean): void;
hideFormAccessoryBar(hide: boolean): void;
shrinkView(shrink: boolean): void;
}
declare var Keyboard: Keyboard;
interface /*PhoneGapNavigator extends*/ Navigator {
accelerometer: Accelerometer;
camera: Camera;
+47
View File
@@ -0,0 +1,47 @@
import Q = require('q');
import promisePool = require('promise-pool');
var pool = new promisePool.Pool<number>((taskDataId, index) => {
return Q.delay(Math.floor(Math.random() * 5000)).then(function () {
taskDataId == 0;
index == 0;
});
}, 20);
pool
.pause()
.delay(5000)
.then(function () {
pool.resume();
});
pool.retries == 0;
pool.retryInterval == 0;
pool.maxRetryInterval == 0;
pool.retryIntervalMultiplier == 0;
pool.add(0);
pool
.start(onProgress)
.then(result => {
result.total == 0;
return pool.reset();
})
.then(() => {
return pool.start(onProgress);
})
.then(result => {
result.total == 0;
return pool.reset();
})
.then(() => {
pool.endless == true;
});
function onProgress(progress: promisePool.IProgress) {
progress.success == true;
progress.fulfilled == 0;
progress.total == 0;
progress.index == 0;
}
+124
View File
@@ -0,0 +1,124 @@
// Type definitions for promise-pool
// Project: https://github.com/vilic/promise-pool
// Definitions by: VILIC VANE <https://github.com/vilic>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../q-retry/q-retry.d.ts" />
declare module "promise-pool" {
/**
* interface for the final result.
*/
export interface IResult {
fulfilled: number;
rejected: number;
total: number;
}
/**
* interface for progress data.
*/
export interface IProgress {
index: number;
success: boolean;
error: any;
retries: number;
fulfilled: number;
rejected: number;
pending: number;
total: number;
}
/**
* tasks pool that manages concurrency.
*/
export class Pool<T> {
/**
* (get/set) the max concurrency of this task pool.
*/
public concurrency: number;
private _tasksData;
/**
* (get/set) the processor function that handles tasks data.
*/
public processor: (data: T, index: number) => Q.IPromise<void>;
private _deferred;
private _pauseDeferred;
/**
* (get) the number of successful tasks.
*/
public fulfilled: number;
/**
* (get) the number of failed tasks.
*/
public rejected: number;
/**
* (get) the number of pending tasks.
*/
public pending: number;
/**
* (get) the number of completed tasks and pending tasks in total.
*/
public total: number;
/**
* (get/set) indicates whether this task pool is endless, if so, tasks can still be added even after all previous tasks have been fulfilled.
*/
public endless: boolean;
/**
* (get/set) defaults to 0, the number or retries that this task pool will take for every single task, could be Infinity.
*/
public retries: number;
/**
* (get/set) defaults to 0, interval (milliseconds) between each retries.
*/
public retryInterval: number;
/**
* (get/set) defaults to Infinity, max retry interval when retry interval multiplier applied.
*/
public maxRetryInterval: number;
/**
* (get/set) defaults to 1, the multiplier applies to interval after every retry.
*/
public retryIntervalMultiplier: number;
private _index;
private _currentConcurrency;
public onProgress: (progress: IProgress) => void;
/**
* initialize a task pool.
* @param processor a function takes the data and index as parameters and returns a promise.
* @param concurrency the concurrency of this task pool.
* @param endless defaults to false. indicates whether this task pool is endless, if so, tasks can still be added even after all previous tasks have been fulfilled.
* @param tasksData an initializing array of task data.
*/
constructor(processor: (data: T, index: number) => Q.IPromise<void>, concurrency: number, endless?: boolean, tasksData?: T[]);
/**
* add a data item.
* @param taskData task data to add.
*/
public add(taskData: T): void;
/**
* add data items.
* @param tasskData tasks data to add.
*/
public add(tasksData: T[]): void;
/**
* start tasks, return a promise that will be fulfilled after all tasks accomplish if endless is false.
* @param onProgress a callback that will be triggered every time when a single task is fulfilled.
*/
public start(onProgress?: (progress: IProgress) => void): Q.Promise<IResult>;
private _start();
private _process(data, index);
private _notifyProgress(index, success, err, retries);
private _next();
/**
* pause tasks and return a promise that will be fulfilled after the running tasks accomplish. this will wait for running tasks to complete instead of aborting them.
*/
public pause(): Q.Promise<void>;
/**
* resume tasks.
*/
public resume(): void;
/**
* pause tasks, then clear pending tasks data and reset counters. return a promise that will be fulfilled after resetting accomplish.
*/
public reset(): Q.Promise<void>;
}
}
+39
View File
@@ -0,0 +1,39 @@
import Q = require('q-retry');
Q
.retry(() => {
return '';
})
.then(str => {
str.charAt;
return 0;
})
.retry(num => {
num.toFixed;
})
.retry(() => {
}, 5)
.retry(() => {
}, (reason, retries) => {
retries.toFixed;
})
.retry(() => {
}, (reason, retries) => {
retries.toFixed;
}, 10)
.retry(() => {
return '';
}, (reason, retries) => {
}, {
limit: 10,
interval: 1000,
maxInterval: 20000,
intervalMultiplier: 1.5
})
.then(str => {
str.charAt;
});
+39
View File
@@ -0,0 +1,39 @@
// Type definitions for q-retry
// Project: https://github.com/vilic/q-retry
// Definitions by: VILIC VANE <https://github.com/vilic>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../q/Q.d.ts" />
declare module Q {
export interface IRetryOptions {
limit?: number;
interval?: number;
maxInterval?: number;
intervalMultiplier?: number;
}
export function retry<U>(process: () => IPromise<U>, onFail: (reason: any, retries: number) => void, limit: number): Promise<U>;
export function retry<U>(process: () => IPromise<U>, onFail: (reason: any, retries: number) => void, options?: IRetryOptions): Promise<U>;
export function retry<U>(process: () => IPromise<U>, limit: number): Promise<U>;
export function retry<U>(process: () => IPromise<U>, options?: IRetryOptions): Promise<U>;
export function retry<U>(process: () => U, onFail: (reason: any, retries: number) => void, limit: number): Promise<U>;
export function retry<U>(process: () => U, onFail: (reason: any, retries: number) => void, options?: IRetryOptions): Promise<U>;
export function retry<U>(process: () => U, limit: number): Promise<U>;
export function retry<U>(process: () => U, options?: IRetryOptions): Promise<U>;
interface Promise<T> {
retry<U>(process: (value: T) => IPromise<U>, onFail: (reason: any, retries: number) => void, limit: number): Promise<U>;
retry<U>(process: (value: T) => IPromise<U>, onFail: (reason: any, retries: number) => void, options?: IRetryOptions): Promise<U>;
retry<U>(process: (value: T) => IPromise<U>, limit: number): Promise<U>;
retry<U>(process: (value: T) => IPromise<U>, options?: IRetryOptions): Promise<U>;
retry<U>(process: (value: T) => U, onFail: (reason: any, retries: number) => void, limit: number): Promise<U>;
retry<U>(process: (value: T) => U, onFail: (reason: any, retries: number) => void, options?: IRetryOptions): Promise<U>;
retry<U>(process: (value: T) => U, limit: number): Promise<U>;
retry<U>(process: (value: T) => U, options?: IRetryOptions): Promise<U>;
}
}
declare module "q-retry" {
export = Q;
}
Vendored
+5 -1
View File
@@ -214,6 +214,7 @@ declare module Q {
export function nfapply<T>(nodeFunction: Function, args: any[]): Promise<T>;
export function ninvoke<T>(nodeModule: any, functionName: string, ...args: any[]): Promise<T>;
export function npost<T>(nodeModule: any, functionName: string, args: any[]): Promise<T>;
export function nsend<T>(nodeModule: any, functionName: string, ...args: any[]): Promise<T>;
export function nmcall<T>(nodeModule: any, functionName: string, ...args: any[]): Promise<T>;
@@ -293,7 +294,10 @@ declare module Q {
* Returns a promise that will have the same result as promise, but will only be fulfilled or rejected after at least ms milliseconds have passed.
*/
export function delay<T>(value: T, ms: number): Promise<T>;
/**
* Returns a promise that will be fulfilled with undefined after at least ms milliseconds have passed.
*/
export function delay(ms: number): Promise <void>;
/**
* Returns whether a given promise is in the fulfilled state. When the static version is used on non-promises, the result is always true.
*/
+4 -4
View File
@@ -381,7 +381,7 @@ interface QUnitStatic extends QUnitAssert{
* @param expected Number of assertions in this test
* @param test Function to close over assertions
*/
asyncTest(name: string, expected: number, test: () => any): any;
asyncTest(name: string, expected: number, test: (assert: QUnitAssert) => any): any;
/**
* Add an asynchronous test to run. The test must include a call to start().
@@ -392,7 +392,7 @@ interface QUnitStatic extends QUnitAssert{
* @param name Title of unit being tested
* @param test Function to close over assertions
*/
asyncTest(name: string, test: () => any): any;
asyncTest(name: string, test: (assert: QUnitAssert) => any): any;
/**
* Specify how many assertions are expected to run within a test.
@@ -662,7 +662,7 @@ declare function testStart(callback: (details: TestStartCallbackObject) => any):
* @param expected Number of assertions in this test
* @param test Function to close over assertions
*/
declare function asyncTest(name: string, expected?: any, test?: () => any): any;
declare function asyncTest(name: string, expected?: any, test?: (assert: QUnitAssert) => any): any;
/**
* Add an asynchronous test to run. The test must include a call to start().
@@ -673,7 +673,7 @@ declare function asyncTest(name: string, expected?: any, test?: () => any): any;
* @param name Title of unit being tested
* @param test Function to close over assertions
*/
declare function asyncTest(name: string, test: () => any): any;
declare function asyncTest(name: string, test: (assert: QUnitAssert) => any): any;
/**
* Specify how many assertions are expected to run within a test.
+52
View File
@@ -0,0 +1,52 @@
/// <reference path="recaptcha.d.ts"/>
var recaptchaOptions: RecaptchaOptions = {
theme : 'custom',
custom_theme_widget: 'recaptcha_widget'
};
var recaptchaOptions: RecaptchaOptions = {
custom_translations: { instructions_visual: "This is my text:" }
};
var recaptchaOptions: RecaptchaOptions = {
custom_translations: {
instructions_visual: "Scrivi le due parole:",
instructions_audio: "Trascrivi ci\u00f2 che senti:",
play_again: "Riascolta la traccia audio",
cant_hear_this: "Scarica la traccia in formato MP3",
visual_challenge: "Modalit\u00e0 visiva",
audio_challenge: "Modalit\u00e0 auditiva",
refresh_btn: "Chiedi due nuove parole",
help_btn: "Aiuto",
incorrect_try_again: "Scorretto. Riprova.",
},
lang: 'it',
theme: 'red'
};
var recaptchaOptions: RecaptchaOptions = {
theme : 'white',
tabindex : 2
};
Recaptcha.create("public_key_a",
"element_id_a",
{
theme: "red",
callback: Recaptcha.focus_response_field
}
);
Recaptcha.create("public_key_b",
"element_id_b",
recaptchaOptions
);
Recaptcha.switch_type("audio");
Recaptcha.get_challenge();
Recaptcha.get_response();
Recaptcha.reload();
Recaptcha.showhelp();
Recaptcha.focus_response_field();
Recaptcha.destroy();
+39
View File
@@ -0,0 +1,39 @@
// Type definitions for Google Recaptcha
// Project: https://www.google.com/recaptcha
// Definitions by: Brent Jenkins <https://github.com/brentj73>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare class Recaptcha {
constructor();
static reload(): void;
static switch_type(newtype: string): void;
static showhelp(): void;
static get_challenge(): string;
static get_response(): string;
static focus_response_field(): void;
static create(public_key: string, element: string, options: RecaptchaOptions): void;
static destroy(): void;
}
interface RecaptchaOptions {
tabindex?: number;
theme?: string;
callback?: Function;
lang?: string;
custom_theme_widget?: string;
custom_translations?: CustomTranslations;
}
interface CustomTranslations {
visual_challenge?: string;
audio_challenge?: string;
refresh_btn?: string;
instructions_visual?: string;
instructions_audio?: string;
help_btn?: string;
play_again?: string;
cant_hear_this?: string;
incorrect_try_again?: string;
image_alt_text?: string;
privacy_and_terms?: string;
}
+1 -1
View File
@@ -4573,7 +4573,7 @@ declare module SP {
get_id(): number;
get_information(): SP.TimeZoneInformation;
localTimeToUTC(date: Date): SP.DateTimeResult;
uTCToLocalTime(date: Date): SP.DateTimeResult;
utcToLocalTime(date: Date): SP.DateTimeResult;
}
export class TimeZoneCollection extends SP.ClientObjectCollection<TimeZone> {
itemAt(index: number): SP.TimeZone;
+267
View File
@@ -0,0 +1,267 @@
/// <reference path="./sjcl.d.ts" />
var b: boolean;
var n: number;
var s: string;
var bn: sjcl.BigNumber;
var ba: sjcl.BitArray;
function testBigNumber() {
bn = new sjcl.bn();
bn = new sjcl.bn(0);
bn = new sjcl.bn("0");
bn = new sjcl.bn(bn);
bn = bn.initWith(0);
bn = bn.initWith("0");
bn = bn.initWith(bn);
bn = bn.addM(0);
bn = bn.addM("0");
bn = bn.addM(bn);
bn = bn.subM(0);
bn = bn.subM("0");
bn = bn.subM(bn);
bn = bn.mod(0);
bn = bn.mod("0");
bn = bn.mod(bn);
bn = bn.inverseMod(0);
bn = bn.inverseMod("0");
bn = bn.inverseMod(bn);
bn = bn.add(0);
bn = bn.add("0");
bn = bn.add(bn);
bn = bn.sub(0);
bn = bn.sub("0");
bn = bn.sub(bn);
bn = bn.mul(0);
bn = bn.mul("0");
bn = bn.mul(bn);
bn = bn.mulmod(0, 0);
bn = bn.mulmod(0, "0");
bn = bn.mulmod(0, bn);
bn = bn.mulmod("0", 0);
bn = bn.mulmod("0", "0");
bn = bn.mulmod("0", bn);
bn = bn.mulmod(bn, 0);
bn = bn.mulmod(bn, "0");
bn = bn.mulmod(bn, bn);
bn = bn.powermod(0, 0);
bn = bn.powermod(0, "0");
bn = bn.powermod(0, bn);
bn = bn.powermod("0", 0);
bn = bn.powermod("0", "0");
bn = bn.powermod("0", bn);
bn = bn.powermod(bn, 0);
bn = bn.powermod(bn, "0");
bn = bn.powermod(bn, bn);
bn = bn.copy();
b = bn.equals(0);
b = bn.equals(bn);
b = bn.greaterEquals(0);
b = bn.greaterEquals(bn);
n = bn.getLimb(0);
s = bn.toString();
bn = bn.doubleM();
bn = bn.halveM();
bn = bn.square();
bn = bn.power(1);
bn = bn.power([1, 1]);
bn = bn.power(bn);
bn = bn.trim();
bn = bn.reduce();
bn = bn.fullReduce();
bn = bn.normalize();
bn = bn.cnormalize();
ba = bn.toBits();
ba = bn.toBits(1);
n = bn.bitLength();
bn = sjcl.bn.fromBits(ba);
}
function testBitArray() {
ba = sjcl.bitArray.bitSlice(ba, 0, 1);
n = sjcl.bitArray.extract(ba, 0, 1);
ba = sjcl.bitArray.concat(ba, ba);
n = sjcl.bitArray.bitLength(ba);
ba = sjcl.bitArray.clamp(ba, 0);
n = sjcl.bitArray.partial(1, 1);
n = sjcl.bitArray.partial(1, 1, 0);
n = sjcl.bitArray.getPartial(0);
b = sjcl.bitArray.equal(ba, ba);
ba = sjcl.bitArray._shiftRight(ba, 0);
ba = sjcl.bitArray._shiftRight(ba, 0, 0);
ba = sjcl.bitArray._shiftRight(ba, 0, 0, ba);
}
function testCodecs() {
s = sjcl.codec.base64.fromBits(ba);
ba = sjcl.codec.base64.toBits(s);
s = sjcl.codec.base64url.fromBits(ba);
ba = sjcl.codec.base64url.toBits(s);
s = sjcl.codec.hex.fromBits(ba);
ba = sjcl.codec.hex.toBits(s);
s = sjcl.codec.utf8String.fromBits(ba);
ba = sjcl.codec.utf8String.toBits(s);
var bytes: number[] = sjcl.codec.bytes.fromBits(ba);
ba = sjcl.codec.bytes.toBits(bytes);
}
function testHashes() {
var hash: sjcl.SjclHash;
ba = hash.reset().update("xxx").update(ba).finalize();
hash = new sjcl.hash.sha1();
hash = new sjcl.hash.sha1(hash);
ba = sjcl.hash.sha1.hash(ba);
ba = sjcl.hash.sha1.hash("xxx");
hash = new sjcl.hash.sha256();
hash = new sjcl.hash.sha256(hash);
ba = sjcl.hash.sha256.hash(ba);
ba = sjcl.hash.sha256.hash("xxx");
hash = new sjcl.hash.sha512();
hash = new sjcl.hash.sha512(hash);
ba = sjcl.hash.sha512.hash(ba);
ba = sjcl.hash.sha512.hash("xxx");
}
function testSymetric() {
var aes = new sjcl.cipher.aes([0, 0, 0, 0]);
ba = sjcl.mode.cbc.encrypt(aes, ba, ba);
ba = sjcl.mode.cbc.encrypt(aes, ba, ba, ba);
ba = sjcl.mode.gcm.encrypt(aes, ba, ba);
ba = sjcl.mode.gcm.encrypt(aes, ba, ba, ba);
ba = sjcl.mode.gcm.encrypt(aes, ba, ba, ba, 128);
ba = sjcl.mode.ccm.encrypt(aes, ba, ba);
ba = sjcl.mode.ccm.encrypt(aes, ba, ba, ba);
ba = sjcl.mode.ccm.encrypt(aes, ba, ba, ba, 128);
ba = sjcl.mode.ocb2.encrypt(aes, ba, ba);
ba = sjcl.mode.ocb2.encrypt(aes, ba, ba, ba);
ba = sjcl.mode.ocb2.encrypt(aes, ba, ba, ba, 128);
ba = sjcl.mode.ocb2.encrypt(aes, ba, ba, ba, 128, false);
}
function testHmacPbdkf2() {
ba = sjcl.misc.pbkdf2("xxx", "xxx");
ba = sjcl.misc.pbkdf2("xxx", "xxx", 1000);
ba = sjcl.misc.pbkdf2("xxx", "xxx", 1000, 12);
ba = sjcl.misc.pbkdf2("xxx", "xxx", 1000, 12, sjcl.misc.hmac);
ba = sjcl.misc.pbkdf2("xxx", ba);
ba = sjcl.misc.pbkdf2("xxx", ba, 1000);
ba = sjcl.misc.pbkdf2("xxx", ba, 1000, 12);
ba = sjcl.misc.pbkdf2("xxx", ba, 1000, 12, sjcl.misc.hmac);
ba = sjcl.misc.pbkdf2(ba, "xxx");
ba = sjcl.misc.pbkdf2(ba, "xxx", 1000);
ba = sjcl.misc.pbkdf2(ba, "xxx", 1000, 12);
ba = sjcl.misc.pbkdf2(ba, "xxx", 1000, 12, sjcl.misc.hmac);
ba = sjcl.misc.pbkdf2(ba, ba);
ba = sjcl.misc.pbkdf2(ba, ba, 1000);
ba = sjcl.misc.pbkdf2(ba, ba, 1000, 12);
ba = sjcl.misc.pbkdf2(ba, ba, 1000, 12, sjcl.misc.hmac);
var hmac: sjcl.SjclHmac;
hmac = new sjcl.misc.hmac(ba);
hmac = new sjcl.misc.hmac(ba, sjcl.hash.sha512);
ba = hmac.mac("xxx");
ba = hmac.mac(ba);
ba = hmac.encrypt("xxx");
ba = hmac.encrypt(ba);
hmac.reset();
hmac.update("xxx");
hmac.update(ba);
ba = hmac.digest();
}
function testECC() {
var keys = sjcl.ecc.elGamal.generateKeys(192, 0);
var ciphertext = sjcl.encrypt(keys.pub, "hello world");
var plaintext = sjcl.decrypt(keys.sec, ciphertext);
// TODO: Maybe deeper testing required. Let me know
}
function testRandom() {
b = sjcl.random.isReady();
ba = sjcl.random.randomWords(8);
ba = sjcl.random.randomWords(8, 6);
var rnd = new sjcl.prng(1);
ba = rnd.randomWords(16);
ba = rnd.randomWords(16, 6);
}
function testSRP() {
var group = sjcl.keyexchange.srp.knownGroup(1024);
ba = sjcl.codec.hex.toBits(s);
ba = sjcl.keyexchange.srp.makeX(s, s, ba);
ba = sjcl.keyexchange.srp.makeVerifier(s, s, ba, group);
}
function testConvenince() {
var x: sjcl.SjclCipherEncrypted;
x = sjcl.encrypt("xxx", "text");
s = sjcl.decrypt(ba, x);
x = sjcl.encrypt("xxx", "text", { iv: ba, salt: ba });
s = sjcl.decrypt(ba, x, { iv: ba, salt: ba });
var y: sjcl.SjclCipherDecrypted;
sjcl.encrypt("xxx", "text", { iv: ba, salt: ba, mode: "gcm" }, x);
s = sjcl.decrypt(ba, x, { iv: ba, salt: ba, mode: "gcm" }, y);
sjcl.encrypt("xxx", "text", { iv: ba, salt: ba, mode: "gcm", iter: 200 }, x);
s = sjcl.decrypt(ba, x, { iv: ba, salt: ba, mode: "gcm", iter: 200 }, y);
}
+556
View File
@@ -0,0 +1,556 @@
// Type definitions for sjcl v1.0.1
// Project: http://crypto.stanford.edu/sjcl/
// Definitions by: Eugene Chernyshov <https://github.com/Evgenus>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module sjcl {
export var bn: BigNumberStatic;
export var bitArray: BitArrayStatic;
export var codec: SjclCodecs;
export var hash: SjclHashes;
export var exception: SjclExceptions;
export var cipher: SjclCiphers;
export var mode: SjclModes;
export var misc: SjclMisc;
export var ecc: SjclEllipticCurveCryptography;
export var random: SjclRandom;
export var prng: SjclRandomStatic;
export var keyexchange: SjclKeyExchange;
export var json: SjclJson;
export var encrypt: SjclConveninceEncryptor;
export var decrypt: SjclConveninceDecryptor;
// ________________________________________________________________________
interface BigNumber {
radix: number;
maxMul: number;
copy(): BigNumber;
/// Initializes this with it, either as a bn, a number, or a hex string.
initWith: TypeHelpers.BigNumberBinaryOperator;
/// Returns true if "this" and "that" are equal. Calls fullReduce().
/// Equality test is in constant time.
equals(that: number): boolean;
equals(that: BigNumber): boolean;
/// Get the i'th limb of this, zero if i is too large.
getLimb(index: number): number;
/// Constant time comparison function.
/// Returns 1 if this >= that, or zero otherwise.
greaterEquals(that: number): boolean;
greaterEquals(that: BigNumber): boolean;
/// Convert to a hex string.
toString(): string;
/// this += that. Does not normalize.
addM: TypeHelpers.BigNumberBinaryOperator;
/// this *= 2. Requires normalized; ends up normalized.
doubleM(): BigNumber;
/// this /= 2, rounded down. Requires normalized; ends up normalized.
halveM(): BigNumber;
/// this -= that. Does not normalize.
subM: TypeHelpers.BigNumberBinaryOperator;
mod: TypeHelpers.BigNumberBinaryOperator;
/// return inverse mod prime p. p must be odd. Binary extended Euclidean algorithm mod p.
inverseMod: TypeHelpers.BigNumberBinaryOperator;
/// this + that. Does not normalize.
add: TypeHelpers.BigNumberBinaryOperator;
/// this - that. Does not normalize.
sub: TypeHelpers.BigNumberBinaryOperator;
/// this * that. Normalizes and reduces.
mul: TypeHelpers.BigNumberBinaryOperator;
/// this ^ 2. Normalizes and reduces.
square(): BigNumber;
/// this ^ n. Uses square-and-multiply. Normalizes and reduces.
power(n: number): BigNumber;
power(n: BigNumber): BigNumber;
power(a: number[]): BigNumber;
/// this * that mod N
mulmod: TypeHelpers.BigNumberTrinaryOperator;
/// this ^ x mod N
powermod: TypeHelpers.BigNumberTrinaryOperator;
trim(): BigNumber;
/// Reduce mod a modulus. Stubbed for subclassing.
reduce(): BigNumber;
/// Reduce and normalize.
fullReduce(): BigNumber;
/// Propagate carries.
normalize(): BigNumber;
/// Constant-time normalize. Does not allocate additional space.
cnormalize(): BigNumber;
/// Serialize to a bit array
toBits(len?: number): BitArray;
/// Return the length in bits, rounded up to the nearest byte.
bitLength(): number;
}
interface BigNumberStatic {
new (): BigNumber;
new (n: string): BigNumber;
new (n: number): BigNumber;
new (n: BigNumber): BigNumber;
fromBits(bits: BitArray): BigNumber;
random: TypeHelpers.Bind1<number>;
prime: {
p127: PseudoMersennePrimeStatic;
// Bernstein's prime for Curve25519
p25519: PseudoMersennePrimeStatic;
// Koblitz primes
p192k: PseudoMersennePrimeStatic;
p224k: PseudoMersennePrimeStatic;
p256k: PseudoMersennePrimeStatic;
// NIST primes
p192: PseudoMersennePrimeStatic;
p224: PseudoMersennePrimeStatic;
p256: PseudoMersennePrimeStatic;
p384: PseudoMersennePrimeStatic;
p521: PseudoMersennePrimeStatic;
};
pseudoMersennePrime(exponent: number, coeff: number[][]): PseudoMersennePrimeStatic;
}
interface PseudoMersennePrime extends BigNumber {
reduce(): PseudoMersennePrime;
fullReduce(): PseudoMersennePrime;
inverse(): PseudoMersennePrime;
}
interface PseudoMersennePrimeStatic extends BigNumberStatic {
new (): PseudoMersennePrime;
new (n: string): PseudoMersennePrime;
new (n: number): PseudoMersennePrime;
new (n: BigNumber): PseudoMersennePrime;
}
// ________________________________________________________________________
interface BitArray extends Array<number> {
}
interface BitArrayStatic {
/// Array slices in units of bits.
bitSlice(a: BitArray, bstart: number, bend: number): BitArray;
/// Extract a number packed into a bit array.
extract(a: BitArray, bstart: number, blenth: number): number;
/// Concatenate two bit arrays.
concat(a1: BitArray, a2: BitArray): BitArray
/// Find the length of an array of bits.
bitLength(a: BitArray): number;
/// Truncate an array.
clamp(a: BitArray, len: number): BitArray;
/// Make a partial word for a bit array.
partial(len: number, x: number, _end?: number): number;
/// Get the number of bits used by a partial word.
getPartial(x: number): number;
/// Compare two arrays for equality in a predictable amount of time.
equal(a: BitArray, b: BitArray): boolean;
/// Shift an array right.
_shiftRight(a: BitArray, shift: number, carry?: number, out?: BitArray): BitArray;
/// xor a block of 4 words together.
_xor4(x: number[], y: number[]): number[];
}
// ________________________________________________________________________
interface SjclCodec<T> {
fromBits(bits: BitArray): T;
toBits(value: T): BitArray;
}
interface SjclCodecs {
utf8String: SjclCodec<string>;
hex: SjclCodec<string>;
bytes: SjclCodec<number[]>;
base64: SjclCodec<string>;
base64url: SjclCodec<string>;
}
// ________________________________________________________________________
interface SjclHash {
reset(): SjclHash;
update(data: string): SjclHash;
update(data: BitArray): SjclHash;
finalize(): BitArray;
}
interface SjclHashStatic {
new (hash?: SjclHash): SjclHash;
hash(data: string): BitArray;
hash(data: BitArray): BitArray;
}
interface SjclHashes {
sha1: SjclHashStatic;
sha256: SjclHashStatic;
sha512: SjclHashStatic;
}
// ________________________________________________________________________
interface SjclExceptions {
corrupt: SjclExceptionFactory;
invalid: SjclExceptionFactory;
bug: SjclExceptionFactory;
notReady: SjclExceptionFactory;
}
interface SjclExceptionFactory {
new (message: string): Error;
}
// ________________________________________________________________________
interface SjclCiphers {
aes: SjclCipherStatic;
}
interface SjclCipher {
encrypt(data: number[]): number[];
decrypt(data: number[]): number[];
}
interface SjclCipherStatic {
new (key: number[]): SjclCipher;
}
// ________________________________________________________________________
interface SjclModes {
gcm: SjclGCMMode;
ccm: SjclCCMMode;
ocb2: SjclOCB2Mode;
cbc: SjclCBCMode;
}
interface SjclGCMMode {
encrypt(prp: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray;
decrypt(prp: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray;
}
interface SjclCCMMode {
encrypt(prp: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray;
decrypt(prp: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray;
}
interface SjclOCB2Mode {
encrypt(prp: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number, premac?: boolean): BitArray;
decrypt(prp: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number, premac?: boolean): BitArray;
pmac(prp: SjclCipher, adata: BitArray): number[];
}
interface SjclCBCMode {
encrypt(prp: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray): BitArray;
decrypt(prp: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray): BitArray;
}
// ________________________________________________________________________
interface Pbkdf2Params {
iter?: number;
salt?: BitArray;
}
interface SjclMisc {
pbkdf2(password: string, salt: string, count?: number, length?: number, Prff?: SjclPseudorandomFunctionFamilyStatic): BitArray;
pbkdf2(password: BitArray, salt: string, count?: number, length?: number, Prff?: SjclPseudorandomFunctionFamilyStatic): BitArray;
pbkdf2(password: BitArray, salt: BitArray, count?: number, length?: number, Prff?: SjclPseudorandomFunctionFamilyStatic): BitArray;
pbkdf2(password: string, salt: BitArray, count?: number, length?: number, Prff?: SjclPseudorandomFunctionFamilyStatic): BitArray;
hmac: SjclHmacStatic;
cachedPbkdf2(password: string, obj?: Pbkdf2Params): {
key: BitArray;
salt: BitArray;
};
}
class SjclPseudorandomFunctionFamily {
encrypt(data: string): BitArray;
encrypt(data: BitArray): BitArray;
}
interface SjclHmac extends SjclPseudorandomFunctionFamily {
mac(data: string): BitArray;
mac(data: BitArray): BitArray;
reset(): void;
update(data: string): void;
update(data: BitArray): void;
digest(): BitArray;
}
interface SjclPseudorandomFunctionFamilyStatic {
new (key: BitArray): SjclPseudorandomFunctionFamily;
}
interface SjclHmacStatic {
new (key: BitArray, Hash?: SjclHashStatic): SjclHmac;
}
// ________________________________________________________________________
interface SjclEllipticCurveCryptography {
point: SjclEllipticalPointStatic;
pointJac: SjclPointJacobianStatic;
curve: SjclEllipticalCurveStatic;
curves: {
c192: SjclEllipticalCurve;
c224: SjclEllipticalCurve;
c256: SjclEllipticalCurve;
c384: SjclEllipticalCurve;
k192: SjclEllipticalCurve;
k224: SjclEllipticalCurve;
k256: SjclEllipticalCurve;
};
basicKey: SjclECCBasic;
elGamal: SjclElGamal;
ecdsa: SjclEcdsa;
}
interface SjclEllipticalPoint {
toJac(): SjclPointJacobian;
mult(k: BigNumber): SjclEllipticalPoint;
mult2(k: BigNumber, k2: BigNumber, affine2: SjclEllipticalPoint): SjclEllipticalPoint;
multiples(): Array<SjclEllipticalPoint>;
isValid(): boolean;
toBits(): BitArray;
}
interface SjclEllipticalPointStatic {
new (curve: SjclEllipticalCurve, x?: BigNumber, y?: BigNumber): SjclEllipticalPoint;
}
interface SjclPointJacobian {
add(T: SjclEllipticalPoint): SjclPointJacobian;
doubl(): SjclPointJacobian;
toAffine(): SjclEllipticalPoint;
mult(k: BigNumber, affine: SjclEllipticalPoint): SjclPointJacobian;
mult2(k1: BigNumber, affine: SjclEllipticalPoint, k2: BigNumber, affine2: SjclEllipticalPoint): SjclPointJacobian;
isValid(): boolean;
}
interface SjclPointJacobianStatic {
new (curve: SjclEllipticalCurve, x?: BigNumber, y?: BigNumber, z?: BigNumber):SjclPointJacobian;
}
interface SjclEllipticalCurve {
fromBits(bits: BitArray): SjclEllipticalPoint;
}
interface SjclEllipticalCurveStatic {
new (Field: BigNumber, r: BigNumber, a: BigNumber, b: BigNumber, x: BigNumber, y: BigNumber): SjclEllipticalCurve;
}
interface SjclKeyPair<P extends SjclECCPublicKey, S extends SjclECCSecretKey> {
pub: P;
sec: S;
}
interface SjclKeysGenerator<P extends SjclECCPublicKey, S extends SjclECCSecretKey> {
(curve: SjclEllipticalCurve, paranoia: number, sec?: BigNumber): SjclKeyPair<P, S>;
(curve: number, paranoia: number, sec?: BigNumber): SjclKeyPair<P, S>;
}
interface SjclECCPublicKeyData {
x: BitArray;
y: BitArray;
}
class SjclECCPublicKey {
get(): SjclECCPublicKeyData;
}
class SjclECCSecretKey {
get(): BitArray;
}
interface SjclECCPublicKeyFactory<T extends SjclECCPublicKey> {
new (curve: SjclEllipticalCurve, point: SjclEllipticalPoint): T;
new (curve: SjclEllipticalCurve, point: BitArray): T;
}
interface SjclECCSecretKeyFactory<T extends SjclECCSecretKey> {
new (curve: SjclEllipticalCurve, exponent: BigNumber): T;
}
interface SjclECCBasic {
publicKey: SjclECCPublicKeyFactory<SjclECCPublicKey>;
secretKey: SjclECCSecretKeyFactory<SjclECCSecretKey>;
generateKeys(cn: string): SjclKeysGenerator<SjclECCPublicKey, SjclECCSecretKey>;
}
class SjclElGamalPublicKey extends SjclECCPublicKey {
kem(paranoia: number): {
key: BitArray;
tag: BitArray;
};
}
class SjclElGamalSecretKey extends SjclECCSecretKey {
unkem(tag: BitArray): BitArray;
dh(pk: SjclECCPublicKey): BitArray;
}
interface SjclElGamal {
publicKey: SjclECCPublicKeyFactory<SjclElGamalPublicKey>;
secretKey: SjclECCSecretKeyFactory<SjclElGamalSecretKey>;
generateKeys: SjclKeysGenerator<SjclElGamalPublicKey, SjclElGamalSecretKey>;
}
class SjclEcdsaPublicKey extends SjclECCPublicKey {
verify(hash: BitArray, rs: BitArray, fakeLegacyVersion: boolean): boolean;
}
class SjclEcdsaSecretKey extends SjclECCSecretKey {
sign(hash: BitArray, paranoia: number, fakeLegacyVersion: boolean, fixedKForTesting?: BigNumber): BitArray;
}
interface SjclEcdsa {
publicKey: SjclECCPublicKeyFactory<SjclEcdsaPublicKey>;
secretKey: SjclECCSecretKeyFactory<SjclEcdsaSecretKey>;
generateKeys: SjclKeysGenerator<SjclEcdsaPublicKey, SjclEcdsaSecretKey>;
}
// ________________________________________________________________________
interface SjclRandom {
randomWords(nwords: number, paranoia?: number): BitArray;
setDefaultParanoia(paranoia: number, allowZeroParanoia: string): void;
addEntropy(data: number, estimatedEntropy: number, source: string): void;
addEntropy(data: number[], estimatedEntropy: number, source: string): void;
addEntropy(data: string, estimatedEntropy: number, source: string): void;
isReady(paranoia?: number): boolean;
getProgress(paranoia?: number): number;
startCollectors(): void;
stopCollectors(): void;
addEventListener(name: string, cb: Function): void;
removeEventListener(name: string, cb: Function): void;
}
interface SjclRandomStatic {
new (defaultParanoia: number): SjclRandom;
}
// ________________________________________________________________________
interface SjclKeyExchange {
srp: SecureRemotePassword;
}
interface SjclSRPGroup {
N: BigNumber;
g: BigNumber;
}
interface SecureRemotePassword {
makeVerifier(username: string, password: string, salt: BitArray, group: SjclSRPGroup): BitArray;
makeX(username: string, password: string, salt: BitArray): BitArray;
knownGroup(i: string): SjclSRPGroup;
knownGroup(i: number): SjclSRPGroup;
}
// ________________________________________________________________________
interface SjclCipherParams {
v?: number;
iter?: number;
ks?: number;
ts?: number;
mode?: string;
adata?: string;
cipher?: string;
}
interface SjclCipherEncryptParams extends SjclCipherParams {
salt: BitArray;
iv: BitArray;
}
interface SjclCipherDecryptParams extends SjclCipherParams {
salt?: BitArray;
iv?: BitArray;
}
interface SjclCipherEncrypted extends SjclCipherEncryptParams {
kemtag?: BitArray;
ct: BitArray;
}
interface SjclCipherDecrypted extends SjclCipherEncrypted {
key: BitArray;
}
interface SjclConveninceEncryptor {
(password: string, plaintext: string, params?: SjclCipherEncryptParams, rp?: SjclCipherEncrypted): SjclCipherEncrypted;
(password: BitArray, plaintext: string, params?: SjclCipherEncryptParams, rp?: SjclCipherEncrypted): SjclCipherEncrypted;
(password: SjclElGamalPublicKey, plaintext: string, params?: SjclCipherEncryptParams, rp?: SjclCipherEncrypted): SjclCipherEncrypted;
}
interface SjclConveninceDecryptor {
(password: string, ciphertext: SjclCipherEncrypted, params?: SjclCipherDecryptParams, rp?: SjclCipherDecrypted): string;
(password: BitArray, ciphertext: SjclCipherEncrypted, params?: SjclCipherDecryptParams, rp?: SjclCipherDecrypted): string;
(password: SjclElGamalSecretKey, ciphertext: SjclCipherEncrypted, params?: SjclCipherDecryptParams, rp?: SjclCipherDecrypted): string;
}
interface SjclJson {
encrypt: SjclConveninceEncryptor;
decrypt: SjclConveninceDecryptor;
encode(obj: Object): string;
decode(obj: string): Object;
}
// ________________________________________________________________________
module TypeHelpers {
interface One<T> {
(value: T): BigNumber;
}
interface BigNumberBinaryOperator extends One<number>, One<string>, One<BigNumber> {
}
interface Two<T1, T2> {
(x: T1, N: T2): BigNumber;
}
interface Bind1<T> extends Two<number, T>, Two<string, T>, Two<BigNumber, T> {
}
interface BigNumberTrinaryOperator extends Bind1<number>, Bind1<string>, Bind1<BigNumber> {
}
}
}
+12 -2
View File
@@ -47,7 +47,7 @@ grid.getDataItem(14).title;
grid.setData([{ title: "task", duration: "5 days", percentComplete: 5, start: "01/01/2013", finish: "12/12/2013", effortDriven: false }], true);
var ids = [];
var ids: string[] = [];
for (i = 0; i < grid.getDataLength(); i++) {
ids.push(grid.getDataItem(i).title);
}
@@ -82,7 +82,7 @@ class SingleCellSelectionModel extends Slick.SelectionModel<MyData, Slick.Range[
this.self._grid.onClick.unsubscribe(this.self.handleGridClick);
}
public handleGridClick(e, args) {
public handleGridClick(e: any, args: any) {
var cell = this.self._grid.getCellFromEvent(e);
if (!cell || !this.self._grid.canCellBeSelected(cell.row, cell.cell)) {
return;
@@ -200,3 +200,13 @@ grid.setCellCssStyles("test", {
var dataView = new Slick.Data.DataView<MyData>();
var gridWithDataView = new Slick.Grid<MyData>('#grid2', dataView, columns, options);
dataView.getIdxById('foo') + 5;
columns.forEach(column => {
if (column.editor !== Slick.Editors.Integer) {
return;
}
});
grid.onSort.subscribe((e, args) => {
var sortCol:string = args.sortCols[0].sortCol.field;
});
-1
View File
@@ -1 +0,0 @@
""

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