diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 7ebdcc514f..44f0d8e9a0 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -401,6 +401,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](egg.js/egg.js.d.ts) [Egg.js](https://github.com/mikeflynn/egg.js) by [Markus Peloso](https://github.com/ToastHawaii) * [:link:](ejs-locals/ejs-locals.d.ts) [ejs-locals](https://github.com/randometc/ejs-locals) by [jt000](https://github.com/jt000) * [:link:](ejs/ejs.d.ts) [ejs.js](http://ejs.co) by [Ben Liddicott](https://github.com/benliddicott/DefinitelyTyped) +* [:link:](elasticsearch/elasticsearch.d.ts) [elasticsearch](https://www.elastic.co) by [Casper Skydt](https://github.com/CasperSkydt/DefinitelyTyped), [Blake Smith](https://github.com/bfsmith/DefinitelyTyped) * [:link:](jquery.elang/jquery.elang.d.ts) [eLang](https://github.com/sumegizoltan/ELang) by [Zoltan Sumegi](https://github.com/sumegizoltan) * [:link:](github-electron/github-electron.d.ts) [Electron](http://electron.atom.io) by [jedmao](https://github.com/jedmao), [rhysd](https://rhysd.github.io), [Milan Burda](https://github.com/miniak) * [:link:](electron-builder/electron-builder.d.ts) [electron-builder](https://github.com/loopline-systems/electron-builder) by [Maxime LUCE](https://github.com/SomaticIT) diff --git a/amcharts/AmCharts.d.ts b/amcharts/AmCharts.d.ts index bbd732bb1c..4f5dbe90f7 100644 --- a/amcharts/AmCharts.d.ts +++ b/amcharts/AmCharts.d.ts @@ -27,6 +27,9 @@ declare namespace AmCharts { /** Clears all the charts on page, removes listeners and intervals. */ function clear(); + /** Handle ready event */ + function ready(Function): void; + /** Create chart by params. */ function makeChart(selector: string, params: any, delay?: number): AmChart; diff --git a/angular-es/angular-es.d.ts b/angular-es/angular-es.d.ts index 10979ae15c..0972b42da0 100644 --- a/angular-es/angular-es.d.ts +++ b/angular-es/angular-es.d.ts @@ -45,12 +45,12 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Component: (component: iComponent) => ngESDecorator; + function Component(component: iComponent): ngESDecorator; /** * Register config block */ - var Config: () => ngESDecorator; + function Config(): ngESDecorator; /** * Register constant @@ -59,7 +59,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Constant: (name: string) => ngESDecorator; + function Constant(name: string): ngESDecorator; /** * Register controller @@ -68,7 +68,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Controller: (name: string) => ngESDecorator; + function Controller(name: string): ngESDecorator; /** * Register decorator @@ -77,7 +77,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Decorator: (name: string) => ngESDecorator; + function Decorator(name: string): ngESDecorator; /** * Register directive @@ -86,7 +86,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Directive: (name: string) => ngESDecorator; + function Directive(name: string): ngESDecorator; /** * Register factory @@ -95,7 +95,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Factory: (name: string) => ngESDecorator; + function Factory(name: string): ngESDecorator; /** * Register filter @@ -104,7 +104,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Filter: (name: string) => ngESDecorator; + function Filter(name: string): ngESDecorator; /** * Add $inject property to target @@ -113,7 +113,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Inject: (...dependencies: Array) => ngESDecorator; + function Inject(...dependencies: Array): ngESDecorator; /** * Inject dependencies as properties to target @@ -122,7 +122,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var InjectAsProperty: (...dependencies: Array) => ngESDecorator; + function InjectAsProperty(...dependencies: Array): ngESDecorator; /** * Attach target to the specified module @@ -131,7 +131,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Module: (name: string) => ngESDecorator; + function Module(name: string): ngESDecorator; /** * Register provider @@ -140,14 +140,14 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Provider: (name: string) => ngESDecorator; + function Provider(name: string): ngESDecorator; /** * Register run block * * @returns {ngESDecorator} - decorated class */ - var Run: () => ngESDecorator; + function Run(): ngESDecorator; /** * Register service @@ -156,7 +156,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Service: (name: string) => ngESDecorator; + function Service(name: string): ngESDecorator; /** * Register value @@ -165,7 +165,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Value: (name: string) => ngESDecorator; + function Value(name: string): ngESDecorator; export { Component, diff --git a/angular-jwt/angular-jwt-tests.ts b/angular-jwt/angular-jwt-tests.ts index 3a6b7d6bf1..818899e829 100644 --- a/angular-jwt/angular-jwt-tests.ts +++ b/angular-jwt/angular-jwt-tests.ts @@ -15,3 +15,18 @@ var $jwtInterceptor: ng.jwt.IJwtInterceptor; $jwtInterceptor.tokenGetter = () => { return expToken; } + + +var authManager: ng.jwt.IAuthManagerServiceProvider; + +// Indicate the user is authenticated +authManager.authenticate(); + +// Indicate the user is unauthenticated +authManager.unauthenticate(); + +// Keep the user authenticated +authManager.checkAuthOnRefresh(); + +// Redirect the user on unauthorized requests +authManager.redirectWhenUnauthenticated(); \ No newline at end of file diff --git a/angular-jwt/angular-jwt.d.ts b/angular-jwt/angular-jwt.d.ts index eb02cf24df..d1f9eb085f 100644 --- a/angular-jwt/angular-jwt.d.ts +++ b/angular-jwt/angular-jwt.d.ts @@ -27,4 +27,11 @@ declare namespace angular.jwt { interface IJwtInterceptor { tokenGetter(...params : any[]): string; } + + interface IAuthManagerServiceProvider { + authenticate(): void; + unauthenticate(): void; + checkAuthOnRefresh(): void; + redirectWhenUnauthenticated(): void; + } } diff --git a/angular-material/angular-material-tests.ts b/angular-material/angular-material-tests.ts index 4464c599e3..c3ebcbaf99 100644 --- a/angular-material/angular-material-tests.ts +++ b/angular-material/angular-material-tests.ts @@ -127,15 +127,30 @@ myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.materia instance.isOpen(); instance.isLockedOpen(); }); + + $scope['onClose'] = $mdSidenav(componentId).onClose(() => {}); }); myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IToastService) => { $scope['openToast'] = () => $mdToast.show($mdToast.simple().textContent('Hello!')); + + $scope['customToast'] = () => { + var options = { + hideDelay: 3000, + position: 'top right', + controller : 'ToastCtrl', + templateUrl : 'toast-template.html', + toastClass: 'my-class' + }; + + $mdToast.show(options); + } }); myApp.controller('PanelController', ($scope: ng.IScope, $mdPanel: ng.material.IPanelService) => { $scope['createPanel'] = () => { var config = { + id: 'myPanel', template: '

Hello!

', hasBackdrop: true, disableParentScroll: true, diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts index 23da7bceb2..66852586da 100644 --- a/angular-material/angular-material.d.ts +++ b/angular-material/angular-material.d.ts @@ -22,7 +22,7 @@ declare namespace angular.material { clickOutsideToClose?: boolean; disableBackdrop?: boolean; escapeToClose?: boolean; - resolve?: {[index: string]: angular.IPromise}; + resolve?: {[index: string]: () => angular.IPromise}; controllerAs?: string; parent?: Function|string|Object; // default: root node disableParentScroll?: boolean; // default: true @@ -53,7 +53,7 @@ declare namespace angular.material { controller(controller?: string|Function): T; locals(locals?: {[index: string]: any}): T; bindToController(bindToController?: boolean): T; // default: false - resolve(resolve?: {[index: string]: angular.IPromise}): T; + resolve(resolve?: {[index: string]: () => angular.IPromise}): T; controllerAs(controllerAs?: string): T; parent(parent?: string|Element|JQuery): T; // default: root node onComplete(onComplete?: Function): T; @@ -91,7 +91,7 @@ declare namespace angular.material { controller?: string|Function; locals?: {[index: string]: any}; bindToController?: boolean; // default: false - resolve?: {[index: string]: angular.IPromise} + resolve?: {[index: string]: () => angular.IPromise} controllerAs?: string; parent?: string|Element|JQuery; // default: root node onShowing?: Function; @@ -132,6 +132,7 @@ declare namespace angular.material { close(): angular.IPromise; isOpen(): boolean; isLockedOpen(): boolean; + onClose(onClose: Function): void; } interface ISidenavService { @@ -162,10 +163,11 @@ declare namespace angular.material { preserveScope?: boolean; // default: false hideDelay?: number; // default (ms): 3000 position?: string; // any combination of 'bottom'/'left'/'top'/'right'/'fit'; default: 'bottom left' + toastClass?: string; controller?: string|Function; locals?: {[index: string]: any}; bindToController?: boolean; // default: false - resolve?: {[index: string]: angular.IPromise} + resolve?: {[index: string]: () => angular.IPromise} controllerAs?: string; parent?: string|Element|JQuery; // default: root node } @@ -291,13 +293,14 @@ declare namespace angular.material { } interface IPanelConfig { + id?: string; template?: string; templateUrl?: string; controller?: string|Function; controllerAs?: string; bindToController?: boolean; // default: true locals?: {[index: string]: any}; - resolve?: {[index: string]: angular.IPromise} + resolve?: {[index: string]: () => angular.IPromise} attachTo?: string|JQuery|Element; propagateContainerEvents?: boolean; panelClass?: string; diff --git a/angular-ui-scroll/angular-ui-scroll.d.ts b/angular-ui-scroll/angular-ui-scroll.d.ts index 168c6ba271..5f24c8ec38 100644 --- a/angular-ui-scroll/angular-ui-scroll.d.ts +++ b/angular-ui-scroll/angular-ui-scroll.d.ts @@ -42,9 +42,10 @@ declare namespace angular.ui { */ topVisibleScope: ng.IRepeatScope; /** - * calling this method reinitializes and reloads the scroller content. + * calling this method reinitializes and reloads the scroller content. + * @param startIndex is an integer indicating what item index the scroller will use to start the load process. */ - reload(): void; + reload(startIndex?: number): void; /** * Replaces the item in the buffer at the given index with the new items. * diff --git a/angularjs/angular-resource.d.ts b/angularjs/angular-resource.d.ts index 441a7e1d3d..f7e803c1c8 100644 --- a/angularjs/angular-resource.d.ts +++ b/angularjs/angular-resource.d.ts @@ -42,15 +42,20 @@ declare namespace angular.resource { (url: string, paramDefaults?: any, /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } where deleteDescriptor : IActionDescriptor */ - actions?: any, options?: IResourceOptions): IResourceClass>; + actions?: IActionHash, options?: IResourceOptions): IResourceClass>; (url: string, paramDefaults?: any, /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } where deleteDescriptor : IActionDescriptor */ - actions?: any, options?: IResourceOptions): U; + actions?: IActionHash, options?: IResourceOptions): U; (url: string, paramDefaults?: any, /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } where deleteDescriptor : IActionDescriptor */ - actions?: any, options?: IResourceOptions): IResourceClass; + actions?: IActionHash, options?: IResourceOptions): IResourceClass; + } + + // Hash of action descriptors allows custom action names + interface IActionHash { + [action: string]: IActionDescriptor } // Just a reference to facilitate describing new actions @@ -186,6 +191,12 @@ declare namespace angular { /** creating a resource service factory */ factory(name: string, resourceServiceFactoryFunction: angular.resource.IResourceServiceFactoryFunction): IModule; } + + namespace auto { + interface IInjectorService { + get(name: '$resource'): ng.resource.IResourceService; + } + } } interface Array diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 111ba86cce..1831bc0493 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1,6 +1,6 @@ // Type definitions for Angular JS 1.5 // Project: http://angularjs.org -// Definitions by: Diego Vilar +// Definitions by: Diego Vilar , Georgii Dolzhykov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -125,6 +125,7 @@ declare namespace angular { isFunction(value: any): value is Function; isNumber(value: any): value is number; isObject(value: any): value is Object; + isObject(value: any): value is T; isString(value: any): value is string; isUndefined(value: any): boolean; lowercase(str: string): string; @@ -238,7 +239,6 @@ declare namespace angular { * @param directiveFactory An injectable directive factory function. */ directive(name: string, inlineAnnotatedFunction: any[]): IModule; - directive(name: string, injectionFunction: Function): 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. @@ -1412,6 +1412,16 @@ declare namespace angular { * Absolute or relative URL of the resource that is being requested. */ url: string; + /** + * Event listeners to be bound to the XMLHttpRequest object. + * To bind events to the XMLHttpRequest upload object, use uploadEventHandlers. The handler will be called in the context of a $apply block. + */ + eventHandlers?: { [type: string]: EventListenerOrEventListenerObject }; + /** + * Event listeners to be bound to the XMLHttpRequest upload object. + * To bind events to the XMLHttpRequest object, use eventHandlers. The handler will be called in the context of a $apply block. + */ + uploadEventHandlers?: { [type: string]: EventListenerOrEventListenerObject }; } interface IHttpHeadersGetter { diff --git a/atom/atom.d.ts b/atom/atom.d.ts index 389d6ef16e..ac899ba5ac 100644 --- a/atom/atom.d.ts +++ b/atom/atom.d.ts @@ -946,9 +946,14 @@ declare namespace AtomCore { registry: any; repository: Object; scopeName: string; + tokenizeLines: (text: string) => any; // TBD } + + interface IGrammars { + grammarForScopeName(scope: string): IGrammar; + } interface IPane /* extends Theorist.Model */ { itemForURI: (uri:string)=>IEditor; @@ -1302,6 +1307,7 @@ declare namespace AtomCore { deserializers:IDeserializerManager; config: IConfig; commands: ICommandRegistry; + grammars: IGrammars; keymaps: IKeymapManager; keymap: IKeymapManager; packages: IPackageManager; diff --git a/autobind-decorator/autobind-decorator-tests.ts b/autobind-decorator/autobind-decorator-tests.ts new file mode 100644 index 0000000000..e428604802 --- /dev/null +++ b/autobind-decorator/autobind-decorator-tests.ts @@ -0,0 +1,43 @@ +/// + +import autobind = require('autobind-decorator'); + +class Test { + public static what: string = 'static'; + + @autobind + public static test(): void { + console.log(this.what); + } + + public constructor(public what: string) { + this.what = what; + } + + @autobind + public test(): void { + console.warn(this.what); + } +} + +const tester: Test = new Test('bind'); +const { test } = tester; +tester.test(); // warns 'bind'. +test(); // warns 'bind'. +Test.test(); // logs 'static'. + +@autobind +class Component { + public constructor(private someMember: string) { + this.someMember = someMember; + } + + public someMethod(): void { + console.error(this.someMember); + } +} + +const component: Component = new Component('React vs Angular2'); +const { someMethod } = component; +component.someMethod(); // errors 'React vs Angular2' +someMethod(); // errors 'React vs Angular2' diff --git a/autobind-decorator/autobind-decorator.d.ts b/autobind-decorator/autobind-decorator.d.ts new file mode 100644 index 0000000000..51ba89c9bf --- /dev/null +++ b/autobind-decorator/autobind-decorator.d.ts @@ -0,0 +1,10 @@ +// Type definitions for autobind-decorator v1.3.3 +// Project: https://github.com/andreypopp/autobind-decorator +// Definitions by: Ivo Stratev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'autobind-decorator' { + function autobind(target: TFunction): TFunction | void; + function autobind(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor | void; + export = autobind; +} diff --git a/autobind-decorator/autobind-decorator.ts.tscparams b/autobind-decorator/autobind-decorator.ts.tscparams new file mode 100644 index 0000000000..1ee3d05cb6 --- /dev/null +++ b/autobind-decorator/autobind-decorator.ts.tscparams @@ -0,0 +1 @@ +--experimentalDecorators diff --git a/aws-lambda/aws-lambda-tests.ts b/aws-lambda/aws-lambda-tests.ts index 8b9f53a8ab..f562b59d3d 100644 --- a/aws-lambda/aws-lambda-tests.ts +++ b/aws-lambda/aws-lambda-tests.ts @@ -4,55 +4,29 @@ import lambda = require('aws-lambda'); var str: string; var date: Date; -var sns: lambda.SNS; -var kinesis: lambda.Kinesis; -var recordsList: lambda.Record[]; var anyObj: any; var num: number; -var identity: lambda.Identity; +var identity: lambda.CognitoIdentity; var error: Error; - -/* Records */ -var records: lambda.Records; - -recordsList = records.Records; - -/* Record */ -var record: lambda.Record; - -str = record.EventVersion; -str = record.EventSubscriptionArn; -str = record.EnventSource; -sns = record.Sns; -kinesis = record.kinesis; - -/* SNS */ -str = sns.Type; -str = sns.MessageId; -str = sns.TopicArn; -str = sns.Subject; -str = sns.Message; -date = sns.Timestamp; - -/* Kinesis */ -var kinesis: lambda.Kinesis; - -str = kinesis.data; +var b: boolean; +var clientCtx: lambda.ClientContext; /* Context */ var context: lambda.Context; -context.log(str, anyObj); -context.fail(str); -context.succeed(str); -context.succeed(anyObj); -context.succeed(str, anyObj); +b = context.callbackWaitsForEmptyEventLoop; +str = context.functionName; +str = context.functionVersion; +str = context.invokedFunctionArn; +num = context.memoryLimitInMB; str = context.awsRequestId; -num = context.getRemainingTimeInMillis(); +str = context.logGroupName; +str = context.logStreamName; identity = context.identity; +clientCtx = context.clientContext; -/* Identity */ -var identity: lambda.Identity; +/* CognitoIdentity */ +var identity: lambda.CognitoIdentity; str = identity.cognitoIdentityId; str = identity.cognitoIdentityPoolId; diff --git a/aws-lambda/aws-lambda.d.ts b/aws-lambda/aws-lambda.d.ts index 081c6e0e3e..c9a66a3783 100644 --- a/aws-lambda/aws-lambda.d.ts +++ b/aws-lambda/aws-lambda.d.ts @@ -1,55 +1,68 @@ // Type definitions for AWS Lambda // Project: http://docs.aws.amazon.com/lambda -// Definitions by: Michael Skarum +// Definitions by: James Darbyshire , Michael Skarum , Stef Heyenrath // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "aws-lambda" { + // Context + // http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html + interface Context { + // Properties + callbackWaitsForEmptyEventLoop: boolean; + functionName: string; + functionVersion: string; + invokedFunctionArn: string; + memoryLimitInMB: number; + awsRequestId: string; + logGroupName: string; + logStreamName: string; + identity?: CognitoIdentity; + clientContext?: ClientContext; + + // Functions + getRemainingTimeInMillis(): number; - export interface Records { - Records: Record[]; - } - interface Record { - EventVersion: string; - EventSubscriptionArn: string; - EnventSource: string; - Sns: SNS; - kinesis: Kinesis; - } - interface SNS { - Type: string; - MessageId: string; - TopicArn: string; - Subject: string; - Message: string; - Timestamp: Date; - } - - interface Kinesis { - data: string; - } - - export interface Context { + // Functions for compatibility with earlier Node.js Runtime v0.10.42 log(message: string, object: any): void; fail(message: string): void; succeed(message: string): void; succeed(object: any): void; - succeed(message: string, object: any): void; - awsRequestId: string; - getRemainingTimeInMillis(): number; - /** Information about the Amazon Cognito identity provider when invoked through the AWS Mobile SDK. It can be null. */ - identity?: Identity; + succeed(message: string, object: any): void; } - - interface Identity { + + interface CognitoIdentity { cognitoIdentityId: string; cognitoIdentityPoolId: string; } - + + interface ClientContext { + client: ClientContextClient; + Custom?: any; + env: ClientContextEnv; + } + + interface ClientContextClient { + installationId: string; + appTitle: string; + appVersionName: string; + appVersionCode: string; + appPackageName: string; + } + + interface ClientContextEnv { + platformVersion: string; + platform: string; + make: string; + model: string; + locale: string; + } + /** * Optional callback parameter. + * http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html * - * @param error – an optional parameter that you can use to provide results of the failed Lambda function execution. - * @param result – an optional parameter that you can use to provide the result of a successful function execution. The result provided must be JSON.stringify compatible. + * @param error – an optional parameter that you can use to provide results of the failed Lambda function execution. + * @param result – an optional parameter that you can use to provide the result of a successful function execution. The result provided must be JSON.stringify compatible. */ export type Callback = (error?: Error, result?: any) => void; } \ No newline at end of file diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index cb35f34e97..09ec2f6267 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -226,7 +226,7 @@ declare module "aws-sdk" { constructor(options?: any); endpoint: Endpoint; - getObject(params: s3.GetObjectRequest, callback: (err: Error, data: any) => void): void; + getObject(params: s3.GetObjectRequest, callback?: (err: Error, data: any) => void): any; putObject(params: s3.PutObjectRequest, callback: (err: Error, data: any) => void): void; deleteObject(params: s3.DeleteObjectRequest, callback: (err: Error, data: any) => void): void; headObject(params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void; @@ -235,6 +235,12 @@ declare module "aws-sdk" { upload(params?: s3.PutObjectRequest, options?: s3.UploadOptions, callback?: (err: Error, data: any) => void): void; listObjects(params: s3.ListObjectRequest, callback: (err: Error, data: s3.ListObjectResponse) => void): void; listObjectsV2(params: s3.ListObjectV2Request, callback: (err: Error, data: s3.ListObjectV2Response) => void): void; + waitFor(state: string, params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void; + + createMultipartUpload(params: any, callback: (err: Error, data: any) => void): void; + uploadPart(params: any, callback: (err: Error, data: any) => void): void; + listParts(params: any, callback: (err: Error, data: any) => void): void; + completeMultipartUpload(params: any, callback: (err: Error, data: any) => void): void; } export class STS { diff --git a/axe-core/axe-core-tests.ts b/axe-core/axe-core-tests.ts new file mode 100644 index 0000000000..7decb865c2 --- /dev/null +++ b/axe-core/axe-core-tests.ts @@ -0,0 +1,91 @@ +/// + +var context:any = document +var $fixture:any = {} + +// axe.a11yCheck config +axe.a11yCheck(context, {}, (results) => { + // axe's results object + console.log(results.passes.length) + console.log(results.violations.length) +}); +// axe.a11yCheck include/exclude +axe.a11yCheck({include: [['#id1'], ['#id2']]}, {}, (results) => { + console.log(results) +}) +axe.a11yCheck({exclude: [$fixture[0]]}, {}, (results) => { + console.log(results) +}) +var tagConfigRunOnly: axe.RunOnly = { + type: 'tag', + values: ['wcag2a'] +} +var tagConfig = { + runOnly: tagConfigRunOnly +} +axe.a11yCheck(context, tagConfig, (results) => { + console.log(results) +}) +var includeExcludeTagsRunOnly: axe.RunOnly = { + type: 'tags', + value: { + include: ['wcag2a', 'wcag2aa'], + exclude: ['experimental'] + } +} +var includeExcludeTagsConfig = { + runOnly: includeExcludeTagsRunOnly +} +axe.a11yCheck(context, includeExcludeTagsConfig, (results) => { + console.log(results) +}) +var someRulesConfig = { + rules: { + "color-contrast": {enabled: 'false'}, + "heading-order": {enabled: 'true'} + } +} +axe.a11yCheck(context, someRulesConfig, (results) => { + console.log(results) +}) + +// axe.configure +var spec: axe.Spec = { + branding: { + brand: 'foo', + application: 'bar' + }, + reporter: 'v1', + checks: [{ + id: 'custom-check', + evaluate: function() { + return true + } + }], + rules: [{ + id: 'custom-rule', + any: ['custom-check'] + }] +} +axe.configure(spec) + +axe.reset() + +axe.getRules(['wcag2aa']) +typeof axe.getRules() === 'object' + +// Plugins +var pluginSrc: axe.AxePlugin = { + id: 'doStuff', + run: (data:any, callback:Function) => { + callback() + }, + commands: [{ + id: 'run-doStuff', + callback: (data:any, callback:Function) => { + axe.plugins['doStuff'].run(data, callback) + } + }] +} +axe.registerPlugin(pluginSrc) +axe.cleanup() diff --git a/axe-core/axe-core.d.ts b/axe-core/axe-core.d.ts new file mode 100644 index 0000000000..98818e75cc --- /dev/null +++ b/axe-core/axe-core.d.ts @@ -0,0 +1,159 @@ +// Type definitions for axe-core 2.0.5 +// Project: https://github.com/dequelabs/axe-core +// Definitions by: Marcy Sutton +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace axe { + + export type ImpactValue = "minor" | "moderate" | "serious" | "critical"; + + export type TagValue = "wcag2a" | "wcag2aa" | "section508" | "best-practice"; + + export type ReporterVersion = "v1" | "v2"; + + export type RunOnlyType = "rule" | "rules" | "tag" | "tags"; + + export interface ElementContext { + node?: Object, + selector?: string, + include?: any[], + exclude?: any[] + } + export interface RunOnly { + type: RunOnlyType, + value?: { + include?: string[], + exclude?: string[] + } + values?: TagValue[] + } + export interface AxeResults { + url: string, + timestamp: string, + passes: Pass[], + violations: Violation[] + } + export interface Pass { + description: string, + help: string, + helpUrl: string, + id: string, + impact: ImpactValue, + tags: TagValue[], + nodes: NodeResult[] + } + export interface Violation { + description: string, + help: string, + helpUrl: string, + id: string, + impact: ImpactValue, + tags: TagValue[], + nodes: NodeResult[] + } + export interface NodeResult { + html: string, + impact: ImpactValue, + target: string[], + any: CheckResult[], + all: CheckResult[], + none: CheckResult[] + } + export interface CheckResult { + id: string, + impact: string, + message: string, + data: any, + relatedNodes?: RelatedNode[] + } + export interface RelatedNode { + target: string[], + html: string + } + export interface Spec { + branding?: { + brand: string, + application: string + }, + reporter?: ReporterVersion, + checks?: Check[], + rules?: Rule[] + } + export interface Check { + id: string, + evaluate: Function, + after?: Function, + options?: any, + matches?: string, + enabled?: boolean + } + export interface Rule { + id: string, + selector?: string, + excludeHidden?: boolean, + enabled?: boolean, + pageLevel?: boolean, + any?: string[], + all?: string[], + none?: string[], + tags?: string[], + matches?: string + } + export interface AxePlugin { + id: string, + run(...args:any[]): any, + commands: { + id: string, + callback(...args:any[]): void + }[], + cleanup?(callback:Function): void + } + + export let plugins: any + + /** + * Starts analysis on the current document and its subframes + * + * @param {Object} context The `Context` specification object @see Context + * @param {Array} options Options passed into rules or checks, temporarily modifyint them. + * @param {Function} callback The function to invoke when analysis is complete. + * @returns {Object} results The aXe results object + */ + export function a11yCheck(context: ElementContext, options: {runOnly?: RunOnly, rules?: Object}, callback: (results:AxeResults) => void): AxeResults + + /** + * Method for configuring the data format used by aXe. Helpful for adding new + * rules, which must be registered with the library to execute. + * @param {Spec} Spec Object with valid `branding`, `reporter`, `checks` and `rules` data + */ + export function configure(spec: Spec): void + + /** + * Searches and returns rules that contain a tag in the list of tags. + * @param {Array} tags Optional array of tags + * @return {Array} Array of rules + */ + export function getRules(tags?: string[]): Object[] + + /** + * Restores the default axe configuration + */ + export function reset(): void + + /** + * Function to register a plugin configuration in document and its subframes + * @param {Object} plugin A plugin configuration object + */ + export function registerPlugin(plugin: AxePlugin): void + + /** + * Function to clean up plugin configuration in document and its subframes + */ + export function cleanup(): void + +} + +// axe is also available as a module +declare module "axe-core" { + export = axe; +} diff --git a/azure-mobile-apps/azure-mobile-apps-tests.ts b/azure-mobile-apps/azure-mobile-apps-tests.ts index 093932c2fb..302f732889 100644 --- a/azure-mobile-apps/azure-mobile-apps-tests.ts +++ b/azure-mobile-apps/azure-mobile-apps-tests.ts @@ -72,6 +72,13 @@ table.read.use([function () {}, function () {}]); table.read.use(function () {}, function () {}); table.use(function () {}).use(function () {}).read(function () {}).use(function () {}) +table.access = undefined; +table.access = 'authenticated'; +table.read.access = 'anonymous'; +table.update.access = 'disabled'; +table.delete.access = 'authenticated'; +table.insert.access = 'authenticated'; + // Express.Table, instantiated from the static require('azure-mobile-apps').table() // This is going to be interesting if we ever support more than one provider var table2 = mobileApps.table(); @@ -84,4 +91,14 @@ mobileApps.logger.debug('a debug message') // Query queries.create('table').where({ x: 10 }).select('col1,col2'); -mobileApps.query.create('table'); \ No newline at end of file +mobileApps.query.create('table'); + +// custom sql query +mobileApp.api.add('query', { authorize: true, get: (req, res, next) => { + req.azureMobile.data.execute({ + sql: "SELECT * FROM TODOITEM WHERE COMPLETE = :complete", + parameters: [ + { name: 'complete', value: 1 } + ] + }).then(x => {}); +}, delete: function () {} }); diff --git a/azure-mobile-apps/azure-mobile-apps.d.ts b/azure-mobile-apps/azure-mobile-apps.d.ts index 0a42fa9ecf..a17e41e2d6 100644 --- a/azure-mobile-apps/azure-mobile-apps.d.ts +++ b/azure-mobile-apps/azure-mobile-apps.d.ts @@ -47,6 +47,7 @@ declare namespace Azure.MobileApps { interface Table { authorize?: boolean; + access?: AccessType; autoIncrement?: boolean; dynamicSchema?: boolean; name: string; @@ -66,8 +67,11 @@ declare namespace Azure.MobileApps { (operationHandler: (context: Context) => void): Table; use(...middleware: Middleware[]): Table; use(middleware: Middleware[]): Table; + access: AccessType; } + type AccessType = 'anonymous' | 'authenticated' | 'disabled'; + interface Tables { configuration: Configuration; add(name: string, definition?: Table | TableDefinition): void; @@ -215,7 +219,7 @@ declare namespace Azure.MobileApps { item: any; req: Express.Request; res: Express.Response; - data: (table: TableDefinition) => Data.Table; + data: ContextData; tables: (tableName: string) => Data.Table; user: User; push: typeof nh; @@ -223,6 +227,21 @@ declare namespace Azure.MobileApps { execute(): Thenable; } + interface ContextData { + (table: TableDefinition): Data.Table; + execute(q: SqlQueryDefinition): Thenable; + } + + interface SqlQueryDefinition { + sql: string; + parameters?: SqlParameterDefinition[]; + } + + interface SqlParameterDefinition { + name: string; + value: any; + } + interface TableDefinition { authorize?: boolean; autoIncrement?: boolean; diff --git a/azure-mobile-services-client/AzureMobileServicesClient.d.ts b/azure-mobile-services-client/AzureMobileServicesClient.d.ts index afd6014598..6fa0f9c475 100644 --- a/azure-mobile-services-client/AzureMobileServicesClient.d.ts +++ b/azure-mobile-services-client/AzureMobileServicesClient.d.ts @@ -17,7 +17,7 @@ declare namespace Microsoft.WindowsAzure { login(provider: string, token: string): asyncPromise; login(provider: string, callback: (error: any, user: User) => void ): void; login(provider: string): asyncPromise; - logout(): void; + logout(): asyncPromise; getTable(tableName: string): MobileServiceTable; withFilter(serviceFilter: (request: any, next: (request: any, callback: (error: any, response: any) => void) => void, callback: (error: any, response: any) => void) => void): MobileServiceClient; /** diff --git a/backlog-js/backlog-js-tests.ts b/backlog-js/backlog-js-tests.ts new file mode 100644 index 0000000000..979eb57ca4 --- /dev/null +++ b/backlog-js/backlog-js-tests.ts @@ -0,0 +1,88 @@ +/// + +import * as backlogjs from 'backlog-js'; + +const host = 'example.backlog.jp'; +const apiKey = 'apiKey'; +const clientId = 'clientId'; +const clientSecret = 'clientSecret'; +const redirectUri = 'redirectUri'; +const state = 'state'; +const code = 'code'; +const refreshToken = 'refreshToken'; +const configure = { host, apiKey } +const credentials = { clientId, clientSecret } + +const oauth2 = new backlogjs.OAuth2(credentials); +oauth2.getAuthorizationURL({ host, redirectUri, state }); +oauth2.getAccessToken({ host, code, redirectUri }).then(data => {}).catch(err => {}); +oauth2.refreshAccessToken({ host, refreshToken }).then(data => {}).catch(err => {}); + +const backlog = new backlogjs.Backlog(configure); +backlog.getSpace().then(data => { }).catch(err => { }); +backlog.getSpaceActivities({ + activityTypeId: [ + backlogjs.Option.ActivityType.IssueCreated, + backlogjs.Option.ActivityType.IssueUpdated + ], + minId: 1, + maxId: 2, + count: 3, + order: "asc" +}).then(data => { }).catch(err => { }); +backlog.getSpaceDiskUsage().then(data => { }).catch(err => { }); +backlog.getSpaceIcon().then(data => { }).catch(err => { }); +backlog.postSpaceAttachment(new FormData()).then(data => { }).catch(err => { }); +backlog.getUsers().then(data => { }).catch(err => { }); +backlog.getUser(1).then(data => { }).catch(err => { }); +backlog.postUser({ + userId: 'string', + password: 'string', + name: 'string', + mailAddress: 'string', + roleType: backlogjs.Option.User.RoleType.Admin +}).then(data => { }).catch(err => { }); +backlog.patchUser(1, { + password: 'string', + name: 'string', + mailAddress: 'string', + roleType: backlogjs.Option.User.RoleType.Admin +}).then(data => { }).catch(err => { }); +backlog.deleteUser(1).then(data => { }).catch(err => { }); +backlog.getMyself().then(data => { }).catch(err => { }); +backlog.getUserActivities(1, { + activityTypeId: [ + backlogjs.Option.ActivityType.IssueCreated, + backlogjs.Option.ActivityType.IssueUpdated + ], + minId: 1, + maxId: 2, + count: 3, + order: "asc" +}).then(data => { }).catch(err => { }); +backlog.getUserStars(1, { + minId: 1, + maxId: 2, + count: 3, + order: "asc" +}).then(data => { }).catch(err => { }); +backlog.getUserStarsCount(1, { + since: 'YYYY-MM-DD', + until: 'YYYY-MM-DD' +}).then(data => { }).catch(err => { }); +backlog.getRecentlyViewedIssues({ + order: 'asc', + offset: 1, + count: 2 +}).then(data => { }).catch(err => { }); +backlog.getRecentlyViewedProjects({ + order: 'asc', + offset: 1, + count: 2 +}).then(data => { }).catch(err => { }); +backlog.getRecentlyViewedWikis({ + order: 'asc', + offset: 1, + count: 2 +}).then(data => { }).catch(err => { }); +backlog.getUserIcon(1).then(data => {}).catch(err => {}); diff --git a/backlog-js/backlog-js.d.ts b/backlog-js/backlog-js.d.ts new file mode 100644 index 0000000000..353e7e90cd --- /dev/null +++ b/backlog-js/backlog-js.d.ts @@ -0,0 +1,695 @@ +// Type definitions for backlog-js 0.9.0 +// Project: https://github.com/nulab/backlog-js +// Definitions by: Yuichi Watanabe +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// +/// + +declare module 'backlog-js' { + + class Request { + private configure; + constructor(configure: { + host: string; + apiKey?: string; + accessToken?: string; + timeout?: number; + }); + get(path: string, params?: any): Promise; + post(path: string, params?: any): Promise; + put(path: string, params: any): Promise; + patch(path: string, params: any): Promise; + delete(path: string, params?: any): Promise; + request(options: { + method: string; + path: string; + params?: Params | FormData; + }): Promise; + checkStatus(response: IResponse): Promise; + parseJSON(response: IResponse): Promise; + private toFormData(params); + private toQueryString(params); + webAppBaseURL: string; + restBaseURL: string; + } + + type Params = { + [index: string]: number | string | number[] | string[]; + }; + + export class Backlog extends Request { + constructor(configure: { + host: string; + apiKey?: string; + accessToken?: string; + timeout?: number; + }); + getSpace(): Promise; + getSpaceActivities(params: Option.Space.GetActivitiesParams): Promise; + getSpaceNotification(): Promise; + putSpaceNotification(params: Option.Space.PutSpaceNotificationParams): Promise; + getSpaceDiskUsage(): Promise; + getSpaceIcon(): Promise; + postSpaceAttachment(form: FormData): Promise; + getUsers(): Promise; + getUser(userId: number): Promise; + postUser(params: Option.User.PostUserParams): Promise; + patchUser(userId: number, params: Option.User.PatchUserParams): Promise; + deleteUser(userId: number): Promise; + getMyself(): Promise; + getUserActivities(userId: number, params: Option.User.GetUserActivitiesParams): Promise; + getUserStars(userId: number, params: Option.User.GetUserStarsParams): Promise; + getUserStarsCount(userId: number, params: Option.User.GetUserStarsCountParams): Promise; + getRecentlyViewedIssues(params: Option.User.GetRecentlyViewedParams): Promise; + getRecentlyViewedProjects(params: Option.User.GetRecentlyViewedParams): Promise; + getRecentlyViewedWikis(params: Option.User.GetRecentlyViewedParams): Promise; + getUserIcon(userId: number): Promise; + getGroups(params: Option.Group.GetGroupsParams): Promise; + postGroups(params: Option.Group.PostGroupsParams): Promise; + getGroup(groupId: number): Promise; + patchGroup(groupId: number, params: Option.Group.PatchGroupParams): Promise; + deleteGroup(groupId: number): Promise; + getStatuses(): Promise; + getResolutions(): Promise; + getPriorities(): Promise; + postProject(params: Option.Project.PostProjectParams): Promise; + getProjects(params?: Option.Project.GetProjectsParams): Promise; + getProject(projectIdOrKey: string): Promise; + patchProject(projectIdOrKey: string, params: Option.Project.PatchProjectParams): Promise; + deleteProject(projectIdOrKey: string): Promise; + getProjectActivities(projectIdOrKey: string, params: Option.Space.GetActivitiesParams): Promise; + getProjectUsers(projectIdOrKey: string): Promise; + deleteProjectUsers(projectIdOrKey: string, params: Option.Project.DeleteProjectUsersParams): Promise; + postProjectAdministrators(projectIdOrKey: string, params: Option.Project.PostProjectAdministrators): Promise; + getProjectAdministrators(projectIdOrKey: string): Promise; + deleteProjectAdministrators(projectIdOrKey: string, params: Option.Project.DeleteProjectAdministrators): Promise; + getIssueTypes(projectIdOrKey: string): Promise; + postIssueType(projectIdOrKey: string, params: Option.Project.PostIssueTypeParams): Promise; + patchIssueType(projectIdOrKey: string, id: number, params: Option.Project.PatchIssueTypeParams): Promise; + deleteIssueType(projectIdOrKey: string, id: number, params: Option.Project.DeleteIssueTypeParams): Promise; + getCategories(projectIdOrKey: string): Promise; + postCategories(projectIdOrKey: string, params: Option.Project.PostCategoriesParams): Promise; + patchCategories(projectIdOrKey: string, id: number, params: Option.Project.PatchCategoriesParams): Promise; + deleteCategories(projectIdOrKey: string, id: number): Promise; + getVersions(projectIdOrKey: string): Promise; + postVersions(projectIdOrKey: string, params: Option.Project.PostVersionsParams): Promise; + patchVersions(projectIdOrKey: string, id: number, params: Option.Project.PatchVersionsParams): Promise; + deleteVersions(projectIdOrKey: string, id: number): Promise; + getCustomFields(projectIdOrKey: string): Promise; + postCustomField(projectIdOrKey: string, params: Option.Project.PostCustomFieldParams | Option.Project.PostCustomFieldWithNumericParams | Option.Project.PostCustomFieldWithDateParams | Option.Project.PostCustomFieldWithListParams): Promise; + patchCustomField(projectIdOrKey: string, id: number, params: Option.Project.PatchCustomFieldParams | Option.Project.PatchCustomFieldWithNumericParams | Option.Project.PatchCustomFieldWithDateParams | Option.Project.PatchCustomFieldWithListParams): Promise; + deleteCustomField(projectIdOrKey: string, id: number): Promise; + postCustomFieldItem(projectIdOrKey: string, id: number, params: Option.Project.PostCustomFieldItemParams): Promise; + patchCustomFieldItem(projectIdOrKey: string, id: number, itemId: number, params: Option.Project.PatchCustomFieldItemParams): Promise; + deleteCustomFieldItem(projectIdOrKey: string, id: number, params: Option.Project.PostCustomFieldItemParams): Promise; + getSharedFiles(projectIdOrKey: string, path: string, params: Option.Project.GetSharedFilesParams): Promise; + getProjectsDiskUsage(projectIdOrKey: string): Promise; + getWebhooks(projectIdOrKey: string): Promise; + postWebhook(projectIdOrKey: string, params: Option.Project.PostWebhookParams): Promise; + getWebhook(projectIdOrKey: string, webhookId: string): Promise; + patchWebhook(projectIdOrKey: string, webhookId: string, params: Option.Project.PatchWebhookParams): Promise; + deleteWebhook(projectIdOrKey: string, webhookId: string): Promise; + postIssue(params: Option.Issue.PostIssueParams): Promise; + patchIssue(issueIdOrKey: string, params: Option.Issue.PatchIssueParams): Promise; + getIssues(params?: Option.Issue.GetIssuesParams): Promise; + getIssue(issueIdOrKey: string): Promise; + getIssuesCount(params?: Option.Issue.GetIssuesParams): Promise; + deleteIssuesCount(issueIdOrKey: string): Promise; + getIssueComments(issueIdOrKey: string, params: Option.Issue.GetIssueCommentsParams): Promise; + postIssueComments(issueIdOrKey: string, params: Option.Issue.PostIssueCommentsParams): Promise; + getIssueCommentsCount(issueIdOrKey: string): Promise; + getIssueComment(issueIdOrKey: string, commentId: number): Promise; + patchIssueComment(issueIdOrKey: string, commentId: number, params: Option.Issue.PatchIssueCommentParams): Promise; + getIssueCommentNotifications(issueIdOrKey: string, commentId: number): Promise; + postIssueCommentNotifications(issueIdOrKey: string, commentId: number, prams: Option.Issue.IssueCommentNotifications): Promise; + getIssueAttachments(issueIdOrKey: string): Promise; + deleteIssueAttachment(issueIdOrKey: string, attachmentId: string): Promise; + getIssueSharedFiles(issueIdOrKey: string): Promise; + linkIssueSharedFiles(issueIdOrKey: string, params: Option.Issue.LinkIssueSharedFilesParams): Promise; + unlinkIssueSharedFile(issueIdOrKey: string, id: number): Promise; + getWikis(projectIdOrKey: number): Promise; + getWikisCount(projectIdOrKey: number): Promise; + getWikisTags(projectIdOrKey: number): Promise; + postWiki(params: Option.Wiki.PostWikiParams): Promise; + getWiki(wikiId: number): Promise; + patchWiki(wikiId: number, params: Option.Wiki.PatchWikiParams): Promise; + deleteWiki(wikiId: number, mailNotify: boolean): Promise; + getWikisAttachments(wikiId: number): Promise; + postWikisAttachments(wikiId: number, attachmentId: number[]): Promise; + deleteWikisAttachments(wikiId: number, attachmentId: number): Promise; + getWikisSharedFiles(wikiId: number): Promise; + linkWikisSharedFiles(wikiId: number, fileId: number[]): Promise; + unlinkWikisSharedFiles(wikiId: number, id: number): Promise; + getWikisHistory(wikiId: number, params: Option.Wiki.GetWikisHistoryParams): Promise; + getWikisStars(wikiId: number): Promise; + postStar(params: Option.Project.PostStarParams): Promise; + getNotifications(params: Option.Notification.GetNotificationsParams): Promise; + getNotificationsCount(params: Option.Notification.GetNotificationsCountParams): Promise; + resetNotificationsMarkAsRead(): Promise; + markAsReadNotification(id: number): Promise; + getGitRepositories(projectIdOrKey: string): Promise; + getGitRepository(projectIdOrKey: string, repoIdOrName: string): Promise; + getPullRequests(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.GetPullRequestsParams): Promise; + getPullRequestsCount(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.GetPullRequestsParams): Promise; + postPullRequest(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.PostPullRequestParams): Promise; + getPullRequest(projectIdOrKey: string, repoIdOrName: string, number: number): Promise; + patchPullRequest(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.PatchPullRequestParams): Promise; + getPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.GetPullRequestCommentsParams): Promise; + postPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.PostPullRequestCommentsParams): Promise; + getPullRequestCommentsCount(projectIdOrKey: string, repoIdOrName: string, number: number): Promise; + patchPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, commentId: number, params: Option.PullRequest.PatchPullRequestCommentsParams): Promise; + getPullRequestAttachments(projectIdOrKey: string, repoIdOrName: string, number: number): Promise; + deletePullRequestAttachment(projectIdOrKey: string, repoIdOrName: string, number: number, attachmentId: number): Promise; + getProjectIcon(projectIdOrKey: string): Promise; + getSharedFile(projectIdOrKey: string, sharedFileId: number): Promise; + getIssueAttachment(issueIdOrKey: string, attachmentId: number): Promise; + getWikiAttachment(wikiId: number, attachmentId: number): Promise; + getPullRequestAttachment(projectIdOrKey: string, repoIdOrName: string, number: number, attachmentId: number): Promise; + private download(path); + private upload(path, params); + private parseFileData(response); + } + + export class OAuth2 { + private credentials; + private timeout; + constructor(credentials: Option.OAuth2.Credentials, timeout?: number); + getAuthorizationURL(options: { + host: string; + redirectUri?: string; + state?: string; + }): string; + getAccessToken(options: { + host: string; + code: string; + redirectUri?: string; + }): Promise; + refreshAccessToken(options: { + host: string; + refreshToken: string; + }): Promise; + } + + import { PassThrough } from 'stream'; + export namespace Entity { + export namespace File { + export type FileData = NodeFileData | BrowserFileData; + export interface NodeFileData { + body: PassThrough; + url: string; + filename: string; + } + export interface BrowserFileData { + body: any; + url: string; + blob?: () => Promise; + } + } + export namespace OAuth2 { + export interface AccessToken { + access_token: string; + token_type: string; + expires_in: number; + refresh_token: string; + } + } + } + + + export namespace Option { + export type Order = "asc" | "desc"; + export enum ActivityType { + Undefined = -1, + IssueCreated = 1, + IssueUpdated = 2, + IssueCommented = 3, + IssueDeleted = 4, + WikiCreated = 5, + WikiUpdated = 6, + WikiDeleted = 7, + FileAdded = 8, + FileUpdated = 9, + FileDeleted = 10, + SvnCommitted = 11, + GitPushed = 12, + GitRepositoryCreated = 13, + IssueMultiUpdated = 14, + ProjectUserAdded = 15, + ProjectUserRemoved = 16, + NotifyAdded = 17, + PullRequestAdded = 18, + PullRequestUpdated = 19, + PullRequestCommented = 20, + PullRequestMerged = 21, + } + export namespace Notification { + export interface GetNotificationsParams { + minId?: number; + maxId?: number; + count?: number; + order?: Order; + } + export interface GetNotificationsCountParams { + alreadyRead: boolean; + resourceAlreadyRead: boolean; + } + } + export namespace Space { + export interface GetActivitiesParams { + activityTypeId?: ActivityType[]; + minId?: number; + maxId?: number; + count?: number; + order?: Order; + } + export interface PutSpaceNotificationParams { + content: string; + } + } + export namespace User { + export interface PostUserParams { + userId: string; + password: string; + name: string; + mailAddress: string; + roleType: RoleType; + } + export interface PatchUserParams { + password?: string; + name?: string; + mailAddress?: string; + roleType?: RoleType; + } + export enum RoleType { + Admin = 1, + User = 2, + Reporter = 3, + Viewer = 4, + GuestReporter = 5, + GuestViewer = 6, + } + export interface GetUserActivitiesParams { + activityTypeId?: ActivityType[]; + minId?: number; + maxId?: number; + count?: number; + order?: Order; + } + export interface GetUserStarsParams { + minId?: number; + maxId?: number; + count?: number; + order?: Order; + } + export interface GetUserStarsCountParams { + since?: string; + until?: string; + } + export interface GetRecentlyViewedParams { + order?: Order; + offset?: number; + count?: number; + } + } + export namespace Group { + export interface GetGroupsParams { + order?: Order; + offset?: number; + count?: number; + } + export interface PostGroupsParams { + name: string; + members?: string[]; + } + export interface PatchGroupParams { + name?: string; + members?: string[]; + } + } + export namespace Project { + export type TextFormattingRule = "backlog" | "markdown"; + export interface PostProjectParams { + name: string; + key: string; + chartEnabled: boolean; + projectLeaderCanEditProjectLeader?: boolean; + subtaskingEnabled: boolean; + textFormattingRule: TextFormattingRule; + } + export interface PatchProjectParams { + name?: string; + key?: string; + chartEnabled?: boolean; + subtaskingEnabled?: boolean; + projectLeaderCanEditProjectLeader?: boolean; + textFormattingRule?: TextFormattingRule; + archived?: boolean; + } + export interface GetProjectsParams { + archived?: boolean; + all?: boolean; + } + export interface DeleteProjectUsersParams { + userId: number; + } + export interface PostProjectAdministrators { + userId: number; + } + export interface DeleteProjectAdministrators { + userId: number; + } + export type IssueTypeColor = "#e30000" | "#990000" | "#934981" | "#814fbc" | "#2779ca" | "#007e9a" | "#7ea800" | "#ff9200" | "#ff3265" | "#666665"; + export interface PostIssueTypeParams { + name: string; + color: IssueTypeColor; + } + export interface PatchIssueTypeParams { + name?: string; + color?: IssueTypeColor; + } + export interface DeleteIssueTypeParams { + substituteIssueTypeId: number; + } + export interface PostCategoriesParams { + name: string; + } + export interface PatchCategoriesParams { + name: string; + } + export interface PostVersionsParams { + name: string; + description: string; + startDate: string; + releaseDueDate: string; + } + export interface PatchVersionsParams { + name: string; + description?: string; + startDate?: string; + releaseDueDate?: string; + archived?: boolean; + } + export interface PostCustomFieldParams { + typeId: FieldType; + name: string; + applicableIssueTypes?: number[]; + description?: string; + required?: boolean; + } + export interface PostCustomFieldWithNumericParams extends PostCustomFieldParams { + min?: number; + max?: number; + initialValue?: number; + unit?: string; + } + export interface PostCustomFieldWithDateParams extends PostCustomFieldParams { + min?: string; + max?: string; + initialValueType?: number; + initialDate?: string; + initialShift?: number; + } + export interface PostCustomFieldWithListParams extends PostCustomFieldParams { + items?: string[]; + allowInput?: boolean; + allowAddItem?: boolean; + } + export interface PatchCustomFieldParams { + name?: string; + applicableIssueTypes?: number[]; + description?: string; + required?: boolean; + } + export interface PatchCustomFieldWithNumericParams extends PatchCustomFieldParams { + min?: number; + max?: number; + initialValue?: number; + unit?: string; + } + export interface PatchCustomFieldWithDateParams extends PatchCustomFieldParams { + min?: string; + max?: string; + initialValueType?: number; + initialDate?: string; + initialShift?: number; + } + export interface PatchCustomFieldWithListParams extends PatchCustomFieldParams { + items?: string[]; + allowInput?: boolean; + allowAddItem?: boolean; + } + export interface PostCustomFieldItemParams { + name: string; + } + export interface PatchCustomFieldItemParams { + name: string; + } + export interface GetSharedFilesParams { + order?: Order; + offset?: number; + count?: number; + } + export interface PostWebhookParams { + name?: string; + description?: string; + hookUrl?: string; + allEvent?: boolean; + activityTypeIds?: number[]; + } + export interface PatchWebhookParams { + name?: string; + description?: string; + hookUrl?: string; + allEvent?: boolean; + activityTypeIds?: number[]; + } + export enum FieldType { + Text = 1, + TextArea = 2, + Numeric = 3, + Date = 4, + SingleList = 5, + MultipleList = 6, + CheckBox = 7, + Radio = 8, + } + export interface PostStarParams { + issueId?: number; + commentId?: number; + wikiId?: number; + pullRequestId?: number; + pullRequestCommentId?: number; + } + } + export namespace Issue { + export interface PostIssueParams { + projectId: number; + summary: string; + priorityId: number; + issueTypeId: number; + parentIssueId?: number; + description?: string; + startDate?: string; + dueDate?: string; + estimatedHours?: number; + actualHours?: number; + categoryId?: number[]; + versionId?: number[]; + milestoneId?: number[]; + assigneeId?: number; + notifiedUserId?: number[]; + attachmentId?: number[]; + [customField_: string]: any; + } + export interface PatchIssueParams { + summary?: string; + parentIssueId?: number; + description?: string; + statusId?: number; + resolutionId?: number; + startDate?: string; + dueDate?: string; + estimatedHours?: number; + actualHours?: number; + issueTypeId?: number; + categoryId?: number[]; + versionId?: number[]; + milestoneId?: number[]; + priorityId?: number; + assigneeId?: number; + notifiedUserId?: number[]; + attachmentId?: number[]; + comment?: string; + [customField_: string]: any; + } + export interface GetIssuesParams { + projectId?: number[]; + issueTypeId?: number[]; + categoryId?: number[]; + versionId?: number[]; + milestoneId?: number[]; + statusId?: number[]; + priorityId?: number[]; + assigneeId?: number[]; + createdUserId?: number[]; + resolutionId?: number[]; + parentChild?: ParentChildType; + attachment?: boolean; + sharedFile?: boolean; + sort?: SortKey; + order?: Order; + offset?: number; + count?: number; + createdSince?: string; + createdUntil?: string; + updatedSince?: string; + updatedUntil?: string; + startDateSince?: string; + startDateUntil?: string; + dueDateSince?: string; + dueDateUntil?: string; + id?: number[]; + parentIssueId?: number[]; + keyword: string; + [customField_: string]: any; + } + export enum ParentChildType { + All = 0, + NotChild = 1, + Child = 2, + NotChildNotParent = 3, + Parent = 4, + } + export type SortKey = "issueType" | "category" | "version" | "milestone" | "summary" | "status" | "priority" | "attachment" | "sharedFile" | "created" | "createdUser" | "updated" | "updatedUser" | "assignee" | "startDate" | "dueDate" | "estimatedHours" | "actualHours" | "childIssue"; + export interface GetIssueCommentsParams { + minId?: number; + maxId?: number; + count?: number; + order?: Order; + } + export interface PostIssueCommentsParams { + content: string; + notifiedUserId?: number[]; + attachmentId?: number[]; + } + export interface PatchIssueCommentParams { + content: string; + } + export interface IssueCommentNotifications { + notifiedUserId: number[]; + } + export interface LinkIssueSharedFilesParams { + fileId: number[]; + } + } + export namespace PullRequest { + export interface GetPullRequestsParams { + statusId?: number[]; + assigneeId?: number[]; + issueId?: number[]; + createdUserId?: number[]; + offset?: number; + count?: number; + } + export interface PostPullRequestParams { + summary: string; + description: string; + base: string; + branch: string; + issueId?: number; + assigneeId?: number; + notifiedUserId?: number[]; + attachmentId?: number[]; + } + export interface PatchPullRequestParams { + summary?: string; + description?: string; + issueId?: number; + assigneeId?: number; + notifiedUserId?: number[]; + comment?: string[]; + } + export interface GetPullRequestCommentsParams { + minId?: number; + maxId?: number; + count?: number; + order?: Order; + } + export interface PostPullRequestCommentsParams { + content: string; + notifiedUserId?: number[]; + } + export interface PatchPullRequestCommentsParams { + content: string; + } + } + export namespace Wiki { + export interface PostWikiParams { + projectId: number; + name: string; + content: string; + mailNotify?: boolean; + } + export interface PatchWikiParams { + name?: string; + content?: string; + mailNotify?: boolean; + } + export interface GetWikisHistoryParams { + minId?: number; + maxId?: number; + count?: number; + order?: Order; + } + } + export namespace OAuth2 { + export interface Credentials { + clientId: string; + clientSecret: string; + } + } + } + + export namespace Error { + export class BacklogError extends global.Error { + private _name; + private _url; + private _status; + private _body; + private _response; + constructor(name: BacklogErrorNameType, response: IResponse, body?: { + errors: BacklogErrorMessage[]; + }); + name: BacklogErrorNameType; + url: string; + status: number; + body: { + errors: BacklogErrorMessage[]; + }; + response: IResponse; + } + export class BacklogApiError extends BacklogError { + constructor(response: IResponse, body?: { + errors: BacklogErrorMessage[]; + }); + } + export class BacklogAuthError extends BacklogError { + constructor(response: IResponse, body?: { + errors: BacklogErrorMessage[]; + }); + } + export class UnexpectedError extends BacklogError { + constructor(response: IResponse); + } + export interface BacklogErrorMessage { + message: string; + code: number; + errorInfo: string; + moreInfo: string; + } + export type BacklogErrorNameType = 'BacklogApiError' | 'BacklogAuthError' | 'UnexpectedError'; + } + +} diff --git a/bluebird/bluebird-tests.ts b/bluebird/bluebird-tests.ts index 59cef89b1a..d7995438c1 100644 --- a/bluebird/bluebird-tests.ts +++ b/bluebird/bluebird-tests.ts @@ -82,6 +82,7 @@ var voidProm: Promise; var fooProm: Promise; var barProm: Promise; +var barOrVoidProm: Promise; var fooOrBarProm: Promise; var bazProm: Promise; @@ -221,12 +222,12 @@ barProm = fooProm.then((value: Foo) => { }, (reason: any) => { return barProm; }); -barProm = fooProm.then((value: Foo) => { +barOrVoidProm = fooProm.then((value: Foo) => { return bar; }, (reason: any) => { return; }); -barProm = fooProm.then((value: Foo) => { +barOrVoidProm = fooProm.then((value: Foo) => { return bar; }, (reason: any) => { return voidProm; diff --git a/bluebird/bluebird.d.ts b/bluebird/bluebird.d.ts index 042347f096..35b506542a 100644 --- a/bluebird/bluebird.d.ts +++ b/bluebird/bluebird.d.ts @@ -47,8 +47,10 @@ class Bluebird implements Bluebird.Thenable, Bluebird.Inspection { /** * Promises/A+ `.then()`. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. */ - then(onFulfill: (value: R) => U | Bluebird.Thenable, onReject?: (error: any) => U | Bluebird.Thenable): Bluebird; - then(onFulfill: (value: R) => U | Bluebird.Thenable, onReject?: (error: any) => void | Bluebird.Thenable): Bluebird; + then(onFulfill: (value: R) => U1 | Bluebird.Thenable, onReject: (error: any) => U2 | Bluebird.Thenable): Bluebird; + then(onFulfill: (value: R) => U | Bluebird.Thenable, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; + then(onFulfill: (value: R) => U | Bluebird.Thenable): Bluebird; + then(): Bluebird; /** * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. diff --git a/braintree-web/braintree-web-tests.ts b/braintree-web/braintree-web-tests.ts new file mode 100644 index 0000000000..40b34df418 --- /dev/null +++ b/braintree-web/braintree-web-tests.ts @@ -0,0 +1,432 @@ +/// + +let version: string = braintree.VERSION; + +let clientToken: string = "eyJ2ZXJzaW9uIjoyLCJhdXRob3JpemF0aW9uRmluZ2VycHJpbnQiOiI0YjlhYzVmYmI4ZTNkYzQzMmFkZjJhNzBlNjZlMWNjY2M5ODRkYzE4ZTM4YmY4NjYzZTM5NjM3NWZjYmQzY2U5fGNyZWF0ZWRfYXQ9MjAxNi0wOS0wOFQwNTowMzo0MC4xNjk1NTUwMzUrMDAwMFx1MDAyNm1lcmNoYW50X2lkPTM0OHBrOWNnZjNiZ3l3MmJcdTAwMjZwdWJsaWNfa2V5PTJuMjQ3ZHY4OWJxOXZtcHIiLCJjb25maWdVcmwiOiJodHRwczovL2FwaS5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tOjQ0My9tZXJjaGFudHMvMzQ4cGs5Y2dmM2JneXcyYi9jbGllbnRfYXBpL3YxL2NvbmZpZ3VyYXRpb24iLCJjaGFsbGVuZ2VzIjpbXSwiZW52aXJvbm1lbnQiOiJzYW5kYm94IiwiY2xpZW50QXBpVXJsIjoiaHR0cHM6Ly9hcGkuc2FuZGJveC5icmFpbnRyZWVnYXRld2F5LmNvbTo0NDMvbWVyY2hhbnRzLzM0OHBrOWNnZjNiZ3l3MmIvY2xpZW50X2FwaSIsImFzc2V0c1VybCI6Imh0dHBzOi8vYXNzZXRzLmJyYWludHJlZWdhdGV3YXkuY29tIiwiYXV0aFVybCI6Imh0dHBzOi8vYXV0aC52ZW5tby5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tIiwiYW5hbHl0aWNzIjp7InVybCI6Imh0dHBzOi8vY2xpZW50LWFuYWx5dGljcy5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tLzM0OHBrOWNnZjNiZ3l3MmIifSwidGhyZWVEU2VjdXJlRW5hYmxlZCI6dHJ1ZSwicGF5cGFsRW5hYmxlZCI6dHJ1ZSwicGF5cGFsIjp7ImRpc3BsYXlOYW1lIjoiQWNtZSBXaWRnZXRzLCBMdGQuIChTYW5kYm94KSIsImNsaWVudElkIjpudWxsLCJwcml2YWN5VXJsIjoiaHR0cDovL2V4YW1wbGUuY29tL3BwIiwidXNlckFncmVlbWVudFVybCI6Imh0dHA6Ly9leGFtcGxlLmNvbS90b3MiLCJiYXNlVXJsIjoiaHR0cHM6Ly9hc3NldHMuYnJhaW50cmVlZ2F0ZXdheS5jb20iLCJhc3NldHNVcmwiOiJodHRwczovL2NoZWNrb3V0LnBheXBhbC5jb20iLCJkaXJlY3RCYXNlVXJsIjpudWxsLCJhbGxvd0h0dHAiOnRydWUsImVudmlyb25tZW50Tm9OZXR3b3JrIjp0cnVlLCJlbnZpcm9ubWVudCI6Im9mZmxpbmUiLCJ1bnZldHRlZE1lcmNoYW50IjpmYWxzZSwiYnJhaW50cmVlQ2xpZW50SWQiOiJtYXN0ZXJjbGllbnQzIiwiYmlsbGluZ0FncmVlbWVudHNFbmFibGVkIjp0cnVlLCJtZXJjaGFudEFjY291bnRJZCI6ImFjbWV3aWRnZXRzbHRkc2FuZGJveCIsImN1cnJlbmN5SXNvQ29kZSI6IlVTRCJ9LCJjb2luYmFzZUVuYWJsZWQiOmZhbHNlLCJtZXJjaGFudElkIjoiMzQ4cGs5Y2dmM2JneXcyYiIsInZlbm1vIjoib2ZmIn0="; + +braintree.client.create({ + authorization: clientToken +}, function (error: BraintreeError, clientInstance: any) { + + var form: HTMLFormElement = document.getElementById('my-form-id') as HTMLFormElement; + var data: { creditCard: BraintreeWeb.CreditCardInfo } = { + creditCard: { + number: form['cc-number'].value, + cvv: form['cc-cvv'].value, + expirationDate: form['cc-date'].value, + billingAddress: { + postalCode: form['cc-postal'].value + } + } + }; + + clientInstance.request({ + endpoint: 'payment_methods/credit_cards', + method: 'post', + data: data + }, function (requestErr: BraintreeError, response: { creditCards: any[]; }) { + if (requestErr) { throw new Error(requestErr.message); } + + console.log('Got nonce:', response.creditCards[0].nonce); + }); + + braintree.hostedFields.create({ + client: clientInstance, + styles: { + 'input': { + 'font-size': '16pt', + 'color': '#3A3A3A' + }, + + '.number': { + 'font-family': 'monospace' + }, + '.valid': { + 'color': 'green' + } + }, + fields: { + number: { + selector: '#card-number' + }, + cvv: { + selector: '#cvv' + }, + expirationDate: { + selector: '#expiration-date' + } + } + }, function (hostedFieldsErr?: BraintreeError, hostedFieldsInstance?: any) { + + if (hostedFieldsErr) { + // Handle error in Hosted Fields creation + console.log(`Error Code: ${error.code}, Type: ${error.type}, Message: ${error.message}, Details: ${error.details}`); + return; + } + + let form = new HTMLFormElement(); + + form.addEventListener('submit', function (event: Event) { + event.preventDefault(); + + hostedFieldsInstance.tokenize(function (tokenizeErr: BraintreeError, payload: BraintreeWeb.HostedFieldsTokenizePayload) { + if (tokenizeErr) { + // Handle error in Hosted Fields tokenization + switch (tokenizeErr.code) { + case 'HOSTED_FIELDS_FIELDS_EMPTY': + console.error('All fields are empty! Please fill out the form.'); + break; + case 'HOSTED_FIELDS_FIELDS_INVALID': + console.error('Some fields are invalid:', tokenizeErr.details.invalidFieldKeys); + break; + case 'HOSTED_FIELDS_FAILED_TOKENIZATION': + console.error('Tokenization failed server side. Is the card valid?'); + break; + case 'HOSTED_FIELDS_TOKENIZATION_NETWORK_ERROR': + console.error('Network error occurred when tokenizing.'); + break; + default: + console.error('Something bad happened!', tokenizeErr); + } + return; + } + + // Put `payload.nonce` into the `payment-method-nonce` input, and then + // submit the form. Alternatively, you could send the nonce to your server + // with AJAX. + (document.querySelector('input[name="payment-method-nonce"]') as HTMLInputElement).value = payload.nonce; + form.submit(); + }); + }, false); + + hostedFieldsInstance.on('focus', function (event: BraintreeWeb.HostedFieldsStateObject) { + console.log(event.emittedBy, 'has been focused'); + }); + + hostedFieldsInstance.teardown(function (teardownErr: BraintreeError) { + if (teardownErr) { + console.error('Could not tear down Hosted Fields!'); + } else { + console.info('Hosted Fields has been torn down!'); + } + }); + + hostedFieldsInstance.tokenize({ + vault: true + }, function (tokenizeErr: BraintreeError, payload: BraintreeWeb.HostedFieldsTokenizePayload) { + if (tokenizeErr) { + console.error(tokenizeErr); + } else { + console.log('Got nonce:', payload.nonce); + } + }); + + hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: BraintreeError) { + if (addClassErr) { + console.error(addClassErr); + } + }); + + hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: BraintreeError) { + if (addClassErr) { + console.error(addClassErr); + return; + } + + // some time later... + hostedFieldsInstance.removeClass('number', 'custom-class'); + }); + + hostedFieldsInstance.setPlaceholder('number', '4111 1111 1111 1111', function (placeholderErr: BraintreeError) { + if (placeholderErr) { + console.error(placeholderErr); + } + }); + + hostedFieldsInstance.on('cardTypeChange', function (event: BraintreeWeb.HostedFieldsStateObject) { + // Update the placeholder value if there is only one possible card type + if (event.cards.length === 1) { + braintree.hostedFields.setPlaceholder('cvv', event.cards[0].code.name, function (placeholderErr: BraintreeError) { + if (placeholderErr) { + // Handle errors, such as invalid field name + console.error(placeholderErr); + } + }); + } + }); + + hostedFieldsInstance.clear('number', function (clearErr: BraintreeError) { + if (clearErr) { + console.error(clearErr); + } + }); + + hostedFieldsInstance.clear('number'); + hostedFieldsInstance.clear('cvv'); + hostedFieldsInstance.clear('expirationDate'); + + var state = braintree.hostedFields.getState(); + + var formValid = Object.keys(state.fields).every(function (key) { + return state.fields[key].isValid; + }); + }); + + braintree.applePay.create({ client: clientInstance }, function (createErr?: BraintreeError, applePayInstance?: any) { + if (createErr) { + // Handle error in client creation + console.log(`Error Code: ${error.code}, Type: ${error.type}, Message: ${error.message}, Details: ${error.details}`); + + return; + } + + let request = { + countryCode: 'US', + currencyCode: 'USD', + supportedNetworks: ['visa', 'masterCard'], + merchantCapabilities: ['supports3DS'], + total: { label: 'Your Label', amount: '10.00' }, + }; + + var paymentRequest = braintree.applePay.createPaymentRequest(request); + + console.log(paymentRequest); + // { total: { }, countryCode: 'US', currencyCode: 'USD', merchantCapabilities: [ ], supportedNetworks: [ ] } + }); + + braintree.applePay.create({ client: clientInstance }, function (createErr, applePayInstance) { + let request = { + countryCode: 'US', + currencyCode: 'USD', + supportedNetworks: ['visa', 'masterCard'], + merchantCapabilities: ['supports3DS'], + total: { label: 'Your Label', amount: '10.00' }, + }; + + var session = new ApplePaySession(1, request); + + session.onvalidatemerchant = function (event: { validationURL: string }) { + braintree.applePay.performValidation({ + validationURL: event.validationURL + }, function (err, validationData) { + if (err) { + console.error(err); + session.abort(); + return; + } + session.completeMerchantValidation(validationData); + }); + }; + }); + + braintree.applePay.create({ client: clientInstance }, function (createErr, applePayInstance) { + let request = { + countryCode: 'US', + currencyCode: 'USD', + supportedNetworks: ['visa', 'masterCard'], + merchantCapabilities: ['supports3DS'], + total: { label: 'Your Label', amount: '10.00' }, + }; + + var session = new ApplePaySession(1, request); + + session.onpaymentauthorized = function (event) { + braintree.applePay.tokenize({ + token: event.payment.token + }, function (err, tokenizedPayload) { + if (err) { + session.completePayment(ApplePayStatusCodes.STATUS_FAILURE); + return; + } + session.completePayment(ApplePayStatusCodes.STATUS_SUCCESS); + + // Send the tokenizedPayload to your server. + }); + }; + }); + + braintree.paypal.create({ + client: clientInstance + }, function (createErr, paypalInstance) { + if (createErr) { + if (createErr.code === 'PAYPAL_BROWSER_NOT_SUPPORTED') { + console.error('This browser is not supported.'); + } else { + console.error('Error!', createErr); + } + } + + let button = new HTMLButtonElement(); + + button.addEventListener('click', function () { + // Disable the button so that we don't attempt to open multiple popups. + button.setAttribute('disabled', 'disabled'); + + // Because PayPal tokenization opens a popup, this must be called + // as a result of a user action, such as a button click. + paypalInstance.tokenize({ + flow: 'vault' // Required + // Any other tokenization options + }, function (tokenizeErr: BraintreeError, payload: BraintreeWeb.PayPalTokenizePayload) { + button.removeAttribute('disabled'); + + if (tokenizeErr) { + // Handle tokenization errors or premature flow closure + + switch (tokenizeErr.code) { + case 'PAYPAL_POPUP_CLOSED': + console.error('Customer closed PayPal popup.'); + break; + case 'PAYPAL_ACCOUNT_TOKENIZATION_FAILED': + console.error('PayPal tokenization failed. See details:', tokenizeErr.details); + break; + case 'PAYPAL_FLOW_FAILED': + console.error('Unable to initialize PayPal flow. Are your options correct?', tokenizeErr.details); + break; + default: + console.error('Error!', tokenizeErr); + } + } else { + // Submit payload.nonce to your server + } + }); + }); + }); + + braintree.unionpay.create({ client: clientInstance }, function (createErr, unionpayInstance) { + if (createErr) { + console.error(createErr); + return; + } + + unionpayInstance.fetchCapabilities({ + card: { + number: '4111111111111111' + } + }, function (fetchErr: BraintreeError, cardCapabilities: BraintreeWeb.UnionPayFetchCapabilitiesPayload) { + if (fetchErr) { + console.error(fetchErr); + return; + } + + if (cardCapabilities.isUnionPay) { + if (cardCapabilities.unionPay && !cardCapabilities.unionPay.isSupported) { + // Braintree cannot process this UnionPay card. + // Ask the user for a different card. + return; + } + + if (cardCapabilities.isDebit) { + // CVV and expiration date are not required + } else { + // CVV and expiration date are required + } + + // Show mobile phone number field for enrollment + } + }); + + unionpayInstance.enroll({ + card: { + number: '4111111111111111', + expirationMonth: '12', + expirationYear: '2038' + }, + mobile: { + countryCode: '62', + number: '111111111111' + } + }, function (enrollErr: BraintreeError, response: BraintreeWeb.UnionPayEnrollPayload) { + if (enrollErr) { + console.error(enrollErr); + return; + } + + if (response.smsCodeRequired) { + // If smsCodeRequired, wait for SMS auth code from customer + // Then use response.enrollmentId during {@link UnionPay#tokenize} + } else { + // SMS code is not required from the user. + // {@link UnionPay#tokenize} can be called immediately + } + }); + + let enrollResponse: { + enrollmentId: string + }; + + unionpayInstance.tokenize({ + card: { + number: '4111111111111111', + expirationMonth: '12', + expirationYear: '2038', + cvv: '123' + }, + enrollmentId: enrollResponse.enrollmentId, // Returned from enroll + smsCode: '11111' // Received by customer's phone, if SMS enrollment was required. Otherwise it should be omitted + }, function (tokenizeErr: BraintreeError, response: BraintreeWeb.UnionPayTokenizePayload) { + if (tokenizeErr) { + console.error(tokenizeErr); + return; + } + + // Send response.nonce to your server + }); + + unionpayInstance.teardown(function (teardownErr: BraintreeError) { + if (teardownErr) { + console.error('Could not tear down UnionPay.'); + } else { + console.log('UnionPay has been torn down.'); + } + }); + }); +}); + +let existingNonce = "fake-valid-nonce"; +let submitNonceToServer: (nonce: string) => void; + +braintree.threeDSecure.verifyCard({ + nonce: existingNonce, + amount: 123.45, + addFrame: function (err, iframe) { + // Set up your UI and add the iframe. + let my3DSContainer = document.createElement('div'); + my3DSContainer.appendChild(iframe); + document.body.appendChild(my3DSContainer); + }, + removeFrame: function () { + let my3DSContainer = document.createElement('div'); + + // Remove UI that you added in addFrame. + document.body.removeChild(my3DSContainer); + } +}, function (err: BraintreeError, payload: BraintreeWeb.ThreeDSecureVerifyPayload) { + if (err) { + console.error(err); + return; + } + + if (payload.liabilityShifted) { + // Liablity has shifted + submitNonceToServer(payload.nonce); + } else if (payload.liabilityShiftPossible) { + // Liablity may still be shifted + // Decide if you want to submit the nonce + } else { + // Liablity has not shifted and will not shift + // Decide if you want to submit the nonce + } +}); + +braintree.threeDSecure.cancelVerifyCard(function (err: BraintreeError, verifyPayload: BraintreeWeb.ThreeDSecureVerifyPayload) { + if (err) { + // Handle error + console.log(err.message); // No verification payload available + return; + } + + verifyPayload.nonce; // The nonce returned from the 3ds lookup call + verifyPayload.liabilityShifted; // boolean + verifyPayload.liabilityShiftPossible; // boolean +}); \ No newline at end of file diff --git a/braintree-web/braintree-web.d.ts b/braintree-web/braintree-web.d.ts new file mode 100644 index 0000000000..2cf2d89467 --- /dev/null +++ b/braintree-web/braintree-web.d.ts @@ -0,0 +1,1738 @@ +// Type definitions for Braintree-web v3.0.2 +// Project: https://github.com/braintree/braintree-web +// Definitions by: Guy Shahine +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * @module braintree-web/american-express + * @description This module is for use with Amex Express Checkout. To accept American Express cards, use Hosted Fields. + */ +declare namespace BraintreeWeb { + export interface AmericanExpress { + /** + * @static + * @function create + * @param {object} options Creation options: + * @param {Client} options.client A {@link Client} instance. + * @param {callback} callback The second argument, `data`, is the {@link AmericanExpress} instance. + * @returns {void} + */ + create: (options: { client: Client }, callback: callback) => void; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class + * @param {object} options Options + * @description You cannot use this constructor directly. Use {@link module:braintree-web/american-express.create|braintree.american-express.create} instead. + * @classdesc This class allows you use a nonce to interact with American Express Checkout. To accept American Express cards, use Hosted Fields. + */ + export class AmericanExpress { + /** + * @class + * @param {object} options Options + * @description You cannot use this constructor directly. Use {@link module:braintree-web/american-express.create|braintree.american-express.create} instead. + * @classdesc This class allows you use a nonce to interact with American Express Checkout. To accept American Express cards, use Hosted Fields. + */ + constructor(options: any); + + /** + * Gets the rewards balance associated with a Braintree nonce. + * @public + * @param {object} options Request options + * @param {string} options.nonce An existing Braintree nonce. + * @param {callback} callback The second argument, data, is the returned server data. + * @returns {void} + * @example + * var americanExpress = require('braintree-web/american-express'); + * + * americanExpress.create({client: clientInstance}, function (createErr, americanExpressInstance) { + * var options = {nonce: existingBraintreeNonce}; + * americanExpressInstance.getRewardsBalance(options, function (getErr, payload) { + * if (getErr || payload.error) { + * // Handle error + * return; + * } + * + * console.log('Rewards amount: ' + payload.rewardsAmount); + * }); + * }); + */ + public getRewardsBalance(options: { nonce: string }, callback: callback): void; + + /** + * Gets the Express Checkout nonce profile given a nonce from American Express. + * @public + * @param {object} options Request options + * @param {string} options.nonce An existing nonce from American Express (note that this is not a nonce from Braintree). + * @param {callback} callback The second argument, data, is the returned server data. + * @returns {void} + * @example + * var americanExpress = require('braintree-web/american-express'); + * + * americanExpress.create({client: clientInstance}, function (createErr, americanExpressInstance) { + * var options = {nonce: existingAmericanExpressNonce}; + * americanExpressInstance.getExpressCheckoutProfile(options, function (getErr, payload) { + * if (getErr) { + * // Handle error + * return; + * } + * + * console.log('Number of cards: ' + payload.amexExpressCheckoutCards.length); + * }); + * }); + */ + public getExpressCheckoutProfile(options: { nonce: string }, callback: callback): void; + } +} + + +// more info https://developer.apple.com/reference/applepayjs/1916082-applepay_js_data_types/paymentrequest + +// billingContact +// Billing contact information for the user. +// countryCode +//Required.The merchant’s two- letter ISO 3166 country code. +// currencyCode +// Required.The three- letter ISO 4217 currency code for the payment. +// lineItems +//A set of line items that explain recurring payments and additional charges. +// merchantCapabilities +// Required.The payment capabilities supported by the merchant.The value must be one or more of supports3DS, supportsEMV, supportsCredit, or supportsDebit. +// requiredBillingContactFields +// The billing information that is required from the user.The value must be one or more of postalAddress, phone, email, or name. +// requiredShippingContactFields +// The shipping information that is required from the user.The value must be one or more of postalAddress, phone, email, or name. +// shippingContact +// Shipping contact information for the user. +// shippingMethods +//A set of available shipping methods.Totals for all shipping methods must be non- negative to pass validation. +// shippingType +// How the items are to be shipped.This property is optional.If specified, it must be one or more of shipping, delivery, storePickup, or servicePickup.The default value is shipping. +// supportedNetworks +// Required.The payment networks supported by the merchant.The value must be one or more of amex, discover, interac, masterCard, privateLabel, or visa. +// total +// Required.The total amount for the payment.The total must be greater than zero and have a label to pass validation. +interface ApplePayPaymentRequest { + total: { + label: string; + amount: string; + }; + countryCode: string; + currencyCode: string; + supportedNetworks: string[]; + merchantCapabilities: string[]; + + billingContact?: any; + shippingContact?: any; + shippingMethods?: any; + shippingType?: any; + requiredBillingContactFields?: any; + requiredShippingContactFields?: any; +} + +declare enum ApplePayStatusCodes { + // The requested action succeeded. + STATUS_SUCCESS = 1, + // The requested action failed. + STATUS_FAILURE, + // The billing address is not valid. + STATUS_INVALID_BILLING_POSTAL_ADDRESS, + // The shipping address is not valid. + STATUS_INVALID_SHIPPING_POSTAL_ADDRESS, + // The shipping contact information is not valid. + STATUS_INVALID_SHIPPING_CONTACT, + // The required PIN information was not provided. Cards on the China Union Pay payment network may require a PIN to authenticate the transaction. + STATUS_PIN_REQUIRED, + // The PIN information is not valid.Cards on the China Union Pay network may require a PIN. + STATUS_PIN_INCORRECT, + // The maximum number of tries for a PIN has been reached and the user has been locked out. Cards on the China Union Pay network may require a PIN. + STATUS_PIN_LOCKOUT, +} + +interface ApplePayPayload { + merchantIdentifier: string; + domainName: string; + displayName: string; +} + +declare class ApplePaySession { + constructor(version: number, request: ApplePayPaymentRequest); + + canMakePayments(): boolean; + + canMakePaymentsWithActiveCard(merchantIdentifier: string): boolean; + + completeMerchantValidation(merchantSession: any): void; + + abort(): void; + + begin(): void; + + completePayment(status: ApplePayStatusCodes): void; + + completePaymentMethodSelection(newTotal: any, newLineItems: any): void; + + completeShippingContactSelection(status: ApplePayStatusCodes, newShippingMethods: any, newTotal: any, newLineItems: any): void; + + completeShippingMethodSelection(status: ApplePayStatusCodes, newTotal: any, newLineItems: any): void; + + supportsVersion(version: number): boolean; + + oncancel: (event: any) => void; + + onpaymentauthorized: (event: any) => void; + + onpaymentmethodselected: (event: any) => void; + + onshippingcontactselected: (event: any) => void; + + onshippingmethodselected: (event: any) => void; + + onvalidatemerchant: (event: any) => void; +} + +/** + * @module braintree-web/apple-pay + * @description Accept Apple Pay on the Web. *This component is currently in beta and is subject to change.* + */ +declare namespace BraintreeWeb { + export interface ApplePay { + /** + * @static + * @function create + * @param {object} options Creation options: + * @param {Client} options.client A {@link Client} instance. + * @param {callback} callback The second argument, `data`, is the {@link ApplePay} instance. + * @returns {void} + */ + create: (options: { client: Client }, callback: callback) => void; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class + * @param {object} options Options + * @description You cannot use this constructor directly. Use {@link module:braintree-web/apple-pay.create|braintree.apple-pay.create} instead. + * @classdesc This class represents an Apple Pay component. Instances of this class have methods for validating the merchant server and tokenizing payments. + */ + export class ApplePay { + /** + * @class + * @param {object} options Options + * @description You cannot use this constructor directly. Use {@link module:braintree-web/apple-pay.create|braintree.apple-pay.create} instead. + * @classdesc This class represents an Apple Pay component. Instances of this class have methods for validating the merchant server and tokenizing payments. + */ + constructor(options: any); + + /** + * Merges a payment request with Braintree defaults + * The following properties are assigned to `paymentRequest` if not already defined + * - countryCode + * - currencyCode + * - merchantCapabilities + * - supportedNetworks + * @public + * @param {external:ApplePayPaymentRequest} paymentRequest The payment request details to apply on top of those from Braintree. + * @returns {external:ApplePayPaymentRequest} The decorated `paymentRequest`. + * @example + * var applePay = require('braintree-web/apple-pay'); + * + * applePay.create({client: clientInstance}, function (createErr, applePayInstance) { + * // ... + * var paymentRequest = applePay.createPaymentRequest({ + * total: { + * label: 'My Company', + * amount: '19.99' + * }); + * + * console.log(paymentRequest); + * // { total: { }, countryCode: 'US', currencyCode: 'USD', merchantCapabilities: [ ], supportedNetworks: [ ] } + * + */ + public createPaymentRequest(paymentRequest: ApplePayPaymentRequest): ApplePayPaymentRequest + + /** + * Validates the merchant website, as required by ApplePaySession before payment can be authorized. + * @public + * @param {object} options Options + * @param {string} options.validationURL The validationURL fram an ApplePayValidateMerchantEvent. + * @param {string} [options.displayName] + * - The canonical name for your store. + * - The system may display this name to the user. + * - Use a 128-character or less, UTF-8 string. + * - Do not localize the name. + * @param {string} [options.merchantIdentifier] + * Your Apple merchant identifier. This is the Apple Merchant ID created on the Apple Developer Portal. + * Defaults to the merchant identifier specified in the Braintree Control Panel. + * You can use this field to override the merchant identifier for this transaction. + * @param {callback} callback The second argument, data, is the Apple Pay merchant session object. + * Pass the merchant session to your Apple Pay session's completeMerchantValidation method. + * @returns {void} + * @example + * var applePay = require('braintree-web/apple-pay'); + * + * applePay.create({client: clientInstance}, function (createErr, applePayInstance) { + * var session = new ApplePaySession(1, { + * // This should be the payment request object that + * // contains the information needed to display the payment sheet. + * }); + * + * session.onvalidatemerchant = function (event) { + * applePay.performValidation({ + * validationURL: event.validationURL + * }, function(err, validationData) { + * if (err) { + * console.error(err); + * session.abort(); + * return; + * } + * session.completeMerchantValidation(validationData); + * }); + * }; + * }); + */ + public performValidation(options: { validationURL: string, displayName?: string, merchantIdentifier?: string }, callback: callback): void; + + /** + * Tokenizes an Apple Pay payment. + * @public + * @param {object} options Options + * @param {object} options.token The `payment.token` property of an {@link external:ApplePayPaymentAuthorizedEvent} + * @param {callback} callback The second argument, data, is the tokenized payload. + * @returns {void} + * @example + * var applePay = require('braintree-web/apple-pay'); + * + * applePay.create({client: clientInstance}, function (createErr, applePayInstance) { + * var session = new ApplePaySession(1, { }); + * + * session.onpaymentauthorized = function (event) { + * applePay.tokenize({ + * token: event.payment.token + * }, function (err, tokenizedPayload) { + * if (err) { + * session.completePayment(ApplePaySession.STATUS_FAILURE); + * return; + * } + * session.completePayment(ApplePaySession.STATUS_SUCCESS); + * + * // Send the tokenizedPayload to your server. + * }); + * }; + * }); + */ + public tokenize(options: { token: any }, callback: callback): void; + + } +} + +/** @module braintree-web/client */ +declare namespace BraintreeWeb { + /** + * This object is returned by {@link Client#getConfiguration|getConfiguration}. This information is used extensively by other Braintree modules to properly configure themselves. + * @typedef {object} Client~configuration + * @property {object} client The braintree-web/client parameters. + * @property {string} client.authorization A tokenizationKey or clientToken. + * @property {object} gatewayConfiguration Gateway-supplied configuration. + * @property {object} analyticsMetadata Analytics-specific data. + * @property {string} analyticsMetadata.sessionId Uniquely identifies a browsing session. + * @property {string} analyticsMetadata.sdkVersion The braintree.js version. + * @property {string} analyticsMetadata.merchantAppId Identifies the merchant's web app. + */ + interface ClientAnalyticsMetadata { + sessionId: string; + sdkVersion: string; + merchantAppId: string; + } + + interface Configuration { + client: Client; + gatewayConfiguration: any; + analyticsMetadata: ClientAnalyticsMetadata; + } + + interface CreditCardInfo { + number: string; + cvv: string; + expirationDate: string; + billingAddress: { + postalCode?: string; + } + } + + export interface Client { + authorization: string; + + /** + * @function + * @description This function is the entry point for the braintree.client module. It is used for creating {@link Client} instances that service communication to Braintree servers. + * @param {object} options Object containing all {@link Client} options: + * @param {string} options.authorization A tokenizationKey or clientToken. + * @param {callback} callback The second argument, data, is the {@link Client} instance. + * @returns {void} + * @example + * var createClient = require('braintree-web/client').create; + * + * createClient({ + * authorization: CLIENT_AUTHORIZATION + * }, function (createErr, clientInstance) { + * ... + * }); + * @static + */ + create: (options: { authorization: string }, callback: callback) => void; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class + * @param {Client~configuration} configuration Options + * @description Do not use this constructor directly. Use {@link module:braintree-web/client.create|braintree.client.create} instead. + * @classdesc This class is required by many other Braintree components. It serves as the base API layer that communicates with our servers. It is also capable of being used to formulate direct calls to our servers, such as direct credit card tokenization. See {@link Client#request}. + */ + export class Client { + /** + * @class + * @param {Client~configuration} configuration Options + * @description Do not use this constructor directly. Use {@link module:braintree-web/client.create|braintree.client.create} instead. + * @classdesc This class is required by many other Braintree components. It serves as the base API layer that communicates with our servers. It is also capable of being used to formulate direct calls to our servers, such as direct credit card tokenization. See {@link Client#request}. + */ + constructor(configuration: Configuration); + + + /** + * Returns a copy of the configuration values. + * @public + * @returns {Client~configuration} configuration + */ + public getConfiguration(): Configuration; + + /** + * Used by other modules to formulate all network requests to the Braintree gateway. It is also capable of being used directly from your own form to tokenize credit card information. However, be sure to satisfy PCI compliance if you use direct card tokenization. + * @public + * @param {object} options Request options: + * @param {string} options.method HTTP method. i.e. "get" or "post" + * @param {string} options.endpoint Enpoint path. i.e. "payment_methods" + * @param {object} options.data Data to send with the request + * @param {string} [options.timeout=60000] Timeout limit + * @param {callback} callback The second argument, data, is the returned server data. + * @example + * Direct Credit Card Tokenization + * var createClient = require('braintree-web/client').create; + * + * createClient({ + * authorization: CLIENT_AUTHORIZATION + * }, function (createErr, clientInstance) { + * var form = document.getElementById('my-form-id'); + * var data = { + * creditCard: { + * number: form['cc-number'].value, + * cvv: form['cc-cvv'].value, + * expirationDate: form['cc-date'].value, + * billingAddress: { + * postalCode: form['cc-postal'].value + * } + * } + * }; + * + * // Warning: For a merchant to be eligible for the easiest level of PCI compliance (SAQ A), + * // payment fields cannot be hosted on your checkout page. + * // For an alternative to the following, use Hosted Fields. + * clientInstance.request({ + * endpoint: 'payment_methods/credit_cards', + * method: 'post', + * data: data + * }, function (requestErr, response) { + * if (requestErr) { throw new Error(requestErr); } + * + * console.log('Got nonce:', response.creditCards[0].nonce); + * }); + * }); + * @returns {void} + */ + public request(options: { method: string, endpoint: string, data: any, timeout?: number }, callback: callback): void; + + } +} + +/** @module braintree-web/data-collector */ +declare namespace BraintreeWeb { + export interface DataCollector { + /** + * @static + * @function create + * @param {object} options Creation options: + * @param {Client} options.client A {@link Client} instance. + * @param {boolean} [options.kount] If true, Kount fraud data collection is enabled. + * @param {boolean} [options.paypal] If true, PayPal fraud data collection is enabled. + * @param {callback} callback The second argument, `data`, is the {@link DataCollector} instance. + * @returns {void} + */ + create: (options: { client: Client, kount: boolean, paypal: boolean }, callback: callback) => void; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class + * @global + * @name DataCollector + * @description Do not use this constructor directly. Use {@link module:braintree-web/data-collector.create|braintree-web.data-collector.create} instead. + * @classdesc This class is used for advanced fraud integration with PayPal and Kount. Instances of this class have {@link DataCollector#deviceData|deviceData} which is used to correlate user sessions with server transactions. + */ + export class DataCollector { + /** + * @class + * @global + * @name DataCollector + * @description Do not use this constructor directly. Use {@link module:braintree-web/data-collector.create|braintree-web.data-collector.create} instead. + * @classdesc This class is used for advanced fraud integration with PayPal and Kount. Instances of this class have {@link DataCollector#deviceData|deviceData} which is used to correlate user sessions with server transactions. + */ + constructor(); + + /** + * @memberof DataCollector + * @name deviceData + * @type string + * @description JSON string to pass with server transactions. + * @instance + */ + deviceData: string; + + /** + * @memberof DataCollector + * @name teardown + * @function + * @description Cleanly remove all event handlers and DOM nodes that were added. + * @param {callback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully. + * @instance + * @returns {void} + */ + teardown(callback?: callback): void; + + } +} + +/** @module braintree-web/hosted-fields */ +declare namespace BraintreeWeb { + /** + * Fields used in {@link module:braintree-web/hosted-fields~fieldOptions fields options} + * @typedef {object} field + * @property {string} selector A CSS selector to find the container where the hosted field will be inserted. + * @property {string} [placeholder] Will be used as the `placeholder` attribute of the input. If `placeholder` is not natively supported by the browser, it will be polyfilled. + * @property {boolean} [formatInput=true] - Enable or disable automatic formatting on this field. Note: Input formatting does not work properly on Android and iOS, so input formatting is automatically disabled on those browsers. + */ + interface HostedFieldsField { + selector: string; + placeholder?: string; + formatInput?: boolean; + } + + /** + * An object that has {@link module:braintree-web/hosted-fields~field field objects} for each field. Used in {@link module:braintree-web/hosted-fields~create create}. + * @typedef {object} fieldOptions + * @property {field} [number] A field for card number. + * @property {field} [expirationDate] A field for expiration date in `MM/YYYY` format. This should not be used with the `expirationMonth` and `expirationYear` properties. + * @property {field} [expirationMonth] A field for expiration month in `MM` format. This should be used with the `expirationYear` property. + * @property {field} [expirationYear] A field for expiration year in `YYYY` format. This should be used with the `expirationMonth` property. + * @property {field} [cvv] A field for 3 or 4 digit CVV or CID. + * @property {field} [postalCode] A field for postal or region code. + */ + interface HostedFieldFieldOptions { + number: HostedFieldsField; + expirationDate?: HostedFieldsField; + expirationMonth?: HostedFieldsField; + expirationYear?: HostedFieldsField; + cvv: HostedFieldsField; + postalCode?: HostedFieldsField; + } + + /** + * @typedef {object} HostedFields~hostedFieldsCard + * @description Information about the card type, sent in {@link HostedFields~stateObject|stateObjects}. + * @property {string} type The code-friendly representation of the card type. It will be one of the following strings: + * - `american-express` + * - `diners-club` + * - `discover` + * - `jcb` + * - `maestro` + * - `master-card` + * - `unionpay` + * - `visa` + * @property {string} niceType The pretty-printed card type. It will be one of the following strings: + * - `American Express` + * - `Diners Club` + * - `Discover` + * - `JCB` + * - `Maestro` + * - `MasterCard` + * - `UnionPay` + * - `Visa` + * @property {object} code + * This object contains data relevant to the security code requirements of the card brand. + * For example, on a Visa card there will be a CVV of 3 digits, whereas an + * American Express card requires a 4-digit CID. + * @property {string} code.name "CVV" "CID" "CVC" + * @property {number} code.size The expected length of the security code. Typically, this is 3 or 4. + */ + + interface HostedFieldsCardCode { + name: string; + size: number; + } + + interface HostedFieldsHostedFieldsCard { + type: string; + niceType: string; + code: HostedFieldsCardCode; + } + + /** + * @typedef {object} HostedFields~hostedFieldsFieldData + * @description Data about Hosted Fields fields, sent in {@link HostedFields~stateObject|stateObjects}. + * @property {HTMLElement} container Reference to the container DOM element on your page associated with the current event. + * @property {boolean} isFocused Whether or not the input is currently focused. + * @property {boolean} isEmpty Whether or not the user has entered a value in the input. + * @property {boolean} isPotentiallyValid + * A determination based on the future validity of the input value. + * This is helpful when a user is entering a card number and types "41". + * While that value is not valid for submission, it is still possible for + * it to become a fully qualified entry. However, if the user enters "4x" + * it is clear that the card number can never become valid and isPotentiallyValid will + * return false. + * @property {boolean} isValid Whether or not the value of the associated input is fully qualified for submission. + */ + interface HostedFieldsHostedFieldsFieldData { + container: HTMLElement; + isFocused: boolean; + isEmpty: boolean; + isPotentiallyValid: boolean; + isValid: boolean; + } + + /** + * @typedef {object} HostedFields~stateObject + * @description The event payload sent from {@link HostedFields#on|on} or {@link HostedFields#getState|getState}. + * @property {HostedFields~hostedFieldsCard[]} cards + * This will return an array of potential {@link HostedFields~hostedFieldsCard|cards}. If the card type has been determined, the array will contain only one card. + * Internally, Hosted Fields uses credit-card-type, + * an open-source card detection library. + * @property {string} emittedBy + * The name of the field associated with an event. This will not be included if returned by {@link HostedFields#getState|getState}. It will be one of the following strings:
+ * - `"number"` + * - `"cvv"` + * - `"expirationDate"` + * - `"expirationMonth"` + * - `"expirationYear"` + * - `"postalCode"` + * @property {object} fields + * @property {?HostedFields~hostedFieldsFieldData} fields.number {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the number field, if it is present. + * @property {?HostedFields~hostedFieldsFieldData} fields.cvv {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the CVV field, if it is present. + * @property {?HostedFields~hostedFieldsFieldData} fields.expirationDate {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the expiration date field, if it is present. + * @property {?HostedFields~hostedFieldsFieldData} fields.expirationMonth {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the expiration month field, if it is present. + * @property {?HostedFields~hostedFieldsFieldData} fields.expirationYear {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the expiration year field, if it is present. + * @property {?HostedFields~hostedFieldsFieldData} fields.postalCode {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the postal code field, if it is present. + */ + interface HostedFieldsFieldDataFields { + number: HostedFieldsHostedFieldsFieldData; + cvv: HostedFieldsHostedFieldsFieldData; + expirationDate: HostedFieldsHostedFieldsFieldData; + expirationMonth: HostedFieldsHostedFieldsFieldData; + expirationYear: HostedFieldsHostedFieldsFieldData; + postalCode: HostedFieldsHostedFieldsFieldData; + } + + interface HostedFieldsStateObject { + cards: HostedFieldsHostedFieldsCard[]; + emittedBy: string; + fields: HostedFieldsFieldDataFields; + } + + /** + * @typedef {object} HostedFields~tokenizePayload + * @property {string} nonce The payment method nonce. + * @property {object} details Additional account details. + * @property {string} details.cardType Type of card, ex: Visa, MasterCard. + * @property {string} details.lastTwo Last two digits of card number. + * @property {string} description A human-readable description. + * @property {string} type The payment method type, always `CreditCard`. + */ + interface HostedFieldsAccountDetails { + cardType: string; + lastTwo: string; + } + + interface HostedFieldsTokenizePayload { + nonce: string; + details: HostedFieldsAccountDetails; + type: string; + description: string; + } + + export interface HostedFields { + /** + * @static + * @function create + * @param {object} options Creation options: + * @param {Client} options.client A {@link Client} instance. + * @param {fieldOptions} options.fields A {@link module:braintree-web/hosted-fields~fieldOptions set of options for each field}. + * @param {styleOptions} options.styles {@link module:braintree-web/hosted-fields~styleOptions Styles} applied to each field. + * @param {callback} callback The second argument, `data`, is the {@link HostedFields} instance. + * @returns {void} + * @example + * braintree.hostedFields.create({ + * client: clientInstance, + * styles: { + * 'input': { + * 'font-size': '16pt', + * 'color': '#3A3A3A' + * }, + * '.number': { + * 'font-family': 'monospace' + * }, + * '.valid': { + * 'color': 'green' + * } + * }, + * fields: { + * number: { + * selector: '#card-number' + * }, + * cvv: { + * selector: '#cvv' + * }, + * expirationDate: { + * selector: '#expiration-date' + * } + * } + * }, callback); + */ + create: (options: { client: Client, fields: HostedFieldFieldOptions, styles: any }, callback: callback) => void; + + + /** + * An object that represents CSS that will be applied in each hosted field. This object looks similar to CSS. Typically, these styles involve fonts (such as `font-family` or `color`). + * + * These are the CSS properties that Hosted Fields supports. Any other CSS should be specified on your page and outside of any Braintree configuration. Trying to set unsupported properties will fail and put a warning in the console. + * + * `color` `font-family` `font-size-adjust` `font-size` `font-stretch` `font-style` `font-variant-alternates` `font-variant-caps` `font-variant-east-asian` `font-variant-ligatures` `font-variant-numeric` `font-variant` `font-weight` `font` `line-height` `opacity` `outline` `text-shadow` `transition` `-moz-osx-font-smoothing` `-moz-tap-highlight-color` `-moz-transition` `-webkit-font-smoothing` `-webkit-tap-highlight-color` `-webkit-transition` + * @typedef {object} styleOptions + */ + styleOptions: any; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class HostedFields + * @param {object} options The Hosted Fields {@link module:braintree-web/hosted-fields.create create} options. + * @description Do not use this constructor directly. Use {@link module:braintree-web/hosted-fields.create|braintree-web.hosted-fields.create} instead. + * @classdesc This class represents a Hosted Fields component produced by {@link module:braintree-web/hosted-fields.create|braintree-web/hosted-fields.create}. Instances of this class have methods for interacting with the input fields within Hosted Fields' iframes. + */ + export class HostedFields { + /** + * @class HostedFields + * @param {object} options The Hosted Fields {@link module:braintree-web/hosted-fields.create create} options. + * @description Do not use this constructor directly. Use {@link module:braintree-web/hosted-fields.create|braintree-web.hosted-fields.create} instead. + * @classdesc This class represents a Hosted Fields component produced by {@link module:braintree-web/hosted-fields.create|braintree-web/hosted-fields.create}. Instances of this class have methods for interacting with the input fields within Hosted Fields' iframes. + */ + constructor(options: any); + + /** + * @name HostedFields#on + * @function + * @param {string} event The name of the event to which you are subscribing. + * @param {function} handler A callback to handle the event. + * @description Subscribes a handler function to a named event. `event` should be {@link HostedFields#event:blur|blur}, {@link HostedFields#event:focus|focus}, {@link HostedFields#event:empty|empty}, {@link HostedFields#event:notEmpty|notEmpty}, {@link HostedFields#event:cardTypeChange|cardTypeChange}, or {@link HostedFields#event:validityChange|validityChange}. Events will emit a {@link HostedFields~stateObject|stateObject}. + * @example + * Listening to a Hosted Field event, in this case 'focus' + * hostedFields.create({ ... }, function (createErr, hostedFieldsInstance) { + * hostedFieldsInstance.on('focus', function (event) { + * console.log(event.emittedBy, 'has been focused'); + * }); + * }); + * @returns {void} + */ + on(event: string, handler: (() => any)): void; + + /** + * Cleanly tear down anything set up by {@link module:braintree-web/hosted-fields.create|create} + * @public + * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if teardown completes successfully. + * @example + * hostedFieldsInstance.teardown(function (teardownErr) { + * if (teardownErr) { + * console.error('Could not tear down Hosted Fields!'); + * } else { + * console.info('Hosted Fields has been torn down!'); + * } + * }); + * @returns {void} + */ + public teardown(callback?: callback): void; + + /** + * Tokenizes fields and returns a nonce payload. + * @public + * @param {object} [options] All tokenization options for the Hosted Fields component. + * @param {boolean} [options.vault=false] When true, will vault the tokenized card. Cards will only be vaulted when using a client created with a client token that includes a customer ID. + * @param {callback} callback The second argument, data, is a {@link HostedFields~tokenizePayload|tokenizePayload} + * @example Tokenize a card + * hostedFieldsInstance.tokenize(function (tokenizeErr, payload) { + * if (tokenizeErr) { + * switch (tokenizeErr.code) { + * case 'HOSTED_FIELDS_FIELDS_EMPTY': + * console.error('All fields are empty! Please fill out the form.'); + * break; + * case 'HOSTED_FIELDS_FIELDS_INVALID': + * console.error('Some fields are invalid:', tokenizeErr.details.invalidFieldKeys); + * break; + * case 'HOSTED_FIELDS_FAILED_TOKENIZATION': + * console.error('Tokenization failed server side. Is the card valid?'); + * break; + * case 'HOSTED_FIELDS_TOKENIZATION_NETWORK_ERROR': + * console.error('Network error occurred when tokenizing.'); + * break; + * default: + * console.error('Something bad happened!', tokenizeErr); + * } + * } else { + * console.log('Got nonce:', payload.nonce); + * } + * }); + * @example Tokenize and vault a card + * hostedFieldsInstance.tokenize({ + * vault: true + * }, function (tokenizeErr, payload) { + * if (tokenizeErr) { + * console.error(tokenizeErr); + * } else { + * console.log('Got nonce:', payload.nonce); + * } + * }); + * @returns {void} + */ + public tokenize(options?: { vault: boolean }, callback?: callback): void; + + /** + * Add a class to a {@link module:braintree-web/hosted-fields~field field}. Useful for updating field styles when events occur elsewhere in your checkout. + * @public + * @param {string} field The field you wish to add a class to. Must be a valid {@link module:braintree-web/hosted-fields~fieldOptions fieldOption}. + * @param {string} classname The class to be added. + * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if the class is added successfully. + * + * @example + * hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr) { + * if (addClassErr) { + * console.error(addClassErr); + * } + * }); + * @returns {void} + */ + public addClass(field: string, classname: string, callback?: callback): void; + + /** + * Removes a class to a {@link module:braintree-web/hosted-fields~field field}. Useful for updating field styles when events occur elsewhere in your checkout. + * @public + * @param {string} field The field you wish to remove a class from. Must be a valid {@link module:braintree-web/hosted-fields~fieldOptions fieldOption}. + * @param {string} classname The class to be removed. + * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if the class is removed successfully. + * + * @example + * hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr) { + * if (addClassErr) { + * console.error(addClassErr); + * return; + * } + * + * // some time later... + * hostedFieldsInstance.removeClass('number', 'custom-class'); + * }); + * @returns {void} + */ + public removeClass(field: string, classname: string, callback?: callback): void; + + /** + * Sets the placeholder of a {@link module:braintree-web/hosted-fields~field field}. + * @public + * @param {string} field The field whose placeholder you wish to change. Must be a valid {@link module:braintree-web/hosted-fields~fieldOptions fieldOption}. + * @param {string} placeholder Will be used as the `placeholder` attribute of the input. + * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if the placeholder updated successfully. + * + * @example + * hostedFieldsInstance.setPlaceholder('number', '4111 1111 1111 1111', function (placeholderErr) { + * if (placeholderErr) { + * console.error(placeholderErr); + * } + * }); + * + * @example Update CVV field on card type change + * hostedFieldsInstance.on('cardTypeChange', function (event) { + * // Update the placeholder value if there is only one possible card type + * if (event.cards.length === 1) { + * hostedFields.setPlaceholder('cvv', event.cards[0].code.name, function (placeholderErr) { + * if (placeholderErr) { + * // Handle errors, such as invalid field name + * console.error(placeholderErr); + * } + * }); + * } + * }); + * @returns {void} + */ + public setPlaceholder(field: string, placeholder: string, callback?: callback): void; + + /** + * Clear the value of a {@link module:braintree-web/hosted-fields~field field}. + * @public + * @param {string} field The field whose placeholder you wish to clear. Must be a valid {@link module:braintree-web/hosted-fields~fieldOptions fieldOption}. + * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if the field cleared successfully. + * @returns {void} + * @example + * hostedFieldsInstance.clear('number', function (clearErr) { + * if (clearErr) { + * console.error(clearErr); + * } + * }); + * + * @example Clear several fields + * hostedFieldsInstance.clear('number'); + * hostedFieldsInstance.clear('cvv'); + * hostedFieldsInstance.clear('expirationDate'); + */ + public clear(field: string, callback?: callback): void; + + /** + * Returns an {@link HostedFields~stateObject|object} that includes the state of all fields and possible card types. + * @public + * @returns {object} {@link HostedFields~stateObject|stateObject} + * @example Check if all fields are valid + * var state = hostedFields.getState(); + * + * var formValid = Object.keys(state.fields).every(function (key) { + * return state.fields[key].isValid; + * }); + */ + public getState(): any; + } +} + +/** @module braintree-web/paypal */ +declare namespace BraintreeWeb { + /** + * @typedef {object} PayPal~tokenizeReturn + * @property {Function} close A handle to close the PayPal checkout flow. + */ + interface PayPalTokenizeReturn { + close: (() => any); + } + + /** + * @typedef {object} PayPal~tokenizePayload + * @property {string} nonce The payment method nonce. + * @property {string} type The payment method type, always `PayPalAccount`. + * @property {object} details Additional PayPal account details. + * @property {string} details.email User's email address. + * @property {string} details.payerId User's payer ID, the unique identifier for each PayPal account. + * @property {string} details.firstName User's given name. + * @property {string} details.lastName User's surname. + * @property {?string} details.countryCode User's 2 character country code. + * @property {?string} details.phone User's phone number (e.g. 555-867-5309). + * @property {?object} details.shippingAddress User's shipping address details, only available if shipping address is enabled. + * @property {string} details.shippingAddress.recipientName Recipient of postage. + * @property {string} details.shippingAddress.line1 Street number and name. + * @property {string} details.shippingAddress.line2 Extended address. + * @property {string} details.shippingAddress.city City or locality. + * @property {string} details.shippingAddress.state State or region. + * @property {string} details.shippingAddress.postalCode Postal code. + * @property {string} details.shippingAddress.countryCode 2 character country code (e.g. US). + * @property {?object} details.billingAddress User's billing address details. + * You will also need to enable the PayPal Billing Address Request feature in your PayPal account. + * To enable this feature, [contact PayPal](https://developers.braintreepayments.com/support/guides/paypal/setup-guide#contacting-paypal-support). + * @property {string} details.billingAddress.line1 Street number and name. + * @property {string} details.billingAddress.line2 Extended address. + * @property {string} details.billingAddress.city City or locality. + * @property {string} details.billingAddress.state State or region. + * @property {string} details.billingAddress.postalCode Postal code. + * @property {string} details.billingAddress.countryCode 2 character country code (e.g. US). + */ + interface PayPalShippingAddress { + recipientName: string; + line1: string; + line2: string; + city: string; + state: string; + postalCode: string; + countryCode: string; + } + + interface PayPalBillingAddress { + line1: string; + line2: string; + city: string; + state: string; + postalCode: string; + countryCode: string; + } + + interface PayPalAccountDetails { + email: string; + payerId: string; + firstName: string; + lastName: string; + countryCode: string; + phone: string; + shippingAddress: PayPalShippingAddress; + billingAddress: PayPalBillingAddress; + } + + interface PayPalTokenizePayload { + nonce: string; + type: string; + details: PayPalAccountDetails; + } + + export interface PayPal { + /** + * @static + * @function create + * @param {object} options Creation options: + * @param {Client} options.client A {@link Client} instance. + * @param {callback} callback The second argument, `data`, is the {@link PayPal} instance. + * @example + * braintree.paypal.create( + * client: clientInstance + * }, function (createErr, paypalInstance) { + * if (createErr) { + * if (createErr.code === 'PAYPAL_BROWSER_NOT_SUPPORTED') { + * console.error('This browser is not supported.'); + * } else { + * console.error('Error!', createErr); + * } + * } + * } + * @returns {void} + */ + create: (options: { client: Client }, callback: callback) => void; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class + * @param {object} options see {@link module:braintree-web/paypal.create|paypal.create} + * @classdesc This class represents a PayPal component. Instances of this class have methods for launching auth dialogs and other programmatic interactions with the PayPal component. + */ + export class PayPal { + /** + * @class + * @param {object} options see {@link module:braintree-web/paypal.create|paypal.create} + * @classdesc This class represents a PayPal component. Instances of this class have methods for launching auth dialogs and other programmatic interactions with the PayPal component. + */ + constructor(options: any); + + /** + * Launches the PayPal login flow and returns a nonce payload. Only one PayPal login flow should be active at a time. One way to achieve this is to disable your PayPal button while the flow is open. + * @public + * @param {object} options All tokenization options for the PayPal component. + * @param {string} options.flow Set to 'checkout' for one-time payment flow, or 'vault' for Vault flow. If 'vault' is used with a client token generated with a customer id, the PayPal account will be added to that customer as a saved payment method. + * @param {string} [options.intent=authorize] + * Checkout flows only. + * * `authorize` - Submits the transaction for authorization but not settlement. + * * `sale` - Payment will be immediately submitted for settlement upon creating a transaction. + * @param {boolean} [options.offerCredit=false] Offers the customer PayPal Credit if they qualify. Checkout flows only. + * @param {string} [options.useraction] + * Changes the call-to-action in the PayPal flow. By default the final button will show the localized + * word for "Continue" and implies that the final amount billed is not yet known. + * + * Setting this option to `commit` changes the button text to "Pay Now" and page text will convey to + * the user that billing will take place immediately. + * @param {string|number} [options.amount] The amount of the transaction. Required when using the Checkout flow. + * @param {string} [options.currency] The currency code of the amount, such as 'USD'. Required when using the Checkout flow. + * @param {string} [options.displayName] The merchant name displayed inside of the PayPal lightbox; defaults to the company name on your Braintree account + * @param {string} [options.locale=en_US] Use this option to change the language, links, and terminology used in the PayPal flow to suit the country and language of your customer. + * @param {boolean} [options.enableShippingAddress=false] Returns a shipping address object in {@link PayPal#tokenize}. + * @param {object} [options.shippingAddressOverride] Allows you to pass a shipping address you have already collected into the PayPal payment flow. + * @param {string} options.shippingAddressOverride.line1 Street address. + * @param {string} [options.shippingAddressOverride.line2] Street address (extended). + * @param {string} options.shippingAddressOverride.city City. + * @param {string} options.shippingAddressOverride.state State. + * @param {string} options.shippingAddressOverride.postalCode Postal code. + * @param {string} options.shippingAddressOverride.countryCode Country. + * @param {string} [options.shippingAddressOverride.phone] Phone number. + * @param {string} [options.shippingAddressOverride.recipientName] Recipient's name. + * @param {boolean} [options.shippingAddressEditable=true] Set to false to disable user editing of the shipping address. + * @param {string} [options.billingAgreementDescription] Use this option to set the description of the preapproved payment agreement visible to customers in their PayPal profile during Vault flows. Max 255 characters. + * @param {callback} callback The second argument, data, is a {@link PayPal~tokenizePayload|tokenizePayload}. + * @example + * button.addEventListener('click', function () { + * // Disable the button so that we don't attempt to open multiple popups. + * button.setAttribute('disabled', 'disabled'); + * + * // Because PayPal tokenization opens a popup, this must be called + * // as a result of a user action, such as a button click. + * paypalInstance.tokenize({ + * flow: 'vault' // Required + * // Any other tokenization options + * }, function (tokenizeErr, payload) { + * button.removeAttribute('disabled'); + * + * if (tokenizeErr) { + * // Handle tokenization errors or premature flow closure + * + * switch (tokenizeErr.code) { + * case 'PAYPAL_POPUP_CLOSED': + * console.error('Customer closed PayPal popup.'); + * break; + * case 'PAYPAL_ACCOUNT_TOKENIZATION_FAILED': + * console.error('PayPal tokenization failed. See details:', tokenizeErr.details); + * break; + * case 'PAYPAL_FLOW_FAILED': + * console.error('Unable to initialize PayPal flow. Are your options correct?', tokenizeErr.details); + * break; + * default: + * console.error('Error!', tokenizeErr); + * } + * } else { + * // Submit payload.nonce to your server + * } + * }); + * }); + * @returns {PayPal~tokenizeReturn} A handle to close the PayPal checkout frame. + */ + public tokenize(options: { flow: string, intent: string, offerCredit: boolean, useraction: string, amount: (string | number), currency: string, displayName: string, locale: string, enableShippingAddress: boolean, shippingAddressOverride: PayPalShippingAddress, shippingAddressEditable: boolean, billingAgreementDescription: string }, callback: callback): PayPalTokenizeReturn; + + /** + * Cleanly tear down anything set up by {@link module:braintree-web/paypal.create|create}. + * @public + * @param {callback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully. + * @returns {void} + */ + public teardown(callback?: () => void): void; + + } +} + +/** @module braintree-web/three-d-secure */ +declare namespace BraintreeWeb { + /** + * @typedef {object} ThreeDSecure~verifyPayload + * @property {string} nonce The new payment method nonce produced by the 3D Secure lookup. The original nonce passed into {@link ThreeDSecure#verifyCard|verifyCard} was consumed. This new nonce should be used to transact on your server. + * @property {object} details Additional account details. + * @property {string} details.cardType Type of card, ex: Visa, MasterCard. + * @property {string} details.lastTwo Last two digits of card number. + * @property {string} description A human-readable description. + * @property {boolean} liabilityShiftPossible Indicates whether the card was eligible for 3D Secure. + * @property {boolean} liabilityShifted Indicates whether the liability for fraud has been shifted away from the merchant. + */ + interface ThreeDSecureAccountDetails { + cardType: string; + lastTwo: string; + } + + interface ThreeDSecureVerifyPayload { + nonce: string; + details: ThreeDSecureAccountDetails; + description: string; + liabilityShiftPossible: boolean; + liabilityShifted: boolean; + } + + export interface ThreeDSecure { + /** + * @static + * @function create + * @param {object} options Creation options: + * @param {Client} options.client A {@link Client} instance. + * @param {callback} callback The second argument, `data`, is the {@link ThreeDSecure} instance. + * @returns {void} + * @example + * braintree.threeDSecure.create({ + * client: client + * }, callback); + */ + create: (options: { client: Client }, callback: callback) => void; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class + * @param {object} options 3D Secure {@link module:braintree-web/three-d-secure.create create} options + * @description Do not use this constructor directly. Use {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create} instead. + * @classdesc This class represents a ThreeDSecure component produced by {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create}. Instances of this class have a method for launching a 3D Secure authentication flow. + */ + export class ThreeDSecure { + /** + * @class + * @param {object} options 3D Secure {@link module:braintree-web/three-d-secure.create create} options + * @description Do not use this constructor directly. Use {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create} instead. + * @classdesc This class represents a ThreeDSecure component produced by {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create}. Instances of this class have a method for launching a 3D Secure authentication flow. + */ + constructor(options: any); + + + /** + * @callback ThreeDSecure~addFrameCallback + * @param {?BraintreeError} [err] `null` or `undefined` if there was no error. + * @param {HTMLIFrameElement} iframe An iframe element containing the bank's authentication page that you must put on your page. + * @description The callback used for options.addFrame in {@link ThreeDSecure#verifyCard|verifyCard}. + * @returns {void} + */ + addFrameCallback: (err?: BraintreeError, iframe?: HTMLIFrameElement) => void; + + /** + * @callback ThreeDSecure~removeFrameCallback + * @description The callback used for options.removeFrame in {@link ThreeDSecure#verifyCard|verifyCard}. + * @returns {void} + */ + removeFrameCallback: () => void; + + /** + * Launch the 3D Secure login flow, returning a nonce payload. + * @public + * @param {object} options Options for card verification. + * @param {string} options.nonce A nonce referencing the card to be verified. For example, this can be a nonce that was returned by Hosted Fields. + * @param {number} options.amount The amount of the transaction in the current merchant account's currency. For example, if you are running a transaction of $123.45 US dollars, `amount` would be 123.45. + * @param {errback} options.addFrame This {@link ThreeDSecure~addFrameCallback|addFrameCallback} will be called when the bank frame needs to be added to your page. + * @param {callback} options.removeFrame This {@link ThreeDSecure~removeFrameCallback|removeFrameCallback} will be called when the bank frame needs to be removed from your page. + * @param {errback} callback The second argument, data, is a {@link ThreeDSecure~verifyPayload|verifyPayload} + * @returns {void} + * @example + * Verifying an existing nonce with 3DS + * var my3DSContainer; + * + * threeDSecure.verifyCard({ + * nonce: existingNonce, + * amount: 123.45, + * addFrame: function (err, iframe) { + * // Set up your UI and add the iframe. + * my3DSContainer = document.createElement('div'); + * my3DSContainer.appendChild(iframe); + * document.body.appendChild(my3DSContainer); + * }, + * removeFrame: function () { + * // Remove UI that you added in addFrame. + * document.body.removeChild(my3DSContainer); + * } + * }, function (err, payload) { + * if (err) { + * console.error(err); + * return; + * } + * + * if (payload.liabilityShifted) { + * // Liablity has shifted + * submitNonceToServer(payload.nonce); + * } else if (payload.liabilityShiftPossible) { + * // Liablity may still be shifted + * // Decide if you want to submit the nonce + * } else { + * // Liablity has not shifted and will not shift + * // Decide if you want to submit the nonce + * } + * }); + */ + public verifyCard(options: { nonce: string, amount: number, addFrame: (err?: BraintreeError, iframe?: HTMLIFrameElement) => void, removeFrame: () => void }, callback: callback): void; + + /** + * Cancel the 3DS flow and return the verification payload if available. + * @public + * @param {errback} callback The second argument is a {@link ThreeDSecure~verifyPayload|verifyPayload}. If there is no verifyPayload (the initial lookup did not complete), an error will be returned. + * @returns {void} + * @example + * threeDSecure.cancelVerifyCard(function (err, verifyPayload) { + * if (err) { + * // Handle error + * console.log(err.message); // No verification payload available + * return; + * } + * + * verifyPayload.nonce; // The nonce returned from the 3ds lookup call + * verifyPayload.liabilityShifted; // boolean + * verifyPayload.liabilityShiftPossible; // boolean + * }); + */ + public cancelVerifyCard(callback: callback): void; + + /** + * Cleanly tear down anything set up by {@link module:braintree-web/three-d-secure.create|create} + * @public + * @param {errback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully. + * @returns {void} + */ + public teardown(callback?: callback): void; + } +} + +/** + * @module braintree-web/unionpay + * @description This module allows you to accept UnionPay payments. *It is currently in beta and is subject to change.* + */ +declare namespace BraintreeWeb { + /** + * @typedef {object} UnionPay~tokenizePayload + * @property {string} nonce The payment method nonce. + * @property {string} type Always CreditCard. + * @property {object} details Additional account details: + * @property {string} details.cardType Type of card, ex: Visa, MasterCard. + * @property {string} details.lastTwo Last two digits of card number. + * @property {string} description A human-readable description. + */ + interface UnionPayAccountDetails { + cardType: string; + lastTwo: string; + description: string; + } + + interface UnionPayTokenizePayload { + nonce: string; + type: string; + details: UnionPayAccountDetails; + } + + /** + * @typedef {object} UnionPay~enrollPayload + * @property {string} enrollmentId UnionPay enrollment ID. This value should be passed to `tokenize`. + * @property {boolean} smsCodeRequired UnionPay `smsCodeRequired` flag. + *

true - the user will receive an SMS code that needs to be supplied for tokenization. + *

false - the card can be immediately tokenized. + */ + interface UnionPayEnrollPayload { + enrollmentId: string; + smsCodeRequired: boolean; + } + + /** + * @typedef {object} UnionPay~fetchCapabilitiesPayload + * @property {boolean} isUnionPay Determines if this card is a UnionPay card. + * @property {boolean} isDebit Determines if this card is a debit card. This property is only present if `isUnionPay` is `true`. + * @property {object} unionPay UnionPay specific properties. This property is only present if `isUnionPay` is `true`. + * @property {boolean} unionPay.supportsTwoStepAuthAndCapture Determines if the card allows for an authorization, but settling the transaction later. + * @property {boolean} unionPay.isSupported Determines if Braintree can process this UnionPay card. When false, Braintree cannot process this card and the user should use a different card. + */ + + interface UnionPayProperties { + supportsTwoStepAuthAndCapture: boolean; + isSupported: boolean; + } + + interface UnionPayFetchCapabilitiesPayload { + isUnionPay: boolean; + isDebit: boolean; + unionPay: UnionPayProperties; + } + + export interface UnionPay { + /** + * @static + * @function create + * @param {object} options Creation options: + * @param {Client} options.client A {@link Client} instance. + * @param {callback} callback The second argument, `data`, is the {@link UnionPay} instance. + * @returns {void} + * @example + * braintree.unionpay.create({ client: clientInstance }, function (createErr, unionpayInstance) { + * if (createErr) { + * console.error(createErr); + * return; + * } + * // ... + * }); + */ + create: (options: { client: Client }, callback: callback) => void; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class + * @param {object} options See {@link module:braintree-web/unionpay.create|unionpay.create}. + * @description You cannot use this constructor directly. Use {@link module:braintree-web/unionpay.create|braintree-web.unionpay.create} instead. + * @classdesc This class represents a UnionPay component. Instances of this class have methods for {@link UnionPay#fetchCapabilities fetching capabilities} of UnionPay cards, {@link UnionPay#enroll enrolling} a UnionPay card, and {@link UnionPay#tokenize tokenizing} a UnionPay card. + */ + export class UnionPay { + /** + * @class + * @param {object} options See {@link module:braintree-web/unionpay.create|unionpay.create}. + * @description You cannot use this constructor directly. Use {@link module:braintree-web/unionpay.create|braintree-web.unionpay.create} instead. + * @classdesc This class represents a UnionPay component. Instances of this class have methods for {@link UnionPay#fetchCapabilities fetching capabilities} of UnionPay cards, {@link UnionPay#enroll enrolling} a UnionPay card, and {@link UnionPay#tokenize tokenizing} a UnionPay card. + */ + constructor(options: any); + + /** + * Fetches the capabilities of a card, including whether or not the SMS enrollment process is required. + * @public + * @param {object} options UnionPay {@link UnionPay#fetchCapabilities fetchCapabilities} options + * @param {object} [options.card] The card from which to fetch capabilities. Note that this will only have one property, `number`. Required if you are not using the `hostedFields` option. + * @param {string} options.card.number Card number. + * @param {HostedFields} [options.hostedFields] The Hosted Fields instance used to collect card data. Required if you are not using the `card` option. + * @param {callback} callback The second argument, data, is a {@link UnionPay#fetchCapabilitiesPayload fetchCapabilitiesPayload}. + * @example With raw card data + * unionpayInstance.fetchCapabilities({ + * card: { + * number: '4111111111111111' + * } + * }, function (fetchErr, cardCapabilities) { + * if (fetchErr) { + * console.error(fetchErr); + * return; + * } + * + * if (cardCapabilities.isUnionPay) { + * if (cardCapabilities.unionPay && !cardCapabilities.unionPay.isSupported) { + * // Braintree cannot process this UnionPay card. + * // Ask the user for a different card. + * return; + * } + * + * if (cardCapabilities.isDebit) { + * // CVV and expiration date are not required + * } else { + * // CVV and expiration date are required + * } + * + * // Show mobile phone number field for enrollment + * } + * }); + * @example With Hosted Fields + * // Fetch capabilities on `blur` inside of the Hosted Fields `create` callback + * hostedFieldsInstance.on('blur', function (event) { + * // Only attempt to fetch capabilities when a valid card number has been entered + * if (event.emittedBy === 'number' && event.fields.number.isValid) { + * unionpayInstance.fetchCapabilities({ + * hostedFields: hostedFieldsInstance + * }, function (fetchErr, cardCapabilities) { + * if (fetchErr) { + * console.error(fetchErr); + * return; + * } + * + * if (cardCapabilities.isUnionPay) { + * if (cardCapabilities.unionPay && !cardCapabilities.unionPay.isSupported) { + * // Braintree cannot process this UnionPay card. + * // Ask the user for a different card. + * return; + * } + * if (cardCapabilities.isDebit) { + * // CVV and expiration date are not required + * // Hide the containers with your `cvv` and `expirationDate` fields + * } else { + * // CVV and expiration date are required + * } + * } else { + * // Not a UnionPay card + * // When form is complete, tokenize using your Hosted Fields instance + * } + * + * // Show your own mobile country code and phone number inputs for enrollment + * }); + * }); + * }); + * @returns {void} + */ + public fetchCapabilities(options: { card: any, hostedFields: HostedFields }, callback: callback): void; + + /** + * Enrolls a UnionPay card. Use {@link UnionPay#fetchCapabilities|fetchCapabilities} to determine if the SMS enrollment process is required. + * @public + * @param {object} options UnionPay enrollment options: + * @param {object} [options.card] The card to enroll. Required if you are not using the `hostedFields` option. + * @param {string} options.card.number The card number. + * @param {string} [options.card.expirationDate] The card's expiration date. May be in the form `MM/YY` or `MM/YYYY`. When defined `expirationMonth` and `expirationYear` are ignored. + * @param {string} [options.card.expirationMonth] The card's expiration month. This should be used with the `expirationYear` parameter. When `expirationDate` is defined this parameter is ignored. + * @param {string} [options.card.expirationYear] The card's expiration year. This should be used with the `expirationMonth` parameter. When `expirationDate` is defined this parameter is ignored. + * @param {HostedFields} [options.hostedFields] The Hosted Fields instance used to collect card data. Required if you are not using the `card` option. + * @param {object} options.mobile The mobile information collected from the customer. + * @param {string} options.mobile.countryCode The country code of the customer's mobile phone number. + * @param {string} options.mobile.number The customer's mobile phone number. + * @param {callback} callback The second argument, data, is a {@link UnionPay~enrollPayload|enrollPayload}. + * @example With raw card data + * unionpayInstance.enroll({ + * card: { + * number: '4111111111111111', + * expirationMonth: '12', + * expirationYear: '2038' + * }, + * mobile: { + * countryCode: '62', + * number: '111111111111' + * } + * }, function (enrollErr, response) { + * if (enrollErr) { + * console.error(enrollErr); + * return; + * } + * + * if (response.smsCodeRequired) { + * // If smsCodeRequired, wait for SMS auth code from customer + * // Then use response.enrollmentId during {@link UnionPay#tokenize} + * } else { + * // SMS code is not required from the user. + * // {@link UnionPay#tokenize} can be called immediately + * }); + * @example With Hosted Fields + * unionpayInstance.enroll({ + * hostedFields: hostedFields, + * mobile: { + * countryCode: '62', + * number: '111111111111' + * } + * }, function (enrollErr, response) { + * if (enrollErr) { + * console.error(enrollErr); + * return; + * } + * + * if (response.smsCodeRequired) { + * // If smsCodeRequired, wait for SMS auth code from customer + * // Then use response.enrollmentId during {@link UnionPay#tokenize} + * } else { + * // SMS code is not required from the user. + * // {@link UnionPay#tokenize} can be called immediately + * } + * }); + * @returns {void} + */ + public enroll(options: { card: any, hostedFields: HostedFields, mobile: any }, callback: callback): void; + + /** + * Tokenizes a UnionPay card and returns a nonce payload. + * @public + * @param {object} options UnionPay tokenization options: + * @param {object} [options.card] The card to enroll. Required if you are not using the `hostedFields` option. + * @param {string} options.card.number The card number. + * @param {string} [options.card.expirationDate] The card's expiration date. May be in the form `MM/YY` or `MM/YYYY`. When defined `expirationMonth` and `expirationYear` are ignored. + * @param {string} [options.card.expirationMonth] The card's expiration month. This should be used with the `expirationYear` parameter. When `expirationDate` is defined this parameter is ignored. + * @param {string} [options.card.expirationYear] The card's expiration year. This should be used with the `expirationMonth` parameter. When `expirationDate` is defined this parameter is ignored. + * @param {string} [options.card.cvv] The card's security number. + * @param {HostedFields} [options.hostedFields] The Hosted Fields instance used to collect card data. Required if you are not using the `card` option. + * @param {string} options.enrollmentId The enrollment ID from {@link UnionPay#enroll}. + * @param {string} [options.smsCode] The SMS code received from the user if {@link UnionPay#enroll} payload have `smsCodeRequired`. if `smsCodeRequired` is false, smsCode should not be passed. + * @param {callback} callback The second argument, data, is a {@link UnionPay~tokenizePayload|tokenizePayload}. + * @example With raw card data + * unionpayInstance.tokenize({ + * card: { + * number: '4111111111111111', + * expirationMonth: '12', + * expirationYear: '2038', + * cvv: '123' + * }, + * enrollmentId: enrollResponse.enrollmentId, // Returned from enroll + * smsCode: '11111' // Received by customer's phone, if SMS enrollment was required. Otherwise it should be omitted + * }, function (tokenizeErr, response) { + * if (tokenizeErr) { + * console.error(tokenizeErr); + * return; + * } + * + * // Send response.nonce to your server + * }); + * @example With Hosted Fields + * unionpayInstance.tokenize({ + * hostedFields: hostedFieldsInstance, + * enrollmentId: enrollResponse.enrollmentId, // Returned from enroll + * smsCode: '11111' // Received by customer's phone, if SMS enrollment was required. Otherwise it should be omitted + * }, function (tokenizeErr, response) { + * if (tokenizeErr) { + * console.error(tokenizeErr); + * return; + * } + * + * // Send response.nonce to your server + * }); + * @returns {void} + */ + public tokenize(options: { card: any, hostedFields: HostedFields, enrollmentId: string, smsCode: string }, callback: callback): void; + + /** + * Cleanly tear down anything set up by {@link module:braintree-web/unionpay.create|create}. This only needs to be called when using UnionPay with Hosted Fields. + * @public + * @param {callback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully. + * @example + * unionpayInstance.teardown(function (teardownErr) { + * if (teardownErr) { + * console.error('Could not tear down UnionPay.'); + * } else { + * console.log('UnionPay has been torn down.'); + * } + * }); + * @returns {void} + */ + public teardown(callback?: callback): void; + + } +} + +declare namespace BraintreeError { + /** + * Enum for {@link BraintreeError} types. + * @name BraintreeError.types + * @enum + * @readonly + * @memberof BraintreeError + * @property {string} CUSTOMER An error caused by the customer. + * @property {string} MERCHANT An error that is actionable by the merchant. + * @property {string} NETWORK An error due to a network problem. + * @property {string} INTERNAL An error caused by Braintree code. + * @property {string} UNKNOWN An error where the origin is unknown. + */ + export enum Types { + CUSTOMER, + MERCHANT, + NETWORK, + INTERNAL, + UNKNOWN + } +} + +/** + * @class + * @global + * @param {object} options Construction options + * @classdesc This class is used to report error conditions, frequently as the first parameter to callbacks throughout the Braintree SDK. + * @description You cannot use this constructor directly. Interact with instances of this class through {@link callback callbacks}. + */ +declare class BraintreeError { + /** + * @class + * @global + * @param {object} options Construction options + * @classdesc This class is used to report error conditions, frequently as the first parameter to callbacks throughout the Braintree SDK. + * @description You cannot use this constructor directly. Interact with instances of this class through {@link callback callbacks}. + */ + constructor(options: any); + + /** + * @type {string} + * @description A code that corresponds to specific errors. + */ + code: string; + + /** + * @type {string} + * @description A short description of the error. + */ + message: string; + + /** + * @type {BraintreeError.types} + * @description The type of error. + */ + type: BraintreeError.Types; + + /** + * @type {object=} + * @description Additional information about the error, such as an underlying network error response. + */ + details: any; +} + +declare namespace BraintreeWeb { + /** + * @global + * @callback callback + * @param {?BraintreeError} [err] `null` or `undefined` if there was no error. + * @param {?any} [data] The successful result of the asynchronous function call (if data exists). + * @description The Node.js-style callback pattern used throughout the SDK. + * @returns {void} + */ + type callback = (err?: BraintreeError, data?: any) => void; +} + +/** + * @module braintree-web + * @description This is the top-level module exported by the Braintree JavaScript SDK. In a browser environment, this will be the global braintree object. In a CommonJS environment (like Browserify or Webpack), it will be the default export of the braintree-web package. In AMD environments (like RequireJS), it can be `require`d like other modules. + * @example + * CommonJS + * var braintree = require('braintree-web'); + * + * braintree.client.create(...); + * @example + * In the browser + * + * + * @example + * AMD + * // main.js + * require.config({ + * paths: { + * braintreeClient: 'https://js.braintreegateway.com/web/3.0.2/js/client.min' + * } + * }); + * + * require(['braintreeClient'], function (braintreeClient) { + * braintreeClient.create(...); + * }); + */ +interface BraintreeStatic { + /** @type {module:braintree-web/client} */ + client: BraintreeWeb.Client; + + /** @type {module:braintree-web/paypal} */ + paypal: BraintreeWeb.PayPal; + + /** @type {module:braintree-web/hosted-fields} */ + hostedFields: BraintreeWeb.HostedFields; + + /** @type {module:braintree-web/three-d-secure} */ + threeDSecure: BraintreeWeb.ThreeDSecure; + + /** @type {module:braintree-web/data-collector} */ + dataCollector: BraintreeWeb.DataCollector; + + /** @type {module:braintree-web/american-express} */ + americanExpress: BraintreeWeb.AmericanExpress; + + /** @type {module:braintree-web/unionpay} */ + unionpay: BraintreeWeb.UnionPay; + + /** @type {module:braintree-web/apple-pay} */ + applePay: BraintreeWeb.ApplePay; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; +} + +declare var braintree: BraintreeStatic; \ No newline at end of file diff --git a/bunnymq/bunnymq-tests.ts b/bunnymq/bunnymq-tests.ts new file mode 100644 index 0000000000..208eb7e992 --- /dev/null +++ b/bunnymq/bunnymq-tests.ts @@ -0,0 +1,36 @@ +/// + +import * as bunnymq from "bunnymq"; + +// Basic usage +var instance = bunnymq({ host: 'amqp://localhost' }); + +// Publisher +instance.producer.produce('queue:name', 'Hello World!'); +// Subscriber +instance.consumer.consume('queue:name', message => { }); + +// RPC Support +instance.producer.produce('queue:name', { message: 'content' }, { rpc: true }) + .then(function (consumerResponse) { + console.log(consumerResponse); + }); + +// Routing keys +instance.producer.produce('queue:name', { message: 'content' }, { routingKey: 'my-routing-key' }); + +// Config +var custom = bunnymq({ + host: 'amqp://localhost', + //number of fetched messages at once on the channel + prefetch: 5, + //requeue put back message into the broker if consumer crashes/trigger exception + requeue: true, + //time between two reconnect (ms) + timeout: 1000, + consumerSuffix: '', + //generate a hostname so we can track this connection on the broker (rabbitmq management plugin) + hostname: "", + //the transport to use to debug. if provided, bunnymq will show some logs + transport: new Object() +}); \ No newline at end of file diff --git a/bunnymq/bunnymq.d.ts b/bunnymq/bunnymq.d.ts new file mode 100644 index 0000000000..1167db21ed --- /dev/null +++ b/bunnymq/bunnymq.d.ts @@ -0,0 +1,120 @@ +// Type definitions for node-bunnymq 2.2.1 +// Project: https://github.com/dial-once/node-bunnymq +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "bunnymq" { + namespace bunnymq { + export type ConsumerCallback = (message: Object) => void; + + /** + * Consumer. + * @interface + */ + export interface Consumer { + /** + * Handle messages from a named queue. + * @param {string} queue A named queue. + * @param {ConsumerCallback} callback A callback. + */ + consume(queue: string, callback: ConsumerCallback): void; + } + + /** + * bunnymq instance. + * @interface + */ + export interface Instance { + /** + * Consumer. + * @type {Consumer} + */ + consumer: Consumer; + + /** + * Producer. + * @type {Producer} + */ + producer: Producer; + } + + /** + * Options. + * @interface + */ + export interface Options { + /** + * Consumer suffix. + * @type {string} + */ + consumerSuffix?: string; + + /** + * Host. + * @type {string} + */ + host?: string; + + /** + * Hostname. + * @type {string} + */ + hostname?: string; + + /** + * Number of fetched messages at once on the channel. + * @type {number} + */ + prefetch?: number; + + /** + * Requeue put back message into the broker if consumer crashes/trigger exception. + * @type {boolean} + */ + requeue?: boolean; + + /** + * Time between two reconnect (in milliseconds). + * @type {number} + */ + timeout?: number; + + /** + * Transport. + * @type {any} + */ + transport?: any; + } + + /** + * Producer. + * @inteface + */ + export interface Producer { + /** + * Send messages to a named queue. + * @param {string} queue A named queue. + * @param {Object} message A message. + * @return {Object} The consumer response. + */ + produce(queue: string, message: Object, options?: ProducerOptions): PromiseLike; + } + + /** + * Options for producer. + * @interface + */ + export interface ProducerOptions { + routingKey?: string; + rpc?: boolean; + } + } + + /** + * Constructor. + * @param {Options} [options] Options. + * @return {Instance} A instance of bunnymq. + */ + function bunnymq(options?: bunnymq.Options): bunnymq.Instance; + export = bunnymq; +} diff --git a/busboy/busboy-tests.ts b/busboy/busboy-tests.ts new file mode 100644 index 0000000000..058b5c92d3 --- /dev/null +++ b/busboy/busboy-tests.ts @@ -0,0 +1,39 @@ +/// +/// + +import * as Busboy from 'busboy'; +import * as http from 'http'; +import * as util from 'util'; + +function serverFn(req: http.ServerRequest, res: http.ServerResponse) { + if (req.method === 'POST') { + var busboy = new Busboy({ headers: req.headers }); + busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { + console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype); + file.on('data', function(data: Buffer) { + console.log('File [' + fieldname + '] got ' + data.length + ' bytes'); + }); + file.on('end', function() { + console.log('File [' + fieldname + '] Finished'); + }); + }); + busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) { + console.log('Field [' + fieldname + ']: value: ' + util.inspect(val)); + }); + busboy.on('finish', function() { + console.log('Done parsing form!'); + res.writeHead(303, { Connection: 'close', Location: '/' }); + res.end(); + }); + req.pipe(busboy); + } else if (req.method === 'GET') { + res.writeHead(200, { Connection: 'close' }); + res.end('\ +
\ +
\ +
\ + \ +
\ + '); + } +} diff --git a/busboy/busboy.d.ts b/busboy/busboy.d.ts new file mode 100644 index 0000000000..3b64f3d112 --- /dev/null +++ b/busboy/busboy.d.ts @@ -0,0 +1,60 @@ +// Type definitions for busboy v0.2.13 +// Project: https://www.npmjs.com/package/busboy +// Definitions by: Jacob Baskin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + +declare namespace busboy { + interface Options { + headers: any; + } + + interface BusboyConfig { + headers?: any; + highWaterMark?: number; + fileHwm?: number; + defCharset?: string; + preservePath?: boolean; + limits?: { + fieldNameSize?: number; + fieldSize?: number; + fields?: number; + fileSize?: number; + files?: number; + parts?: number; + headerPairs?: number; + }; + } + + interface Busboy extends NodeJS.WritableStream { + on(event: 'field', + listener: ( + fieldname: string, + val: any, + fieldnameTruncated: boolean, + valTruncated: boolean, + encoding: string, + mimetype: string) => void): this; + on(event: 'file', + listener: ( + fieldname: string, + file: NodeJS.ReadableStream, + filename: string, + encoding: string, + mimetype: string) => void): this; + on(event: 'finish', callback: () => void): this; + on(event: 'partsLimit', callback: () => void): this; + on(event: 'filesLimit', callback: () => void): this; + on(event: 'fieldsLimit', callback: () => void): this; + on(event: string, listener: Function): this; + } + + interface BusboyConstructor { + new (options: BusboyConfig): Busboy; + } +} + +declare module 'busboy' { + const temp: busboy.BusboyConstructor; + export = temp; +} diff --git a/cache-manager/cache-manager.d.ts b/cache-manager/cache-manager.d.ts index 9570857f01..de6cf867a7 100644 --- a/cache-manager/cache-manager.d.ts +++ b/cache-manager/cache-manager.d.ts @@ -28,7 +28,7 @@ declare module 'cache-manager' { module cacheManager { - function caching(ICongig: StoreConfig): Cache; + function caching(IConfig: StoreConfig): Cache; function multiCaching(Caches: Cache[]): Cache; } diff --git a/canvas-gauges/canvas-gauges-tests.ts b/canvas-gauges/canvas-gauges-tests.ts new file mode 100644 index 0000000000..d0f04e1082 --- /dev/null +++ b/canvas-gauges/canvas-gauges-tests.ts @@ -0,0 +1,20 @@ +/// + +import { + LinearGaugeOptions, + RadialGaugeOptions, + LinearGauge, + RadialGauge +} from 'canvas-gauges'; + +let linearOptions: LinearGaugeOptions = { + renderTo: document.createElement('canvas') +}; +let radialOptions: RadialGaugeOptions = { + renderTo: 'gauge-id' +}; + +new LinearGauge(linearOptions); +new RadialGauge(radialOptions); + +console.log(document.gauges.length); diff --git a/canvas-gauges/canvas-gauges.d.ts b/canvas-gauges/canvas-gauges.d.ts new file mode 100644 index 0000000000..53858e566e --- /dev/null +++ b/canvas-gauges/canvas-gauges.d.ts @@ -0,0 +1,263 @@ +// Type definitions for canvas-gauges +// Project: https://github.com/Mikhus/canvas-gauges +// Definitions by: Mikhus +// Definitions: https://github.com/Mikhus/DefinitelyTyped + +declare namespace CanvasGauges { + export type RenderTarget = string|HTMLElement; + + export interface AnimationRule { + (percent: number): number; + } + + export interface Highlight { + from: number, + to: number, + color: string + } + + export type MajorTicks = string[]|number[]; + + export interface GenericOptions { + renderTo: RenderTarget, + width?: number, + height?: number, + minValue?: number, + maxValue?: number, + value?: number, + units?: string|boolean, + majorTicks?: MajorTicks, + minorTicks?: number, + strokeTicks?: boolean, + animatedValue?: boolean, + title?: string|boolean, + borders?: boolean, + valueInt?: number, + valueDec?: number, + majorTicksInt?: number, + majorTicksDec?: number, + animation?: boolean, + animationDuration?: number, + animationRule?: string|AnimationRule, + colorPlate?: string, + colorMajorTicks?: string, + colorMinorTicks?: string, + colorTitle?: string, + colorUnits?: string, + colorNumbers?: string, + colorNeedle?: string, + colorNeedleEnd?: string, + colorValueText?: string, + colorValueTextShadow?: string, + colorBorderShadow?: string, + colorBorderOuter?: string, + colorBorderOuterEnd?: string, + colorBorderMiddle?: string, + colorBorderMiddleEnd?: string, + colorBorderInner?: string, + colorBorderInnerEnd?: string, + colorValueBoxRect?: string, + colorValueBoxRectEnd?: string, + colorValueBoxBackground?: string, + colorValueBoxShadow?: string, + colorNeedleShadowUp?: string, + colorNeedleShadowDown?: string, + needle?: boolean, + needleShadow?: boolean, + needleType?: string, + needleStart?: number, + needleEnd?: number, + needleWidth?: number, + borderOuterWidth?: number, + borderMiddleWidth?: number, + borderInnerWidth?: number, + borderShadowWidth?: number, + valueBox?: boolean, + valueBoxStroke?: number, + valueText?: string, + valueTextShadow?: boolean, + valueBoxBorderRadius?: number, + highlights?: Highlight[], + fontNumbers?: string, + fontTitle?: string, + fontUnits?: string, + fontValue?: string, + fontTitleSize?: number, + fontValueSize?: number, + fontUnitsSize?: number, + fontNumbersSize?: number + } + + export interface RadialGaugeOptions extends GenericOptions { + ticksAngle?: number, + startAngle?: number, + colorNeedleCircleOuter?: string, + colorNeedleCircleOuterEnd?: string, + colorNeedleCircleInner?: string, + colorNeedleCircleInnerEnd?: string, + needleCircleSize?: number, + needleCircleInner?: boolean, + needleCircleOuter?: boolean, + animationTarget?: string + } + + export interface LinearGaugeOptions extends GenericOptions { + borderRadius?: number, + barBeginCircle?: number, + barWidth?: number, + barStrokeWidth?: number, + barProgress?: boolean, + colorBar?: string, + colorBarEnd?: string, + colorBarStroke?: string, + colorBarProgress?: string, + colorBarProgressEnd?: string, + tickSide?: string, + needleSide?: string, + numberSide?: string, + ticksWidth?: number, + ticksWidthMinor?: number, + ticksPadding?: number, + barLength?: number + } + + export interface DrawEventCallback { + (percent: number): any; + } + + export interface EndEventCallback { + (): any; + } + + export interface rules { + linear: AnimationRule, + quad: AnimationRule, + dequad: AnimationRule, + quint: AnimationRule, + dequint: AnimationRule, + cycle: AnimationRule, + decycle: AnimationRule, + bounce: AnimationRule, + debounce: AnimationRule, + elastic: AnimationRule, + delastic: AnimationRule + } + + export class Animation { + public duration: number; + public rule: string|AnimationRule; + public draw: DrawEventCallback; + public end: EndEventCallback; + + public static rules: rules; + + constructor(rule?: string|AnimationRule, duration?: number, + draw?: DrawEventCallback, end?: EndEventCallback); + + public animate(draw?: DrawEventCallback, end?: EndEventCallback): any; + public destroy(): any; + } + + export class SmartCanvas { + public element: HTMLCanvasElement; + public elementClone: HTMLCanvasElement; + public context: CanvasRenderingContext2D; + public contextClone: CanvasRenderingContext2D; + public drawWidth: number; + public drawHeight: number; + public drawX: number; + public drawY: number; + public minSide: number; + public width: number; + public height: number; + + constructor(element: HTMLCanvasElement, + width?: number, + height?: number); + + public init(): any; + public onRedraw(): any; + public destroy(): any; + public commit(): SmartCanvas; + public redraw(): SmartCanvas; + + public pixelRatio: number; + public static redraw(): any; + public static collection: Array; + } + + export class DomObserver { + public Type: BaseGauge; + public mutationsObserved: boolean; + public isObservable: boolean; + public options: GenericOptions; + public element: string; + public type: string; + + constructor(options: GenericOptions, + element: string, + type: string); + + public isValidNode(node: Node|HTMLElement): boolean; + public traverse(): any; + public observe(records: MutationRecord[]): any; + public process(node: Node|HTMLElement): BaseGauge; + + public static parse(value: any): any; + public static toDashed(camelCase: string): string; + public static toAttributeName(str: string): string; + static domReady(handler: Function): any; + } + + export abstract class BaseGauge { + public type: BaseGauge; + public options: GenericOptions; + public canvas: SmartCanvas; + public animation: Animation; + public value: number; + + constructor(options: GenericOptions); + + public update(options: GenericOptions): BaseGauge; + public destroy(): any; + public abstract draw(): BaseGauge; + + public static initialize(type: string, options: GenericOptions): any; + } + + export class RadialGauge extends BaseGauge { + public type: RadialGauge; + public options: RadialGaugeOptions; + + constructor(options: RadialGaugeOptions); + + public draw(): RadialGauge; + } + + export class LinearGauge extends BaseGauge { + public type: LinearGauge; + public options: LinearGaugeOptions; + + constructor(options: LinearGaugeOptions); + + public draw(): LinearGauge; + } + + export interface Collection extends Array { + get: (id: number | string) => BaseGauge; + } +} + +declare module 'canvas-gauges' { + export = CanvasGauges; +} + +interface Document { + gauges: CanvasGauges.Collection; +} + +interface Window { + BaseGauge: CanvasGauges.BaseGauge; + RadialGauge: CanvasGauges.RadialGauge; + LinearGauge: CanvasGauges.LinearGauge; +} diff --git a/chai-things/chai-things-tests.ts b/chai-things/chai-things-tests.ts index de6a4c3ffe..c49ac3b468 100644 --- a/chai-things/chai-things-tests.ts +++ b/chai-things/chai-things-tests.ts @@ -18,9 +18,19 @@ function test_somethingSyntax() { array.should.include.something.with.property('b', 2); array.should.not.include.something.with.property('b', 3); + chai.expect(array).to.include.something(); + chai.expect(array).to.include.something.that.deep.equals({ b: 2 }); + chai.expect(array).to.include.something.that.not.deep.equals({ b: 2 }); + chai.expect(array).not.to.include.something.that.deep.equals({ c: 3 }); + chai.expect(array).to.include.something.that.not.deep.equals({ c: 3 }); + chai.expect(array).to.include.something.with.property('b', 2); + chai.expect(array).not.to.include.something.with.property('b', 3); + var array2 = [{ a: 'b' }, { a: 'b' }]; array2.should.include.something.that.have.property("a"); array2.should.include.something.that.have.property("a").not.equal("d"); + chai.expect(array2).to.include.something.that.have.property("a"); + chai.expect(array2).to.include.something.that.have.property("a").not.equal("d"); } function test_somethingVariantsSyntax() { @@ -35,6 +45,16 @@ function test_somethingVariantsSyntax() { array.should.include.one.that.deep.equals({ b: 2 }); array.should.include.some(); array.should.include.some.that.deep.equal({ b: 2 }); + + chai.expect(array).to.include.a.thing(); + chai.expect(array).to.include.a.thing.that.deep.equals({ b: 2 }); + chai.expect(array).to.include.an.item(); + chai.expect(array).to.include.an.item.that.deep.equals({ b: 2 }); + chai.expect(array).to.include.one.that.deep.equals({ b: 2 }); + chai.expect(array).to.include.some(); + chai.expect(array).to.include.some.that.deep.equal({ b: 2 }); + chai.expect(array).to.contain.a.thing(); + chai.expect(array).to.contain.a.thing.with.property('a', 1); } function test_allSyntax() { diff --git a/chai-things/chai-things.d.ts b/chai-things/chai-things.d.ts index 2636c9dcea..18c138ff38 100644 --- a/chai-things/chai-things.d.ts +++ b/chai-things/chai-things.d.ts @@ -23,6 +23,15 @@ declare namespace Chai { any: Anything; } + interface Include { + (item: any): any; + a: Item; + an: Item; + one: Something; + some: Something; + something: Something; + } + interface Anything extends Assertion { (): any; that: Assertion; diff --git a/chance/chance.d.ts b/chance/chance.d.ts index 290cde8048..6390b57864 100644 --- a/chance/chance.d.ts +++ b/chance/chance.d.ts @@ -114,8 +114,16 @@ declare namespace Chance { capitalize(str: string): string; mixin(desc: MixinDescriptor): any; pad(num: number, width: number, padChar?: string): string; + /** + * @deprecated Use pickone + */ pick(arr: T[]): T; + pickone(arr: T[]): T; + /** + * @deprecated Use pickset + */ pick(arr: T[], count: number): T[]; + pickset(arr: T[], count: number): T[]; set: Setter; shuffle(arr: T[]): T[]; diff --git a/chart.js/chart.js.d.ts b/chart.js/chart.js.d.ts index e05d930d4e..57389ee4ea 100644 --- a/chart.js/chart.js.d.ts +++ b/chart.js/chart.js.d.ts @@ -73,7 +73,7 @@ interface ChartOptions { onClick?: (any?: any) => any; title?: ChartTitleOptions; legend?: ChartLegendOptions; - tooltip?: ChartTooltipOptions; + tooltips?: ChartTooltipOptions; hover?: ChartHoverOptions; animation?: ChartAnimationOptions; elements?: ChartElementsOptions; diff --git a/colors/colors-tests.ts b/colors/colors-tests.ts index 15fd5ab4e5..ff838da995 100644 --- a/colors/colors-tests.ts +++ b/colors/colors-tests.ts @@ -3,9 +3,17 @@ import colors = require("colors"); +colors.enabled = true; + console.log(colors.black.underline('test')); console.log(colors.rainbow.black.blue.gray('test')); console.log(colors.random.reset.bgWhite.dim('test')); +console.log(colors.random.reset.bgWhite.strip('test')); console.log('test'.black.underline); console.log('test'.rainbow.black.blue.gray); console.log('test'.random.reset.bgWhite.dim); +console.log('test'.random.reset.bgWhite.dim.stripColors); + +colors.enabled = false; + +console.log(colors.black.underline('test')); diff --git a/colors/colors.d.ts b/colors/colors.d.ts index 7a78240287..50e960c416 100644 --- a/colors/colors.d.ts +++ b/colors/colors.d.ts @@ -7,6 +7,9 @@ declare module "colors" { interface Color { (text: string): string; + strip: Color; + stripColors: Color; + black: Color; red: Color; green: Color; @@ -47,6 +50,11 @@ declare module "colors" { namespace e { export function setTheme(theme:any): void; + export var enabled: boolean; + + export var strip: Color; + export var stripColors: Color; + export var black: Color; export var red: Color; export var green: Color; @@ -88,6 +96,9 @@ declare module "colors" { } interface String { + strip: string; + stripColors: string; + black: string; red: string; green: string; diff --git a/core-js/core-js.d.ts b/core-js/core-js.d.ts index c633dc4ef6..1ad88ff41a 100644 --- a/core-js/core-js.d.ts +++ b/core-js/core-js.d.ts @@ -1889,7 +1889,7 @@ declare module "core-js/fn/number/max-safe-integer" { var MAX_SAFE_INTEGER: typeof core.Number.MAX_SAFE_INTEGER; export = MAX_SAFE_INTEGER; } -declare module "core-js/fn/number/min-safe-interger" { +declare module "core-js/fn/number/min-safe-integer" { var MIN_SAFE_INTEGER: typeof core.Number.MIN_SAFE_INTEGER; export = MIN_SAFE_INTEGER; } @@ -2668,7 +2668,7 @@ declare module "core-js/library/fn/number/max-safe-integer" { var MAX_SAFE_INTEGER: typeof core.Number.MAX_SAFE_INTEGER; export = MAX_SAFE_INTEGER; } -declare module "core-js/library/fn/number/min-safe-interger" { +declare module "core-js/library/fn/number/min-safe-integer" { var MIN_SAFE_INTEGER: typeof core.Number.MIN_SAFE_INTEGER; export = MIN_SAFE_INTEGER; } diff --git a/couchbase/couchbase.d.ts b/couchbase/couchbase.d.ts index 351c9a806d..2508f0e1d5 100644 --- a/couchbase/couchbase.d.ts +++ b/couchbase/couchbase.d.ts @@ -159,6 +159,14 @@ declare module 'couchbase' { * Creates a manager allowing the management of a Couchbase cluster. */ manager(): ClusterManager; + + + /** + * Creates a manager allowing the management of a Couchbase cluster using credentials. + * @param username The username for your cluster. + * @param password The password for your cluster. + */ + manager(username: string, password: string): ClusterManager; /** * Open a bucket to perform operations. This will begin the handshake process immediately and operations will complete later. Subscribe to the connect event to be alerted when the connection is ready, though be aware operations can be successfully queued before this. diff --git a/cucumber/cucumber-tests.ts b/cucumber/cucumber-tests.ts index d6ada278c2..aa17cd331e 100644 --- a/cucumber/cucumber-tests.ts +++ b/cucumber/cucumber-tests.ts @@ -1,30 +1,32 @@ /// +/// function StepSample() { type Callback = cucumber.CallbackStepDefinition; + type Table = cucumber.TableDefinition; var step = this; var hook = this; - + hook.Before(function(scenario, callback){ scenario.isFailed() && callback.pending(); }) - + hook.Around(function(scenario, runScenario) { scenario.isFailed() && runScenario(null, function(){ console.log('finish tasks'); }); }); - + hook.registerHandler('AfterFeatures', function (event, callback) { callback(); }); - + step.Given(/^I am on the Cucumber.js GitHub repository$/, function(callback:Callback) { this.visit('https://github.com/cucumber/cucumber-js', callback); }); step.When(/^I go to the README file$/, function(title:string, callback:Callback) { - callback.pending(); + callback(null, 'pending'); }); step.Then(/^I should see "(.*)" as the page title$/, { timeout:60*1000}, function(title:string, callback:Callback) { @@ -36,5 +38,43 @@ function StepSample() { callback(new Error("Expected to be on page with title " + title)); } }); + + // Type for data_table.js on + // https://github.com/cucumber/cucumber-js/blob/a5fd8251918c278ab2e389226d165cedb44df14a/lib/cucumber/ast/data_table.js + + step.Given(/^a table step with Table raw$/, function(table:Table){ + var expected = [ + ['Cucumber', 'Cucumis sativus'], + ['Burr Gherkin', 'Cucumis anguria'] + ]; + + assert.deepEqual(table.raw(), expected); + }); + + step.Given(/^a table step with Table rows$/, function(table: Table){ + var expected = [ + ['Apricot', '5'], + ['Brocolli', '2'], + ['Cucumber', '10'] + ]; + assert.deepEqual(table.rows(), expected) + }); + + step.Given(/^a table step with Table rowHash$/, function(table:Table){ + var expected = { + 'Cucumber': 'Cucumis sativus', + 'Burr Gherkin': 'Cucumis anguria' + }; + assert.deepEqual(table.rowsHash(), expected) + }); + + step.Given(/^a table step$/, function(table:Table){ + var expected = [ + {'Vegetable': 'Apricot', 'Rating': '5'}, + {'Vegetable': 'Brocolli', 'Rating': '2'}, + {'Vegetable': 'Cucumber', 'Rating': '10'} + ]; + assert.deepEqual(table.hashes(), expected) + }); } diff --git a/cucumber/cucumber.d.ts b/cucumber/cucumber.d.ts index 6c4273e4e0..a415a478e2 100644 --- a/cucumber/cucumber.d.ts +++ b/cucumber/cucumber.d.ts @@ -7,11 +7,20 @@ declare namespace cucumber { export interface CallbackStepDefinition{ pending : () => PromiseLike; - (errror?:any):void; + (errror?:any, pending?: string):void; } + export interface TableDefinition{ + raw: () => Array; + rows: () => Array; + rowsHash: () => {}; + hashes: () => {}; + } + + type StepDefinitionParam = string | CallbackStepDefinition | TableDefinition; + interface StepDefinitionCode { - (...stepArgs: Array): PromiseLike | any | void; + (...stepArgs: Array): PromiseLike | any | void; } interface StepDefinitionOptions{ diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 3ad327ffc3..d539b7439d 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -297,7 +297,7 @@ declare namespace d3 { * @param value the function to compute data for each node */ datum(value: (datum: Datum, index: number, outerIndex: number) => NewDatum): Update; - + /** * Set the data item for each node in the selection. * @param value the constant element to use for each node @@ -415,7 +415,7 @@ declare namespace d3 { select(name: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; call(func: (selection: Enter, ...args: any[]) => any, ...args: any[]): Enter; - + empty(): boolean; size(): number; } @@ -1078,7 +1078,7 @@ declare namespace d3 { * Return the min and max simultaneously. */ export function extent(array: T[], accessor: (datum: T, index: number) => string): [string, string]; - + /** * Return the min and max simultaneously. */ @@ -2928,6 +2928,8 @@ declare namespace d3 { start(): Force; + tick(): Force; + alpha(): number; alpha(value: number): Force; diff --git a/date-fns/date-fns-tests.ts b/date-fns/date-fns-tests.ts new file mode 100644 index 0000000000..4c1dfc2476 --- /dev/null +++ b/date-fns/date-fns-tests.ts @@ -0,0 +1,16 @@ +/// + +import {addDays, closestIndexTo, differenceInCalendarWeeks, max, isDate} from 'date-fns'; +import * as addHours from 'date-fns/add_hours'; + +function test() { + + addDays(new Date(), 5); + closestIndexTo(new Date(), [new Date(), new Date()]); + addHours(new Date(), 5); + differenceInCalendarWeeks(new Date(), new Date()); + differenceInCalendarWeeks(new Date(), new Date(), {weekStartsOn: 1}); + max(new Date(), new Date()); + isDate({}); + +} \ No newline at end of file diff --git a/date-fns/date-fns.d.ts b/date-fns/date-fns.d.ts new file mode 100644 index 0000000000..d0582c2571 --- /dev/null +++ b/date-fns/date-fns.d.ts @@ -0,0 +1,1195 @@ +// Type definitions for date-fns +// Project: https://date-fns.org/ +// Definitions by: Matt Lewis +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type DateOrStringOrNumber = Date | string | number; + +declare module 'date-fns' { + + function addDays(date: DateOrStringOrNumber, amount: number): Date; + namespace addDays {} + + function addHours(date: DateOrStringOrNumber, amount: number): Date; + namespace addHours {} + + function addISOYears(date: DateOrStringOrNumber, amount: number): Date; + namespace addISOYears {} + + function addMilliseconds(date: DateOrStringOrNumber, amount: number): Date; + namespace addMilliseconds {} + + function addMinutes(date: DateOrStringOrNumber, amount: number): Date; + namespace addMinutes {} + + function addMonths(date: DateOrStringOrNumber, amount: number): Date; + namespace addMonths {} + + function addQuarters(date: DateOrStringOrNumber, amount: number): Date; + namespace addQuarters {} + + function addSeconds(date: DateOrStringOrNumber, amount: number): Date; + namespace addSeconds {} + + function addWeeks(date: DateOrStringOrNumber, amount: number): Date; + namespace addWeeks {} + + function addYears(date: DateOrStringOrNumber, amount: number): Date; + namespace addYears {} + + function closestIndexTo(dateToCompare: DateOrStringOrNumber, datesArray: DateOrStringOrNumber[]): number; + namespace closestIndexTo {} + + function closestTo(dateToCompare: DateOrStringOrNumber, datesArray: DateOrStringOrNumber[]): Date; + namespace closestTo {} + + function compareAsc(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace compareAsc {} + + function compareDesc(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace compareDesc {} + + function differenceInCalendarDays(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarDays {} + + function differenceInCalendarISOWeeks(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarISOWeeks {} + + function differenceInCalendarISOYears(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarISOYears {} + + function differenceInCalendarMonths(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarMonths {} + + function differenceInCalendarQuarters(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarQuarters {} + + function differenceInCalendarWeeks(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber, options?: {weekStartsOn: number}): number; + namespace differenceInCalendarWeeks {} + + function differenceInCalendarYears(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarYears {} + + function differenceInDays(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInDays {} + + function differenceInHours(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInHours {} + + function differenceInISOYears(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInISOYears {} + + function differenceInMilliseconds(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInMilliseconds {} + + function differenceInMinutes(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInMinutes {} + + function differenceInMonths(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInMonths {} + + function differenceInQuarters(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInQuarters {} + + function differenceInSeconds(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInSeconds {} + + function differenceInWeeks(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInWeeks {} + + function differenceInYears(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInYears {} + + function distanceInWords(dateFrom: DateOrStringOrNumber, dateTo: DateOrStringOrNumber, options?: {includeSeconds: boolean}): string; + namespace distanceInWords {} + + function distanceInWordsToNow(date: DateOrStringOrNumber, options?: {includeSeconds: boolean}): string; + namespace distanceInWordsToNow {} + + function eachDay(startDate: DateOrStringOrNumber, endDate: DateOrStringOrNumber): Date[]; + namespace eachDay {} + + function endOfDay(date: DateOrStringOrNumber): Date; + namespace endOfDay {} + + function endOfHour(date: DateOrStringOrNumber): Date; + namespace endOfHour {} + + function endOfISOWeek(date: DateOrStringOrNumber): Date; + namespace endOfISOWeek {} + + function endOfISOYear(date: DateOrStringOrNumber): Date; + namespace endOfISOYear {} + + function endOfMinute(date: DateOrStringOrNumber): Date; + namespace endOfMinute {} + + function endOfMonth(date: DateOrStringOrNumber): Date; + namespace endOfMonth {} + + function endOfQuarter(date: DateOrStringOrNumber): Date; + namespace endOfQuarter {} + + function endOfSecond(date: DateOrStringOrNumber): Date; + namespace endOfSecond {} + + function endOfToday(): Date; + namespace endOfToday {} + + function endOfTomorrow(): Date; + namespace endOfTomorrow {} + + function endOfWeek(date: DateOrStringOrNumber, options?: {weekStartsOn: number}): Date; + namespace endOfWeek {} + + function endOfYear(date: DateOrStringOrNumber): Date; + namespace endOfYear {} + + function endOfYesterday(): Date; + namespace endOfYesterday {} + + function format(date: DateOrStringOrNumber, format?: string): string; + namespace format {} + + function getDate(date: DateOrStringOrNumber): number; + namespace getDate {} + + function getDay(date: DateOrStringOrNumber): number; + namespace getDay {} + + function getDayOfYear(date: DateOrStringOrNumber): number; + namespace getDayOfYear {} + + function getDaysInMonth(date: DateOrStringOrNumber): number; + namespace getDaysInMonth {} + + function getDaysInYear(date: DateOrStringOrNumber): number; + namespace getDaysInYear {} + + function getHours(date: DateOrStringOrNumber): number; + namespace getHours {} + + function getISOWeek(date: DateOrStringOrNumber): number; + namespace getISOWeek {} + + function getISOWeeksInYear(date: DateOrStringOrNumber): number; + namespace getISOWeeksInYear {} + + function getISOYear(date: DateOrStringOrNumber): number; + namespace getISOYear {} + + function getMilliseconds(date: DateOrStringOrNumber): number; + namespace getMilliseconds {} + + function getMinutes(date: DateOrStringOrNumber): number; + namespace getMinutes {} + + function getMonth(date: DateOrStringOrNumber): number; + namespace getMonth {} + + function getQuarter(date: DateOrStringOrNumber): number; + namespace getQuarter {} + + function getSeconds(date: DateOrStringOrNumber): number; + namespace getSeconds {} + + function getYear(date: DateOrStringOrNumber): number; + namespace getYear {} + + function isAfter(dateToCompare: DateOrStringOrNumber, date: DateOrStringOrNumber): boolean; + namespace isAfter {} + + function isBefore(dateToCompare: DateOrStringOrNumber, date: DateOrStringOrNumber): boolean; + namespace isBefore {} + + function isDate(argument: any): boolean; + namespace isDate {} + + function isEqual(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isEqual {} + + function isFirstDayOfMonth(date: DateOrStringOrNumber): boolean; + namespace isFirstDayOfMonth {} + + function isFriday(date: DateOrStringOrNumber): boolean; + namespace isFriday {} + + function isFuture(date: DateOrStringOrNumber): boolean; + namespace isFuture {} + + function isLastDayOfMonth(date: DateOrStringOrNumber): boolean; + namespace isLastDayOfMonth {} + + function isLeapYear(date: DateOrStringOrNumber): boolean; + namespace isLeapYear {} + + function isMonday(date: DateOrStringOrNumber): boolean; + namespace isMonday {} + + function isPast(date: DateOrStringOrNumber): boolean; + namespace isPast {} + + function isSameDay(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameDay {} + + function isSameHour(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameHour {} + + function isSameISOWeek(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameISOWeek {} + + function isSameISOYear(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameISOYear {} + + function isSameMinute(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameMinute {} + + function isSameMonth(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameMonth {} + + function isSameQuarter(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameQuarter {} + + function isSameSecond(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameSecond {} + + function isSameWeek(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber, options?: {weekStartsOn: number}): boolean; + namespace isSameWeek {} + + function isSameYear(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameYear {} + + function isSaturday(date: DateOrStringOrNumber): boolean; + namespace isSaturday {} + + function isSunday(date: DateOrStringOrNumber): boolean; + namespace isSunday {} + + function isThisHour(date: DateOrStringOrNumber): boolean; + namespace isThisHour {} + + function isThisISOWeek(date: DateOrStringOrNumber): boolean; + namespace isThisISOWeek {} + + function isThisISOYear(date: DateOrStringOrNumber): boolean; + namespace isThisISOYear {} + + function isThisMinute(date: DateOrStringOrNumber): boolean; + namespace isThisMinute {} + + function isThisMonth(date: DateOrStringOrNumber): boolean; + namespace isThisMonth {} + + function isThisQuarter(date: DateOrStringOrNumber): boolean; + namespace isThisQuarter {} + + function isThisSecond(date: DateOrStringOrNumber): boolean; + namespace isThisSecond {} + + function isThisWeek(date: DateOrStringOrNumber, options?: {weekStartsOn: number}): boolean; + namespace isThisWeek {} + + function isThisYear(date: DateOrStringOrNumber): boolean; + namespace isThisYear {} + + function isThursday(date: DateOrStringOrNumber): boolean; + namespace isThursday {} + + function isToday(date: DateOrStringOrNumber): boolean; + namespace isToday {} + + function isTomorrow(date: DateOrStringOrNumber): boolean; + namespace isTomorrow {} + + function isTuesday(date: DateOrStringOrNumber): boolean; + namespace isTuesday {} + + function isValid(date: DateOrStringOrNumber): boolean; + namespace isValid {} + + function isWednesday(date: DateOrStringOrNumber): boolean; + namespace isWednesday {} + + function isWeekend(date: DateOrStringOrNumber): boolean; + namespace isWeekend {} + + function isWithinRange(date: DateOrStringOrNumber, startDate: DateOrStringOrNumber, endDate: DateOrStringOrNumber): boolean; + namespace isWithinRange {} + + function isYesterday(date: DateOrStringOrNumber): boolean; + namespace isYesterday {} + + function lastDayOfISOWeek(date: DateOrStringOrNumber): Date; + namespace lastDayOfISOWeek {} + + function lastDayOfISOYear(date: DateOrStringOrNumber): Date; + namespace lastDayOfISOYear {} + + function lastDayOfMonth(date: DateOrStringOrNumber): Date; + namespace lastDayOfMonth {} + + function lastDayOfQuarter(date: DateOrStringOrNumber): Date; + namespace lastDayOfQuarter {} + + function lastDayOfWeek(date: DateOrStringOrNumber, options?: {weekStartsOn: number}): Date; + namespace lastDayOfWeek {} + + function lastDayOfYear(date: DateOrStringOrNumber): Date; + namespace lastDayOfYear {} + + function max(...dates: DateOrStringOrNumber[]): Date; + namespace max {} + + function min(...dates: DateOrStringOrNumber[]): Date; + namespace min {} + + function parse(dateString: string): Date; + namespace parse {} + + function setDate(date: DateOrStringOrNumber, dayOfMonth: number): Date; + namespace setDate {} + + function setDay(date: DateOrStringOrNumber, day: number, options?: {weekStartsOn: number}): Date; + namespace setDay {} + + function setDayOfYear(date: DateOrStringOrNumber, dayOfYear: number): Date; + namespace setDayOfYear {} + + function setHours(date: DateOrStringOrNumber, hours: number): Date; + namespace setHours {} + + function setISOWeek(date: DateOrStringOrNumber, isoWeek: number): Date; + namespace setISOWeek {} + + function setISOYear(date: DateOrStringOrNumber, isoYear: number): Date; + namespace setISOYear {} + + function setMilliseconds(date: DateOrStringOrNumber, milliseconds: number): Date; + namespace setMilliseconds {} + + function setMinutes(date: DateOrStringOrNumber, minutes: number): Date; + namespace setMinutes {} + + function setMonth(date: DateOrStringOrNumber, month: number): Date; + namespace setMonth {} + + function setQuarter(date: DateOrStringOrNumber, quarter: number): Date; + namespace setQuarter {} + + function setSeconds(date: DateOrStringOrNumber, seconds: number): Date; + namespace setSeconds {} + + function setYear(date: DateOrStringOrNumber, year: number): Date; + namespace setYear {} + + function startOfDay(date: DateOrStringOrNumber): Date; + namespace startOfDay {} + + function startOfHour(date: DateOrStringOrNumber): Date; + namespace startOfHour {} + + function startOfISOWeek(date: DateOrStringOrNumber): Date; + namespace startOfISOWeek {} + + function startOfISOYear(date: DateOrStringOrNumber): Date; + namespace startOfISOYear {} + + function startOfMinute(date: DateOrStringOrNumber): Date; + namespace startOfMinute {} + + function startOfMonth(date: DateOrStringOrNumber): Date; + namespace startOfMonth {} + + function startOfQuarter(date: DateOrStringOrNumber): Date; + namespace startOfQuarter {} + + function startOfSecond(date: DateOrStringOrNumber): Date; + namespace startOfSecond {} + + function startOfToday(): Date; + namespace startOfToday {} + + function startOfTomorrow(): Date; + namespace startOfTomorrow {} + + function startOfWeek(date: DateOrStringOrNumber, options?: {weekStartsOn: number}): Date; + namespace startOfWeek {} + + function startOfYear(date: DateOrStringOrNumber): Date; + namespace startOfYear {} + + function startOfYesterday(): Date; + namespace startOfYesterday {} + + function subDays(date: DateOrStringOrNumber, amount: number): Date; + namespace subDays {} + + function subHours(date: DateOrStringOrNumber, amount: number): Date; + namespace subHours {} + + function subISOYears(date: DateOrStringOrNumber, amount: number): Date; + namespace subISOYears {} + + function subMilliseconds(date: DateOrStringOrNumber, amount: number): Date; + namespace subMilliseconds {} + + function subMinutes(date: DateOrStringOrNumber, amount: number): Date; + namespace subMinutes {} + + function subMonths(date: DateOrStringOrNumber, amount: number): Date; + namespace subMonths {} + + function subQuarters(date: DateOrStringOrNumber, amount: number): Date; + namespace subQuarters {} + + function subSeconds(date: DateOrStringOrNumber, amount: number): Date; + namespace subSeconds {} + + function subWeeks(date: DateOrStringOrNumber, amount: number): Date; + namespace subWeeks {} + + function subYears(date: DateOrStringOrNumber, amount: number): Date; + namespace subYears {} + +} + +declare module 'date-fns/add_days' { + import {addDays} from 'date-fns'; + export = addDays; +} + +declare module 'date-fns/add_hours' { + import {addHours} from 'date-fns'; + export = addHours; +} + +declare module 'date-fns/add_iso_years' { + import {addISOYears} from 'date-fns'; + export = addISOYears; +} + +declare module 'date-fns/add_milliseconds' { + import {addMilliseconds} from 'date-fns'; + export = addMilliseconds; +} + +declare module 'date-fns/add_minutes' { + import {addMinutes} from 'date-fns'; + export = addMinutes; +} + +declare module 'date-fns/add_months' { + import {addMonths} from 'date-fns'; + export = addMonths; +} + +declare module 'date-fns/add_quarters' { + import {addQuarters} from 'date-fns'; + export = addQuarters; +} + +declare module 'date-fns/add_seconds' { + import {addSeconds} from 'date-fns'; + export = addSeconds; +} + +declare module 'date-fns/add_weeks' { + import {addWeeks} from 'date-fns'; + export = addWeeks; +} + +declare module 'date-fns/add_years' { + import {addYears} from 'date-fns'; + export = addYears; +} + +declare module 'date-fns/closest_index_to' { + import {closestIndexTo} from 'date-fns'; + export = closestIndexTo; +} + +declare module 'date-fns/closest_to' { + import {closestTo} from 'date-fns'; + export = closestTo; +} + +declare module 'date-fns/compare_asc' { + import {compareAsc} from 'date-fns'; + export = compareAsc; +} + +declare module 'date-fns/compare_desc' { + import {compareDesc} from 'date-fns'; + export = compareDesc; +} + +declare module 'date-fns/difference_in_calendar_days' { + import {differenceInCalendarDays} from 'date-fns'; + export = differenceInCalendarDays; +} + +declare module 'date-fns/difference_in_calendar_iso_weeks' { + import {differenceInCalendarISOWeeks} from 'date-fns'; + export = differenceInCalendarISOWeeks; +} + +declare module 'date-fns/difference_in_calendar_iso_years' { + import {differenceInCalendarISOYears} from 'date-fns'; + export = differenceInCalendarISOYears; +} + +declare module 'date-fns/difference_in_calendar_months' { + import {differenceInCalendarMonths} from 'date-fns'; + export = differenceInCalendarMonths; +} + +declare module 'date-fns/difference_in_calendar_quarters' { + import {differenceInCalendarQuarters} from 'date-fns'; + export = differenceInCalendarQuarters; +} + +declare module 'date-fns/difference_in_calendar_weeks' { + import {differenceInCalendarWeeks} from 'date-fns'; + export = differenceInCalendarWeeks; +} + +declare module 'date-fns/difference_in_calendar_years' { + import {differenceInCalendarYears} from 'date-fns'; + export = differenceInCalendarYears; +} + +declare module 'date-fns/difference_in_days' { + import {differenceInDays} from 'date-fns'; + export = differenceInDays; +} + +declare module 'date-fns/difference_in_hours' { + import {differenceInHours} from 'date-fns'; + export = differenceInHours; +} + +declare module 'date-fns/difference_in_iso_years' { + import {differenceInISOYears} from 'date-fns'; + export = differenceInISOYears; +} + +declare module 'date-fns/difference_in_milliseconds' { + import {differenceInMilliseconds} from 'date-fns'; + export = differenceInMilliseconds; +} + +declare module 'date-fns/difference_in_minutes' { + import {differenceInMinutes} from 'date-fns'; + export = differenceInMinutes; +} + +declare module 'date-fns/difference_in_months' { + import {differenceInMonths} from 'date-fns'; + export = differenceInMonths; +} + +declare module 'date-fns/difference_in_quarters' { + import {differenceInQuarters} from 'date-fns'; + export = differenceInQuarters; +} + +declare module 'date-fns/difference_in_seconds' { + import {differenceInSeconds} from 'date-fns'; + export = differenceInSeconds; +} + +declare module 'date-fns/difference_in_weeks' { + import {differenceInWeeks} from 'date-fns'; + export = differenceInWeeks; +} + +declare module 'date-fns/difference_in_years' { + import {differenceInYears} from 'date-fns'; + export = differenceInYears; +} + +declare module 'date-fns/distance_in_words' { + import {distanceInWords} from 'date-fns'; + export = distanceInWords; +} + +declare module 'date-fns/distance_in_words_to_now' { + import {distanceInWordsToNow} from 'date-fns'; + export = distanceInWordsToNow; +} + +declare module 'date-fns/each_day' { + import {eachDay} from 'date-fns'; + export = eachDay; +} + +declare module 'date-fns/end_of_day' { + import {endOfDay} from 'date-fns'; + export = endOfDay; +} + +declare module 'date-fns/end_of_hour' { + import {endOfHour} from 'date-fns'; + export = endOfHour; +} + +declare module 'date-fns/end_of_iso_week' { + import {endOfISOWeek} from 'date-fns'; + export = endOfISOWeek; +} + +declare module 'date-fns/end_of_iso_year' { + import {endOfISOYear} from 'date-fns'; + export = endOfISOYear; +} + +declare module 'date-fns/end_of_minute' { + import {endOfMinute} from 'date-fns'; + export = endOfMinute; +} + +declare module 'date-fns/end_of_month' { + import {endOfMonth} from 'date-fns'; + export = endOfMonth; +} + +declare module 'date-fns/end_of_quarter' { + import {endOfQuarter} from 'date-fns'; + export = endOfQuarter; +} + +declare module 'date-fns/end_of_second' { + import {endOfSecond} from 'date-fns'; + export = endOfSecond; +} + +declare module 'date-fns/end_of_today' { + import {endOfToday} from 'date-fns'; + export = endOfToday; +} + +declare module 'date-fns/end_of_tomorrow' { + import {endOfTomorrow} from 'date-fns'; + export = endOfTomorrow; +} + +declare module 'date-fns/end_of_week' { + import {endOfWeek} from 'date-fns'; + export = endOfWeek; +} + +declare module 'date-fns/end_of_year' { + import {endOfYear} from 'date-fns'; + export = endOfYear; +} + +declare module 'date-fns/end_of_yesterday' { + import {endOfYesterday} from 'date-fns'; + export = endOfYesterday; +} + +declare module 'date-fns/format' { + import {format} from 'date-fns'; + export = format; +} + +declare module 'date-fns/get_date' { + import {getDate} from 'date-fns'; + export = getDate; +} + +declare module 'date-fns/get_day' { + import {getDay} from 'date-fns'; + export = getDay; +} + +declare module 'date-fns/get_day_of_year' { + import {getDayOfYear} from 'date-fns'; + export = getDayOfYear; +} + +declare module 'date-fns/get_days_in_month' { + import {getDaysInMonth} from 'date-fns'; + export = getDaysInMonth; +} + +declare module 'date-fns/get_days_in_year' { + import {getDaysInYear} from 'date-fns'; + export = getDaysInYear; +} + +declare module 'date-fns/get_hours' { + import {getHours} from 'date-fns'; + export = getHours; +} + +declare module 'date-fns/get_iso_week' { + import {getISOWeek} from 'date-fns'; + export = getISOWeek; +} + +declare module 'date-fns/get_iso_weeks_in_year' { + import {getISOWeeksInYear} from 'date-fns'; + export = getISOWeeksInYear; +} + +declare module 'date-fns/get_iso_year' { + import {getISOYear} from 'date-fns'; + export = getISOYear; +} + +declare module 'date-fns/get_milliseconds' { + import {getMilliseconds} from 'date-fns'; + export = getMilliseconds; +} + +declare module 'date-fns/get_minutes' { + import {getMinutes} from 'date-fns'; + export = getMinutes; +} + +declare module 'date-fns/get_month' { + import {getMonth} from 'date-fns'; + export = getMonth; +} + +declare module 'date-fns/get_quarter' { + import {getQuarter} from 'date-fns'; + export = getQuarter; +} + +declare module 'date-fns/get_seconds' { + import {getSeconds} from 'date-fns'; + export = getSeconds; +} + +declare module 'date-fns/get_year' { + import {getYear} from 'date-fns'; + export = getYear; +} + +declare module 'date-fns/is_after' { + import {isAfter} from 'date-fns'; + export = isAfter; +} + +declare module 'date-fns/is_before' { + import {isBefore} from 'date-fns'; + export = isBefore; +} + +declare module 'date-fns/is_date' { + import {isDate} from 'date-fns'; + export = isDate; +} + +declare module 'date-fns/is_equal' { + import {isEqual} from 'date-fns'; + export = isEqual; +} + +declare module 'date-fns/is_first_day_of_month' { + import {isFirstDayOfMonth} from 'date-fns'; + export = isFirstDayOfMonth; +} + +declare module 'date-fns/is_friday' { + import {isFriday} from 'date-fns'; + export = isFriday; +} + +declare module 'date-fns/is_future' { + import {isFuture} from 'date-fns'; + export = isFuture; +} + +declare module 'date-fns/is_last_day_of_month' { + import {isLastDayOfMonth} from 'date-fns'; + export = isLastDayOfMonth; +} + +declare module 'date-fns/is_leap_year' { + import {isLeapYear} from 'date-fns'; + export = isLeapYear; +} + +declare module 'date-fns/is_monday' { + import {isMonday} from 'date-fns'; + export = isMonday; +} + +declare module 'date-fns/is_past' { + import {isPast} from 'date-fns'; + export = isPast; +} + +declare module 'date-fns/is_same_day' { + import {isSameDay} from 'date-fns'; + export = isSameDay; +} + +declare module 'date-fns/is_same_hour' { + import {isSameHour} from 'date-fns'; + export = isSameHour; +} + +declare module 'date-fns/is_same_iso_week' { + import {isSameISOWeek} from 'date-fns'; + export = isSameISOWeek; +} + +declare module 'date-fns/is_same_iso_year' { + import {isSameISOYear} from 'date-fns'; + export = isSameISOYear; +} + +declare module 'date-fns/is_same_minute' { + import {isSameMinute} from 'date-fns'; + export = isSameMinute; +} + +declare module 'date-fns/is_same_month' { + import {isSameMonth} from 'date-fns'; + export = isSameMonth; +} + +declare module 'date-fns/is_same_quarter' { + import {isSameQuarter} from 'date-fns'; + export = isSameQuarter; +} + +declare module 'date-fns/is_same_second' { + import {isSameSecond} from 'date-fns'; + export = isSameSecond; +} + +declare module 'date-fns/is_same_week' { + import {isSameWeek} from 'date-fns'; + export = isSameWeek; +} + +declare module 'date-fns/is_same_year' { + import {isSameYear} from 'date-fns'; + export = isSameYear; +} + +declare module 'date-fns/is_saturday' { + import {isSaturday} from 'date-fns'; + export = isSaturday; +} + +declare module 'date-fns/is_sunday' { + import {isSunday} from 'date-fns'; + export = isSunday; +} + +declare module 'date-fns/is_this_hour' { + import {isThisHour} from 'date-fns'; + export = isThisHour; +} + +declare module 'date-fns/is_this_iso_week' { + import {isThisISOWeek} from 'date-fns'; + export = isThisISOWeek; +} + +declare module 'date-fns/is_this_iso_year' { + import {isThisISOYear} from 'date-fns'; + export = isThisISOYear; +} + +declare module 'date-fns/is_this_minute' { + import {isThisMinute} from 'date-fns'; + export = isThisMinute; +} + +declare module 'date-fns/is_this_month' { + import {isThisMonth} from 'date-fns'; + export = isThisMonth; +} + +declare module 'date-fns/is_this_quarter' { + import {isThisQuarter} from 'date-fns'; + export = isThisQuarter; +} + +declare module 'date-fns/is_this_second' { + import {isThisSecond} from 'date-fns'; + export = isThisSecond; +} + +declare module 'date-fns/is_this_week' { + import {isThisWeek} from 'date-fns'; + export = isThisWeek; +} + +declare module 'date-fns/is_this_year' { + import {isThisYear} from 'date-fns'; + export = isThisYear; +} + +declare module 'date-fns/is_thursday' { + import {isThursday} from 'date-fns'; + export = isThursday; +} + +declare module 'date-fns/is_today' { + import {isToday} from 'date-fns'; + export = isToday; +} + +declare module 'date-fns/is_tomorrow' { + import {isTomorrow} from 'date-fns'; + export = isTomorrow; +} + +declare module 'date-fns/is_tuesday' { + import {isTuesday} from 'date-fns'; + export = isTuesday; +} + +declare module 'date-fns/is_valid' { + import {isValid} from 'date-fns'; + export = isValid; +} + +declare module 'date-fns/is_wednesday' { + import {isWednesday} from 'date-fns'; + export = isWednesday; +} + +declare module 'date-fns/is_weekend' { + import {isWeekend} from 'date-fns'; + export = isWeekend; +} + +declare module 'date-fns/is_within_range' { + import {isWithinRange} from 'date-fns'; + export = isWithinRange; +} + +declare module 'date-fns/is_yesterday' { + import {isYesterday} from 'date-fns'; + export = isYesterday; +} + +declare module 'date-fns/last_day_of_iso_week' { + import {lastDayOfISOWeek} from 'date-fns'; + export = lastDayOfISOWeek; +} + +declare module 'date-fns/last_day_of_iso_year' { + import {lastDayOfISOYear} from 'date-fns'; + export = lastDayOfISOYear; +} + +declare module 'date-fns/last_day_of_month' { + import {lastDayOfMonth} from 'date-fns'; + export = lastDayOfMonth; +} + +declare module 'date-fns/last_day_of_quarter' { + import {lastDayOfQuarter} from 'date-fns'; + export = lastDayOfQuarter; +} + +declare module 'date-fns/last_day_of_week' { + import {lastDayOfWeek} from 'date-fns'; + export = lastDayOfWeek; +} + +declare module 'date-fns/last_day_of_year' { + import {lastDayOfYear} from 'date-fns'; + export = lastDayOfYear; +} + +declare module 'date-fns/max' { + import {max} from 'date-fns'; + export = max; +} + +declare module 'date-fns/min' { + import {min} from 'date-fns'; + export = min; +} + +declare module 'date-fns/parse' { + import {parse} from 'date-fns'; + export = parse; +} + +declare module 'date-fns/set_date' { + import {setDate} from 'date-fns'; + export = setDate; +} + +declare module 'date-fns/set_day' { + import {setDay} from 'date-fns'; + export = setDay; +} + +declare module 'date-fns/set_day_of_year' { + import {setDayOfYear} from 'date-fns'; + export = setDayOfYear; +} + +declare module 'date-fns/set_hours' { + import {setHours} from 'date-fns'; + export = setHours; +} + +declare module 'date-fns/set_iso_week' { + import {setISOWeek} from 'date-fns'; + export = setISOWeek; +} + +declare module 'date-fns/set_iso_year' { + import {setISOYear} from 'date-fns'; + export = setISOYear; +} + +declare module 'date-fns/set_milliseconds' { + import {setMilliseconds} from 'date-fns'; + export = setMilliseconds; +} + +declare module 'date-fns/set_minutes' { + import {setMinutes} from 'date-fns'; + export = setMinutes; +} + +declare module 'date-fns/set_month' { + import {setMonth} from 'date-fns'; + export = setMonth; +} + +declare module 'date-fns/set_quarter' { + import {setQuarter} from 'date-fns'; + export = setQuarter; +} + +declare module 'date-fns/set_seconds' { + import {setSeconds} from 'date-fns'; + export = setSeconds; +} + +declare module 'date-fns/set_year' { + import {setYear} from 'date-fns'; + export = setYear; +} + +declare module 'date-fns/start_of_day' { + import {startOfDay} from 'date-fns'; + export = startOfDay; +} + +declare module 'date-fns/start_of_hour' { + import {startOfHour} from 'date-fns'; + export = startOfHour; +} + +declare module 'date-fns/start_of_iso_week' { + import {startOfISOWeek} from 'date-fns'; + export = startOfISOWeek; +} + +declare module 'date-fns/start_of_iso_year' { + import {startOfISOYear} from 'date-fns'; + export = startOfISOYear; +} + +declare module 'date-fns/start_of_minute' { + import {startOfMinute} from 'date-fns'; + export = startOfMinute; +} + +declare module 'date-fns/start_of_month' { + import {startOfMonth} from 'date-fns'; + export = startOfMonth; +} + +declare module 'date-fns/start_of_quarter' { + import {startOfQuarter} from 'date-fns'; + export = startOfQuarter; +} + +declare module 'date-fns/start_of_second' { + import {startOfSecond} from 'date-fns'; + export = startOfSecond; +} + +declare module 'date-fns/start_of_today' { + import {startOfToday} from 'date-fns'; + export = startOfToday; +} + +declare module 'date-fns/start_of_tomorrow' { + import {startOfTomorrow} from 'date-fns'; + export = startOfTomorrow; +} + +declare module 'date-fns/start_of_week' { + import {startOfWeek} from 'date-fns'; + export = startOfWeek; +} + +declare module 'date-fns/start_of_year' { + import {startOfYear} from 'date-fns'; + export = startOfYear; +} + +declare module 'date-fns/start_of_yesterday' { + import {startOfYesterday} from 'date-fns'; + export = startOfYesterday; +} + +declare module 'date-fns/sub_days' { + import {subDays} from 'date-fns'; + export = subDays; +} + +declare module 'date-fns/sub_hours' { + import {subHours} from 'date-fns'; + export = subHours; +} + +declare module 'date-fns/sub_iso_years' { + import {subISOYears} from 'date-fns'; + export = subISOYears; +} + +declare module 'date-fns/sub_milliseconds' { + import {subMilliseconds} from 'date-fns'; + export = subMilliseconds; +} + +declare module 'date-fns/sub_minutes' { + import {subMinutes} from 'date-fns'; + export = subMinutes; +} + +declare module 'date-fns/sub_months' { + import {subMonths} from 'date-fns'; + export = subMonths; +} + +declare module 'date-fns/sub_quarters' { + import {subQuarters} from 'date-fns'; + export = subQuarters; +} + +declare module 'date-fns/sub_seconds' { + import {subSeconds} from 'date-fns'; + export = subSeconds; +} + +declare module 'date-fns/sub_weeks' { + import {subWeeks} from 'date-fns'; + export = subWeeks; +} + +declare module 'date-fns/sub_years' { + import {subYears} from 'date-fns'; + export = subYears; +} + diff --git a/dojo/dojo.d.ts b/dojo/dojo.d.ts index bca5721240..eaab995a36 100644 --- a/dojo/dojo.d.ts +++ b/dojo/dojo.d.ts @@ -5686,7 +5686,23 @@ declare namespace dojo { * @param dest The object to which to copy/add all properties contained in source. If dest is falsy, thena new object is manufactured before copying/adding properties begins. * @param sources One of more objects from which to draw all properties to copy into dest. sources are processedleft-to-right and if more than one of these objects contain the same property name, the right-mostvalue "wins". */ - mixin(dest: Object, source: Object, sources?: Object[]): Object; + mixin(dest: T): T; + mixin( + dest: T, + source: U + ): T & U; + mixin( + dest: T, + source1: U, + source2: V + ): T & U & V; + mixin( + dest: T, + source1: U, + source2: V, + source3: W + ): T & U & V & W; + mixin(dest: Object, ...sources: Object[]): T; /** * similar to hitch() except that the scope object is left to be * whatever the execution context eventually becomes. diff --git a/dva/dva-tests.tsx b/dva/dva-tests.tsx new file mode 100644 index 0000000000..917ee69e60 --- /dev/null +++ b/dva/dva-tests.tsx @@ -0,0 +1,48 @@ +/// +/// + +import React = __React; + +import dva from 'dva'; +import { connect } from 'dva'; +import { Router, Route } from 'dva/router'; + +// 1. Initialize +const app = dva(); + +// 2. Model +app.model({ + namespace: 'count', + state: 0, + reducers: { + add(count: number) { + return count + 1 + }, + minus(count: number) { + return count - 1 + }, + }, +}); + +// 3. View +const App = connect(({ count }) => ({ + count +}))(function ({ count, dispatch }) { + return ( +
+

{ count }

+ + +
+ ); +}); + +// 4. Router +app.router(({ history }) => + + + +); + +// 5. Start +const countApp = app.start(); diff --git a/dva/dva.d.ts b/dva/dva.d.ts new file mode 100644 index 0000000000..0cf7206e63 --- /dev/null +++ b/dva/dva.d.ts @@ -0,0 +1,61 @@ +// Type definitions for dva v1.0.0 +// Project: https://github.com/dvajs/dva +// Definitions by: nikogu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +declare module 'dva' { + /** connecting Container Components */ + export function connect(maps:Object):Function; + + export default function dva(opts?:Object):{ + + /** dva plugin */ + use: (hooks:Object)=>void, + + /** dva bootstrap */ + start: (selector?:String|HTMLElement)=>void, + + /** dva add model */ + model: (model:Object)=>void, + + /** dva setting router */ + router: (router:Object)=>Object|JSX.Element, + }; +} + +/** + * https://github.com/reactjs/react-router + */ +declare module 'dva/router' { + import React = __React; + + interface RouterProps { + history?: Object + } + export class Router extends React.Component { + render():JSX.Element + } + + + interface RouteProps { + path?: string, + component?: React.ReactNode + } + export class Route extends React.Component { + render():JSX.Element + } + + /** + * https://github.com/reactjs/react-router-redux + */ + export class routerRedux {} + +} + +/** + * https://github.com/fis-components/whatwg-fetch + */ +declare module 'dva/fetch' { + export default Function; +} diff --git a/elastic.js/elastic.js.d.ts b/elastic.js/elastic.js.d.ts index 850d1ccdfa..9bf5f6a9dc 100644 --- a/elastic.js/elastic.js.d.ts +++ b/elastic.js/elastic.js.d.ts @@ -19,7 +19,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -40,7 +40,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -58,7 +58,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -107,7 +107,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the field to operate on. @@ -139,7 +139,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -161,7 +161,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -226,7 +226,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets if the Query should be enhanced with a @@ -278,7 +278,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -298,7 +298,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost factor. @@ -314,7 +314,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -335,7 +335,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -362,7 +362,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -382,7 +382,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the field to operate on. @@ -425,7 +425,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -454,7 +454,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the analyzer name used to analyze the Query object. @@ -522,7 +522,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -536,7 +536,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets analyzer used to analyze the suggest text. @@ -593,7 +593,7 @@ declare module elasticjs { Retrieves the internal suggest object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets if transpositions should be counted as one or two changes, defaults @@ -635,7 +635,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -666,7 +666,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -693,7 +693,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -805,7 +805,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -839,7 +839,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enables caching of the facetFilter @@ -986,7 +986,7 @@ declare module elasticjs { Retrieves the internal facet object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Allows you to specify a different value field to aggrerate over. @@ -1023,7 +1023,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -1086,7 +1086,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1110,7 +1110,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the decay value which defines how documents are scored at the distance @@ -1165,7 +1165,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1185,7 +1185,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the accuracy. How similar the suggested terms at least @@ -1285,7 +1285,7 @@ declare module elasticjs { Retrieves the internal generator object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1389,7 +1389,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -1419,7 +1419,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1438,7 +1438,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -1489,7 +1489,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the field to operate on. @@ -1521,7 +1521,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1531,7 +1531,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enables caching of the facetFilter @@ -1573,7 +1573,7 @@ declare module elasticjs { Retrieves the internal facet object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1595,7 +1595,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -1616,7 +1616,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1636,7 +1636,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -1662,7 +1662,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1684,7 +1684,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -1734,7 +1734,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1766,7 +1766,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enables caching of the facetFilter @@ -1813,7 +1813,7 @@ declare module elasticjs { Retrieves the internal facet object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1823,7 +1823,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -1864,7 +1864,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -1908,7 +1908,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1946,7 +1946,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* The analyzer that will be used to analyze the text. Defaults to the @@ -2000,7 +2000,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -2035,7 +2035,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* The analyzer that will be used to analyze the text. Defaults to the @@ -2091,7 +2091,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -2116,7 +2116,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value of the Query. @@ -2179,7 +2179,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Set to false to use classic Levenshtein edit distance. @@ -2208,7 +2208,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the bottom-right coordinate of the bounding box @@ -2284,7 +2284,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -2344,7 +2344,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the distance unit. Valid values are: @@ -2383,7 +2383,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Adds a new bounded range. @@ -2479,7 +2479,7 @@ declare module elasticjs { Retrieves the internal facet object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the distance unit. Valid values are "mi" for miles or "km" @@ -2515,7 +2515,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -2601,7 +2601,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -2728,7 +2728,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -2771,7 +2771,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -2792,7 +2792,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the GeoPoint from an array point. The array must contain only @@ -2834,7 +2834,7 @@ declare module elasticjs { Retrieves the internal script object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -2853,7 +2853,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -2921,7 +2921,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -3007,7 +3007,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -3059,7 +3059,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -3079,7 +3079,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -3100,7 +3100,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -3119,7 +3119,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -3185,7 +3185,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -3232,7 +3232,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the child document type to search against @@ -3256,7 +3256,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -3317,7 +3317,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -3360,7 +3360,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -3390,7 +3390,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Set's the boundary characters. When highlighting a field that is @@ -3462,7 +3462,7 @@ declare module elasticjs { Sets arbitrary options that can be passed to the highlighter implementation in use. */ - options(opts: string, oField: Object): Highlight; + options(opts: string, oField: string): Highlight; /* Sets the order of highlight fragments. You can apply the option @@ -3508,7 +3508,7 @@ declare module elasticjs { Retrieves the internal script object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the highligher type. You can apply the option @@ -3539,7 +3539,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -3621,7 +3621,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -3655,7 +3655,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enables caching of the facetFilter @@ -3762,7 +3762,7 @@ declare module elasticjs { Retrieves the internal facet object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Allows you to specify a different value field to aggrerate over. @@ -3793,7 +3793,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -3848,7 +3848,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -3859,7 +3859,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the type as a single type or an array of types. If type is a @@ -3896,7 +3896,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the document id of the indexed shape. @@ -3919,7 +3919,7 @@ declare module elasticjs { Retrieves the internal script object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the type which the shape is indexed under. @@ -3945,7 +3945,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -4006,7 +4006,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -4036,7 +4036,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -4057,7 +4057,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -4115,7 +4115,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -4133,7 +4133,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -4177,7 +4177,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -4216,7 +4216,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -4227,7 +4227,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -4248,7 +4248,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the analyzer name used to analyze the Query object. @@ -4377,7 +4377,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the type of the MatchQuery. Valid values are @@ -4411,7 +4411,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the field to operate on. @@ -4443,7 +4443,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -4453,7 +4453,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the field to operate on. @@ -4485,7 +4485,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -4507,7 +4507,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the field to operate on. @@ -4539,7 +4539,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -4559,7 +4559,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -4585,7 +4585,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -4603,7 +4603,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -4657,7 +4657,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* The analyzer that will be used to analyze the text. Defaults to the @@ -4748,7 +4748,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -4767,7 +4767,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* The analyzer that will be used to analyze the text. Defaults to the @@ -4860,7 +4860,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -4883,7 +4883,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the analyzer name used to analyze the Query object. @@ -5022,7 +5022,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the type of the MultiMatchQuery. Valid values are @@ -5061,7 +5061,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -5087,7 +5087,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -5113,7 +5113,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value of the nested Query. @@ -5190,7 +5190,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -5227,7 +5227,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -5246,7 +5246,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -5300,7 +5300,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -5388,7 +5388,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -5437,7 +5437,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Compression controls memory usage and approximation error. The compression @@ -5496,7 +5496,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -5518,7 +5518,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets analyzer used to analyze the suggest text. @@ -5625,7 +5625,7 @@ declare module elasticjs { Retrieves the internal suggest object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the token limit. @@ -5649,7 +5649,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -5698,7 +5698,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value of the Query. @@ -5743,7 +5743,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* The prefix value. @@ -5780,7 +5780,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enables caching of the facetFilter @@ -5827,7 +5827,7 @@ declare module elasticjs { Retrieves the internal facet object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -5853,7 +5853,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -5888,7 +5888,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -5899,7 +5899,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -5922,7 +5922,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets whether or not wildcard characters (* and ?) are allowed as the @@ -6114,7 +6114,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets whether or not queries against multiple fields should be combined using Lucene's @@ -6140,7 +6140,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Adds a filter whose matching documents will have the score function applied. @@ -6156,7 +6156,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -6181,7 +6181,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -6223,7 +6223,7 @@ declare module elasticjs { /* Adds a range to the list of exsiting range expressions. */ - range(from: string, to: string, key: string): RangeAggregation; + range(from: number, to?: number, key?: string): RangeAggregation; /* Allows you generate or modify the terms using a script. @@ -6239,7 +6239,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -6271,7 +6271,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Adds a new bounded range. @@ -6356,7 +6356,7 @@ declare module elasticjs { Retrieves the internal facet object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Allows you to specify an alternate value field to be used to compute statistical information. @@ -6385,7 +6385,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -6476,7 +6476,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value of the Query. @@ -6537,7 +6537,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -6557,7 +6557,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -6630,7 +6630,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value of the Query. @@ -6698,7 +6698,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* The regexp value. @@ -6721,7 +6721,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add an aggregation. This method can be called multiple times @@ -6769,7 +6769,7 @@ declare module elasticjs { by making multiple request. This parameters specifies the starting result/document number point. Combine with size() to achieve paging. */ - from(f: any[]): Request; + from(f: number): Request; /* Performs highlighting based on the Highlight @@ -6827,7 +6827,7 @@ declare module elasticjs { It is recommended to use Sort objects when possible. */ - sort(fieldName: string): Request; + sort(fieldName?: string | any[] | Sort, order?: string): Request; /* Allows to control how the _source field is returned with every hit. @@ -6859,7 +6859,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Enables score computation and tracking during sorting. Be default, @@ -6889,7 +6889,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the weight assigned to the original query of the rescoring. @@ -6921,7 +6921,7 @@ declare module elasticjs { Retrieves the internal script object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the window_size parameter of the rescoring. @@ -6936,7 +6936,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Adds a filter whose matching documents will have the score function applied. @@ -6947,7 +6947,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -6969,7 +6969,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* If execeptions thrown from the script should be ignored or not. @@ -6997,7 +6997,7 @@ declare module elasticjs { Retrieves the internal script object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7015,7 +7015,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -7071,7 +7071,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Adds a filter whose matching documents will have the score function applied. @@ -7098,7 +7098,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7119,7 +7119,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the coordinates for the shape definition. Note, the coordinates @@ -7137,7 +7137,7 @@ declare module elasticjs { Retrieves the internal script object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the shape type. Can be set to one of: point, linestring, polygon, @@ -7163,7 +7163,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -7237,7 +7237,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7258,7 +7258,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the sort order to ascending (asc). Same as calling @@ -7393,7 +7393,7 @@ declare module elasticjs { Retrieves the internal script object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the script sort type. Valid values are: @@ -7433,7 +7433,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -7454,7 +7454,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7474,7 +7474,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -7490,7 +7490,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7509,7 +7509,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -7543,7 +7543,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7562,7 +7562,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -7583,7 +7583,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7602,7 +7602,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -7620,7 +7620,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7640,7 +7640,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -7661,7 +7661,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7693,7 +7693,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enables caching of the facetFilter @@ -7762,7 +7762,7 @@ declare module elasticjs { Retrieves the internal facet object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7786,7 +7786,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the field to operate on. @@ -7818,7 +7818,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7854,7 +7854,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the text to get suggestions for. If not set, the global @@ -7866,7 +7866,7 @@ declare module elasticjs { Retrieves the internal suggest object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7888,7 +7888,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the field to operate on. @@ -7920,7 +7920,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7940,7 +7940,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -7994,7 +7994,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -8015,7 +8015,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -8034,7 +8034,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -8134,7 +8134,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the type of the field value for use in scripts. Current values are: @@ -8169,7 +8169,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Allows you to return all terms, even if the frequency count is 0. This should not be @@ -8301,7 +8301,7 @@ declare module elasticjs { Retrieves the internal facet object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -8320,7 +8320,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -8416,7 +8416,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -8451,7 +8451,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -8483,7 +8483,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Allows you to return all terms, even if the frequency count is 0. This should not be @@ -8579,7 +8579,7 @@ declare module elasticjs { Retrieves the internal facet object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the field for which statistical information will be generated. @@ -8612,7 +8612,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the accuracy. How similar the suggested terms at least @@ -8716,7 +8716,7 @@ declare module elasticjs { Retrieves the internal suggest object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -8740,7 +8740,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -8787,7 +8787,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the child document type to search against @@ -8810,7 +8810,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -8858,7 +8858,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the field to operate on. @@ -8890,7 +8890,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -8915,7 +8915,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -8960,7 +8960,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the wildcard query value. diff --git a/elasticsearch/elasticsearch-tests.ts b/elasticsearch/elasticsearch-tests.ts index 14070aa8cc..6d308dc6ed 100644 --- a/elasticsearch/elasticsearch-tests.ts +++ b/elasticsearch/elasticsearch-tests.ts @@ -45,4 +45,44 @@ client.create({ index: 'index', type: 'type' }, (err, repsonse, status) => { +}); + +client.cluster.getSettings({ + masterTimeout: 100 +}, (err, response) => { +}); + +client.cluster.health({ + masterTimeout: 100 +}, (err, response) => { +}); + +client.cluster.pendingTasks({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.putSettings({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.putSettings({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.reroute({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.state({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.stats({ + ignore: 1 +}, (err, response) => { }); \ No newline at end of file diff --git a/elasticsearch/elasticsearch.d.ts b/elasticsearch/elasticsearch.d.ts index ec67e6a59d..e2079b19d0 100644 --- a/elasticsearch/elasticsearch.d.ts +++ b/elasticsearch/elasticsearch.d.ts @@ -1,12 +1,14 @@ // Type definitions for elasticsearch // Project: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html -// Definitions by: Casper Skydt +// Definitions by: Casper Skydt , Blake Smith // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module Elasticsearch { export class Client { constructor(params: ConfigOptions); indices: Indices; + cluster: Cluster; + cat: Cat; bulk(params: BulkIndexDocumentsParams): PromiseLike; bulk(params: BulkIndexDocumentsParams, callback: (error: any, response: any) => void): void; create(params: CreateDocumentParams): PromiseLike; @@ -230,6 +232,7 @@ declare module Elasticsearch { scroll?: string; search_type?: string; fields?: string[]; + from?: number; size?: number; sort?: string | string[] | boolean; _source?: string | string[] | boolean; @@ -333,6 +336,91 @@ declare module Elasticsearch { body: string | any; index: string | string[] | boolean; } + + export interface Cat { + health(params: CatHealthOptions, callback: (error: any, response: any) => void): void; + health(params: CatHealthOptions): PromiseLike + } + + export interface CatHealthOptions extends GenericParams { + local?: boolean; + masterTimeout?: number | Date; + h?: string | string[] | boolean; + help?: boolean; + ts?: boolean; + v?: boolean; + } + + export interface Cluster { + getSettings(params: ClusterGetSettingsOptions, callback: (error: any, response: any) => void): void; + getSettings(params: ClusterGetSettingsOptions): PromiseLike; + health(params: ClusterHealthOptions, callback: (error: any, response: any) => void): void; + health(params: ClusterHealthOptions): PromiseLike; + pendingTasks(params: ClusterPendingTasksOptions, callback: (error: any, response: any) => void): void; + pendingTasks(params: ClusterPendingTasksOptions): PromiseLike; + putSettings(params: ClusterPutSettingsOptions, callback: (error: any, response: any) => void): void; + putSettings(params: ClusterPutSettingsOptions): PromiseLike; + reroute(params: ClusterRerouteOptions, callback: (error: any, response: any) => void): void; + reroute(params: ClusterRerouteOptions): PromiseLike; + state(params: ClusterStateOptions, callback: (error: any, response: any) => void): void; + state(params: ClusterStateOptions): PromiseLike; + stats(params: ClusterStatsOptions, callback: (error: any, response: any) => void): void; + stats(params: ClusterStatsOptions): PromiseLike; + } + + export interface ClusterGetSettingsOptions extends GenericParams { + flatSettings?: boolean; + masterTimeout?: number | Date; + timeout?: number | Date; + } + + export interface ClusterHealthOptions extends GenericParams { + level?: string; // cluster, indices, shards + local?: boolean; + masterTimeout?: number | Date; + waitForActiveShards?: number; + waitForNodes?: string; + waitForRelocatingShards?: number; + waitForStatus?: string; // green, yellow, red + index?: string | string[] | boolean; + } + + export interface ClusterPendingTasksOptions extends GenericParams { + local?: boolean; + masterTimeout?: number | Date; + } + + export interface ClusterPutSettingsOptions extends GenericParams { + flatSettings?: boolean; + masterTimeout?: number | Date; + timeout?: number | Date; + } + + export interface ClusterRerouteOptions extends GenericParams { + dryRun?: boolean; + explain?: boolean; + metric?: string | string[] | boolean; + masterTimeout?: number | Date; + timeout?: number | Date; + } + + export interface ClusterStateOptions extends GenericParams { + local?: boolean; + masterTimeout?: number | Date; + flatSettings?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: string; // open, closed, none, all (default open) + index?: string | string[] | boolean; + metric?: string | string[] | boolean; + } + + export interface ClusterStatsOptions extends GenericParams { + flatSettings?: boolean; + human?: boolean; + timeout?: number | Date; + nodeId?: string | string[] | boolean; + } } declare module "elasticsearch" { diff --git a/fabricjs/fabricjs.d.ts b/fabricjs/fabricjs.d.ts index 727cb57f23..08fcdb6ec3 100644 --- a/fabricjs/fabricjs.d.ts +++ b/fabricjs/fabricjs.d.ts @@ -333,7 +333,6 @@ declare namespace fabric { on(eventName: {[key:string] : Function}): T; /** * Fires event with an optional options object - * @deprecated `fire` deprecated since 1.0.7 (use `trigger` instead) * @param {String} eventName Event name to fire * @param {Object} [options] Options object */ @@ -341,7 +340,6 @@ declare namespace fabric { /** * Stops event observing for a particular event handler. Calling this method * without arguments removes all handlers for all events - * @deprecated `stopObserving` deprecated since 0.8.34 (use `off` instead) * @param eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler}) * @param handler Function to be deleted from EventListeners */ diff --git a/fs-extra/fs-extra.d.ts b/fs-extra/fs-extra.d.ts index 39656ce685..7061f08746 100644 --- a/fs-extra/fs-extra.d.ts +++ b/fs-extra/fs-extra.d.ts @@ -79,8 +79,9 @@ declare module "fs-extra" { export interface CopyOptions { clobber?: boolean preserveTimestamps?: boolean - dereference?: boolean + dereference?: boolean filter?: CopyFilter + recursive?: boolean } export interface OpenOptions { diff --git a/fullCalendar/fullCalendar.d.ts b/fullCalendar/fullCalendar.d.ts index fd43e51c5f..81ce91d119 100644 --- a/fullCalendar/fullCalendar.d.ts +++ b/fullCalendar/fullCalendar.d.ts @@ -25,15 +25,17 @@ declare namespace FullCalendar { end: moment.Moment; } + export interface Header { + left: string; + center: string; + right: string; + } + export interface Options extends AgendaOptions, EventDraggingResizingOptions, DroppingExternalElementsOptions, SelectionOptions { // General display - http://fullcalendar.io/docs/display/ - header?: { - left: string; - center: string; - right: string; - } - theme?: boolean + header?: boolean | Header; + theme?: boolean; buttonIcons?: { prev: string; next: string; @@ -50,7 +52,7 @@ declare namespace FullCalendar { contentHeight?: number; aspectRatio?: number; handleWindowResize?: boolean; - views?: ViewSpecificOptions; + views?: ViewSpecificOptions; viewRender?: (view: ViewObject, element: JQuery) => void; viewDestroy?: (view: ViewObject, element: JQuery) => void; dayRender?: (date: Date, cell: HTMLTableDataCellElement) => void; diff --git a/geojson2osm/geojson2osm-tests.ts b/geojson2osm/geojson2osm-tests.ts new file mode 100644 index 0000000000..c7bfc05b85 --- /dev/null +++ b/geojson2osm/geojson2osm-tests.ts @@ -0,0 +1,47 @@ +/// +/// + +import { geojson2osm } from 'geojson2osm' + +const features: GeoJSON.FeatureCollection = { + type: 'FeatureCollection', + features: [{ + type: 'Feature', + properties: { + 'building:colour': '#9F8169', + 'building:levels': 21, + building: 'yes', + height: 57, + }, + geometry: { + type: 'Polygon', + coordinates: [ + [ + [ + -434.2249470949173, + -13.15996269397843, + ], + [ + -434.2249470949173, + -13.159751140560356, + ], + [ + -434.2242631316185, + -13.159751140560356, + ], + [ + -434.2242631316185, + -13.15996269397843, + ], + [ + -434.2249470949173, + -13.15996269397843, + ], + ], + ], + }, + }, + ], +} + +geojson2osm(features) diff --git a/geojson2osm/geojson2osm.d.ts b/geojson2osm/geojson2osm.d.ts new file mode 100644 index 0000000000..58393411f1 --- /dev/null +++ b/geojson2osm/geojson2osm.d.ts @@ -0,0 +1,15 @@ +// Type definitions for geojson2osm 0.0.5 +// Project: https://github.com/Rub21/geojson2osm +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'geojson2osm' { + /** + * Converts GeoJSON features to OpenStreetMap XML. + * @param features Input features + * @returns OpenStreetMap XML + */ + export function geojson2osm(features: GeoJSON.Feature | GeoJSON.FeatureCollection): any +} diff --git a/github-electron/github-electron-main-tests.ts b/github-electron/github-electron-main-tests.ts index bebf0b99c8..966465ed3a 100644 --- a/github-electron/github-electron-main-tests.ts +++ b/github-electron/github-electron-main-tests.ts @@ -240,6 +240,63 @@ app.setUserTasks([ } ]); app.setUserTasks([]); + +app.setJumpList([ + { + type: 'custom', + name: 'Recent Projects', + items: [ + { type: 'file', path: 'C:\\Projects\\project1.proj' }, + { type: 'file', path: 'C:\\Projects\\project2.proj' } + ] + }, + { // has a name so type is assumed to be "custom" + name: 'Tools', + items: [ + { + type: 'task', + title: 'Tool A', + program: process.execPath, + args: '--run-tool-a', + iconPath: process.execPath, + iconIndex: 0, + description: 'Runs Tool A' + }, + { + type: 'task', + title: 'Tool B', + program: process.execPath, + args: '--run-tool-b', + iconPath: process.execPath, + iconIndex: 0, + description: 'Runs Tool B' + }] + }, + { + type: 'frequent' + }, + { // has no name and no type so type is assumed to be "tasks" + items: [ + { + type: 'task', + title: 'New Project', + program: process.execPath, + args: '--new-project', + description: 'Create a new project.' + }, + { + type: 'separator' + }, + { + type: 'task', + title: 'Recover Project', + program: process.execPath, + args: '--recover-project', + description: 'Recover Project' + }] + } +]); + if (app.isUnityRunning()) { } if (app.isAccessibilitySupportEnabled()) { diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 7d10fce465..3dc72d7075 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Electron v1.3.4 +// Type definitions for Electron v1.3.5 // Project: http://electron.atom.io/ // Definitions by: jedmao , rhysd , Milan Burda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -199,7 +199,7 @@ declare namespace Electron { * All windows will be closed immediately without asking user * and the before-quit and will-quit events will not be emitted. */ - exit(exitCode: number): void; + exit(exitCode?: number): void; /** * Relaunches the app when current instance exits. * @@ -333,6 +333,19 @@ declare namespace Electron { * Note: This API is only available on Windows. */ setUserTasks(tasks: Task[]): boolean; + /** + * Note: This API is only available on Windows. + */ + getJumpListSettings(): JumpListSettings; + /** + * Sets or removes a custom Jump List for the application. + * + * If categories is null the previously set custom Jump List (if any) will be replaced + * by the standard Jump List for the app (managed by Windows). + * + * Note: This API is only available on Windows. + */ + setJumpList(categories: JumpListCategory[]): SetJumpListResult; /** * This method makes your application a Single Instance Application instead of allowing * multiple instances of your app to run, this will ensure that only a single instance @@ -560,6 +573,89 @@ declare namespace Electron { iconIndex?: number; } + /** + * ok - Nothing went wrong. + * error - One or more errors occured, enable runtime logging to figure out the likely cause. + * invalidSeparatorError - An attempt was made to add a separator to a custom category in the Jump List. + * Separators are only allowed in the standard Tasks category. + * fileTypeRegistrationError - An attempt was made to add a file link to the Jump List + * for a file type the app isn't registered to handle. + * customCategoryAccessDeniedError - Custom categories can't be added to the Jump List + * due to user privacy or group policy settings. + */ + type SetJumpListResult = 'ok' | 'error' | 'invalidSeparatorError' | 'fileTypeRegistrationError' | 'customCategoryAccessDeniedError'; + + interface JumpListSettings { + /** + * The minimum number of items that will be shown in the Jump List. + */ + minItems: number; + /** + * Items that the user has explicitly removed from custom categories in the Jump List. + */ + removedItems: JumpListItem[]; + } + + interface JumpListCategory { + /** + * tasks - Items in this category will be placed into the standard Tasks category. + * frequent - Displays a list of files frequently opened by the app, the name of the category and its items are set by Windows. + * recent - Displays a list of files recently opened by the app, the name of the category and its items are set by Windows. + * custom - Displays tasks or file links, name must be set by the app. + */ + type?: 'tasks' | 'frequent' | 'recent' | 'custom'; + /** + * Must be set if type is custom, otherwise it should be omitted. + */ + name?: string; + /** + * Array of JumpListItem objects if type is tasks or custom, otherwise it should be omitted. + */ + items?: JumpListItem[]; + } + + interface JumpListItem { + /** + * task - A task will launch an app with specific arguments. + * separator - Can be used to separate items in the standard Tasks category. + * file - A file link will open a file using the app that created the Jump List. + */ + type: 'task' | 'separator' | 'file'; + /** + * Path of the file to open, should only be set if type is file. + */ + path?: string; + /** + * Path of the program to execute, usually you should specify process.execPath which opens the current program. + * Should only be set if type is task. + */ + program?: string; + /** + * The command line arguments when program is executed. Should only be set if type is task. + */ + args?: string; + /** + * The text to be displayed for the item in the Jump List. Should only be set if type is task. + */ + title?: string; + /** + * Description of the task (displayed in a tooltip). Should only be set if type is task. + */ + description?: string; + /** + * The absolute path to an icon to be displayed in a Jump List, which can be an arbitrary + * resource file that contains an icon (e.g. .ico, .exe, .dll). + * You can usually specify process.execPath to show the program icon. + */ + iconPath?: string; + /** + * The index of the icon in the resource file. If a resource file contains multiple icons + * this value can be used to specify the zero-based index of the icon that should be displayed + * for this task. If a resource file contains only one icon, this property should be set to zero. + */ + iconIndex?: number; + } + interface LoginItemSettings { /** * True if the app is set to open at login. @@ -3595,7 +3691,7 @@ declare namespace Electron { interface WebContentsStatic { /** - * @returns An array of all web contents. This will contain web contents for all windows, + * @returns An array of all WebContents instances. This will contain web contents for all windows, * webviews, opened devtools, and devtools extension background pages. */ getAllWebContents(): WebContents[]; @@ -3603,6 +3699,10 @@ declare namespace Electron { * @returns The web contents that is focused in this application, otherwise returns null. */ getFocusedWebContents(): WebContents; + /** + * Find a WebContents instance according to its ID. + */ + fromId(id: number): WebContents; } /** @@ -4971,6 +5071,17 @@ declare namespace Electron { * See webContents.sendInputEvent for detailed description of event object. */ sendInputEvent(event: SendInputEvent): void + /** + * Changes the zoom factor to the specified factor. + * Zoom factor is zoom percent divided by 100, so 300% = 3.0. + */ + setZoomFactor(factor: number): void; + /** + * Changes the zoom level to the specified level. + * The original size is 0 and each increment above or below represents + * zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. + */ + setZoomLevel(level: number): void; /** * Shows pop-up dictionary that searches the selected word on the page. * Note: This API is available only on macOS. diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 97d29bbf04..0aef3b74a6 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -61,6 +61,7 @@ declare namespace google.maps { backgroundColor?: string; center?: LatLng|LatLngLiteral; disableDefaultUI?: boolean; + clickableIcons?: boolean; disableDoubleClickZoom?: boolean; draggable?: boolean; draggableCursor?: string; @@ -755,7 +756,7 @@ declare namespace google.maps { zIndex?: number; } - export interface PolyMouseEvent { + export interface PolyMouseEvent extends MouseEvent { edge?: number; path?: number; vertex?: number; diff --git a/gulp/gulp.d.ts b/gulp/gulp.d.ts index 74968ddcc5..f4314bd2f2 100644 --- a/gulp/gulp.d.ts +++ b/gulp/gulp.d.ts @@ -5,9 +5,11 @@ /// /// +/// declare module "gulp" { import Orchestrator = require("orchestrator"); + import VinylFile = require("vinyl"); namespace gulp { interface Gulp extends Orchestrator { @@ -92,7 +94,7 @@ declare module "gulp" { * @param outFolder The path (output folder) to write files to. Or a function that returns it, the function will be provided a vinyl File instance. * @param opt */ - (outFolder: string|((file: string) => string), opt?: DestOptions): NodeJS.ReadWriteStream; + (outFolder: string|((file: VinylFile) => string), opt?: DestOptions): NodeJS.ReadWriteStream; } interface SrcMethod { @@ -149,7 +151,7 @@ declare module "gulp" { * Note that an explicit dot in a portion of the pattern will always match dot files. */ dot?: boolean; - + /** * Set to match only fles, not directories. Set this flag to prevent copying empty directories */ diff --git a/heremaps/heremaps.d.ts b/heremaps/heremaps.d.ts index fe79e55ecf..8d730f3ae5 100644 --- a/heremaps/heremaps.d.ts +++ b/heremaps/heremaps.d.ts @@ -1073,6 +1073,125 @@ declare namespace H { */ resizeToCenter(center: H.geo.IPoint, opt_out?: H.geo.Rect): H.geo.Rect; } + + /** + * A strip is a flat list of latitude, longitude, altitude tuples in a fixed order. + */ + export class Strip { + /** + * Constructor + * @param opt_latLngAlts {Array=} - An optional array of latitude, longitude and altitude triples to initialize the strip with. + * @param opt_ctx {H.geo.AltitudeContext=} - An optional altitude context for all altitudes contained in this strip. + */ + constructor(opt_latLngAlts?: Array, opt_ctx?: H.geo.AltitudeContext); + + /** + * This method pushes a lat, lng, alt to the end of this strip. + * @param lat {H.geo.Latitude} + * @param lng {H.geo.Longitude} + * @param alt {H.geo.Altitude} + */ + pushLatLngAlt(lat: H.geo.Latitude, lng: H.geo.Longitude, alt: H.geo.Altitude): void; + + /** + * This method splices the strip at the provided index, removing the specified number of items at that index and inserting the lat, lng, alt array. + * @param index {number} - The index at which to splice + * @param opt_nRemove {number=} - The number of lat, lng, alt values to remove + * @param opt_latLngAlts {Array=} - The lat, lng, alt values to add + * @returns {Array} - an array of removed elements + */ + spliceLatLngAlts(index: number, opt_nRemove?: number, opt_latLngAlts?: Array): Array; + + /** + * This method inserts one set of lat, lng, alt values into the strip at the specified index. + * @param index {number} - the index at which to add the element + * @param lat {H.geo.Latitude} - the latitude to insert + * @param lng {H.geo.Longitude} - the longitude to insert + * @param alt {H.geo.Altitude} - the altitude to insert + */ + insertLatLngAlt(index: number, lat: H.geo.Latitude, lng: H.geo.Longitude, alt: H.geo.Altitude): void; + + /** + * This method removes one set of lat, lng, alt values from the strip at the specified index. + * @param index {number} + */ + removeLatLngAlt(index: number): void; + + /** + * This method pushes the lat, lng, alt values of a H.geo.Point to the end of this strip. + * @param geoPoint {H.geo.IPoint} + */ + pushPoint(geoPoint: H.geo.IPoint): void; + + /** + * This method inserts the lat, lng, alt values of a H.geo.Point into the list at the specified index. + * @param pointIndex {number} + * @param geoPoint {H.geo.IPoint} + */ + insertPoint(pointIndex: number, geoPoint: H.geo.IPoint): void; + + /** + * This method removes one set of lat, lng, alt values from this strip at the virtual point index specified. + * @param pointIndex {number} - the virtual point index + */ + removePoint(pointIndex: number): void; + + /** + * This method extracts a H.geo.Point from this strip at the virtual point index. If the extracted point has an alt value, the strip's altitude context will be supplied to the point. + * @param pointIndex {number} - the virtual point index in the strip + * @param opt_out {H.geo.Point=} - an optional point object to store the lat, lng, alt values + * @returns {H.geo.Point} - returns either the 'opt_out' point object or a new point object. + */ + extractPoint(pointIndex: number, opt_out?: H.geo.Point): H.geo.Point; + + /** + * This method is a utility method that iterates over the lat, lng, alt array and calls the provided function for each 3 elements passing lat, lng and alt and the virtual point index as arguments. + * @param eachFn {function(H.geo.Latitude, H.geo.Longitude, H.geo.Altitude, number)} - the function to be called for each 3 elements + * @param opt_start {number=} - an optional start index to iterate from + * @param opt_end {number=} - an optional end index to iterate to + */ + eachLatLngAlt(eachFn: (lat: H.geo.Latitude, lng: H.geo.Longitude, alt: H.geo.Altitude, n: number) => void, opt_start?: number, opt_end?: number): void; + + /** + * This method returns the number of times that legs in this strip cross the date border. + * @param opt_closed {boolean=} - indicates whether the strip is closed (i.e. whether the strip's last and first coordinates form the closing leg of a polygon) + * @returns {number} - the amount of times this strip crosses the date border. + */ + getDBCs(opt_closed?: boolean): number; + + /** + * This method return the number of points stored in this strip. + * @returns {number} - the number of points in this strip + */ + getPointCount(): number; + + /** + * This method returns the internal array keeping the lat, lng, alt values. Modifying this array directly can destroy the integrity of this strip. Use it only for read access. + * @returns {Array} - returns the raw lat, lng, alt values of this strip + */ + getLatLngAltArray(): Array; + + /** + * This method returns the bounding box of this strip. + * @returns {?H.geo.Rect} - this strip's bounding rectangle + */ + getBounds(): H.geo.Rect; + + /** + * This method checks whether two longitudes form a leg which crosses the date border. + * @param lng1 {H.geo.Longitude} - the start longitude of the leg + * @param lng2 {H.geo.Longitude} - the end longitude of the leg + * @returns {boolean} - true if the leg crosses the date border, otherwise false + */ + static isDBC(lng1: H.geo.Longitude, lng2: H.geo.Longitude): boolean; + + /** + * This method initializes a new strip with an array of lat, lng values. Arrays are expected to have an even length with the format [lat, lng, lat, lng, ...]. + * @param latLngs {Array} - the array of lat, lng value. + * @returns {H.geo.Strip} - the strip containing the lat, lng values + */ + static fromLatLngArray(latLngs: Array): H.geo.Strip; + } } /***** lang *****/ @@ -1173,6 +1292,78 @@ declare namespace H { } } + /** + * A Polygon with a circular shape. + */ + export class Circle extends H.map.Polygon { + /** + * Constructor + * @param center {H.geo.IPoint} - The geographical coordinates of the circle's center + * @param radius {number} - The radius of the circle in meters + * @param opt_options {H.map.Circle.Options=} - An object that specifies circle options and their initial values (among these, precision has a significant impact on the shape of the circle - please see + */ + constructor(center: H.geo.IPoint, radius: number, opt_options?: H.map.Circle.Options); + + /** + * To set the geographical center point of this circle. If the specified center is an instance of H.geo.Point you must not modify this Point instance without calling setCenter immediately afterwards. + * @param center {H.geo.IPoint} + */ + setCenter(center: H.geo.IPoint): void; + + /** + * To get the center point of this circle You must not modify the returned Point instance without calling setCenter immediately afterwards. + * @returns {H.geo.Point} + */ + getCenter(): H.geo.Point; + + /** + * To set the length of the radius of the circle in meters. The value is clamped to the of {@code[0 ... 20015089.27787877]} (half WGS84 mean circumference) + * @param radius {number} + */ + setRadius(radius: number): void; + + /** + * To get the length of the radius of the circle in meters. + * @returns {number} + */ + getRadius(): number; + + /** + * To set the precision of this circle {@see H.map.Circle.Options#precision} + * @param precision {number} + */ + setPrecision(precision: number): void; + + /** + * To get the precision value of this circle + * @returns {number} + */ + getPrecision(): number; + } + + export module Circle { + /** + * @property style {H.map.SpatialStyle=} - the style to be used when tracing the polyline + * @property visibility {boolean=} - An optional boolean value indicating whether this map object is visible, default is true + * @property precision {number=} - The precision of a circle as a number of segments to be used when rendering the circle. The value is clamped to the range between [4 ... 360], where 60 is the default. Note that the lower the value the more angular and the less circle-like the shape appears and, conversely, the higher the value the smoother and more rounded the result. Thus, starting at the extreme low end of the possible values, 4 produces a square, 6 a hexagon, while 30 results in a circle-like shape, although it appears increasingly angular as the zoom level increases (as you zoom in), and finally 360 produces a smooth circle. + * @property zIndex {number=} - The z-index value of the circle, default is 0 + * @property min {number=} - The minimum zoom level for which the circle is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the circle is visible, default is Infinity + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData + */ + export interface Options { + style?: H.map.SpatialStyle | H.map.SpatialStyle.Options; + visibility?: boolean; + precision?: number; + zIndex?: number; + min?: number; + max?: number; + provider?: H.map.provider.Provider; + data?: any; + } + } + /** * The class represents data model of the map. It holds list of layers that are rendered by map's RenderEngine. The class listens to 'update' events from layers and dispatches them to the RenderEngine. */ @@ -1242,6 +1433,38 @@ declare namespace H { } } + /** + * This class represents a spatial shape in geographic space. It is defined by a path containing the vertices of the shape (lat, lng, alt values). + */ + export class GeoShape extends H.map.Spatial { + /** + * Constructor + * @param isClosed {boolean} - Indicates whether this geographical shape is closed (a polygon) + * @param strip {H.geo.Strip} - The strip describing the shape of the spatial object + * @param options {H.map.Spatial.Options} - The options to apply + */ + constructor(isClosed: boolean, strip: H.geo.Strip, options: H.map.Spatial.Options); + + /** + * This method returns the strip which represents the shape of the spatial object. + * @returns {H.geo.Strip} - the strip + */ + getStrip(): H.geo.Strip; + + /** + * This method sets the geo-information for the spatial object + * @param strip {?H.geo.Strip} - The strip which represents the shape of the spatial object. + * @returns {H.map.GeoShape} - the Spatial instance itself + */ + setStrip(strip: H.geo.Strip): H.map.GeoShape; + + /** + * This method returns the bounding rectangle for this object. The rectangle is the smallest rectangle which encloses all points of the spatial object. + * @returns {H.geo.Rect} + */ + getBounds(): H.geo.Rect; + } + /** * This class represents a map object which can contain other map objects. It's visibility, zIndex and object-order influences the contained map objects */ @@ -1855,6 +2078,92 @@ declare namespace H { } } + /** + * This class represents a polygon in geo-space. It is defined by a strip containing the vertices of a geo shape object (lat, lng, alt values) and a pen to use when rendering the polyline. Polygon represents a closed plane defined by the list of verticies, projected on the map display. List of vericies which define the polygon are is a list of geo coordinates encapsulated by the strip object H.geo.Strip + */ + export class Polygon extends H.map.GeoShape { + /** + * Constructor + * @param strip {H.geo.Strip} - the strip describing this polygon's vertices + * @param opt_options {H.map.Spatial.Options=} - optional initialization parameters + */ + constructor(strip: H.geo.Strip, opt_options?: H.map.Spatial.Options); + + /** + * To set the indicator whether this polygon covers the north pole. It's needed for Polygons whose strip is defined as lines arround the world on longitude axis (for example a circle whose center is one of the poles). In this case a additional information is needed to know if the southern or northern part of the world should be covered by the poygon. + * @param flag {boolean} - A value of true means it covers the north pole, false means south pole + * @returns {H.map.Polygon} - the Polygon instance itself + */ + setNorthPoleCovering(flag: boolean): H.map.Polygon; + + /** + * See H.map.Polygon#setNorthPoleCovering + * @returns {boolean} + */ + getNorthPoleCovering(): boolean; + } + + /** + * This class represents a polyline in geo-space. It is defined by a path containing the vertices of a polyline (lat, lng, alt values) and a pen to use when tracing the path on the map. + */ + export class Polyline extends H.map.GeoShape { + /** + * Constructor + * @param strip {H.geo.Strip} - the strip describing this polygon's vertices + * @param opt_options {H.map.Polyline.Options=} - optional initialization parameters + */ + constructor(strip: H.geo.Strip, opt_options?: H.map.Polyline.Options); + + /** + * This method clips this polyline against a rectangular area and returns the intersecting sub-lines. + * @param geoRect {H.geo.Rect} + * @returns {Array>} + */ + clip(geoRect: H.geo.Rect): Array>; + } + + export module Polyline { + /** + * Options which are used to initialize a polyline + * @property style {(H.map.SpatialStyle | H.map.SpatialStyle.Options)=} - the style to be used when tracing the polyline + * @property arrows {(H.map.ArrowStyle | H.map.ArrowStyle.Options)=} - The arrows style to be used when rendering the polyline. + * @property visibility {boolean=} - An optional boolean value indicating whether this map object is visible, default is true + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData + */ + export interface Options { + style?: (H.map.SpatialStyle | H.map.SpatialStyle.Options); + arrows?: (H.map.ArrowStyle | H.map.ArrowStyle.Options); + visibility?: boolean; + zIndex?: number; + min?: number; + max?: number; + provider?: H.map.provider.Provider; + data?: any; + } + } + + /** + * A Polygon with a rectangular shape. + */ + export class Rect extends H.map.Polygon { + /** + * Constructor + * @param bounds {H.geo.Rect} - The geographical bounding box for this rectangle + * @param opt_options {H.map.Spatial.Options=} + */ + constructor(bounds: H.geo.Rect, opt_options?: H.map.Spatial.Options); + + /** + * To set the bounds of this rectangle. + * @param bounds {H.geo.Rect} + */ + setBounds(bounds: H.geo.Rect): void; + } + /** * This class represents a spatial map object which provides its projected geometry. */ @@ -1985,8 +2294,8 @@ declare namespace H { miterLimit: number; lineDash: Array; lineDashOffset: number; - MAX_LINE_WIDTH: number; - DEFAULT_STYLE: H.map.SpatialStyle; + static MAX_LINE_WIDTH: number; + static DEFAULT_STYLE: H.map.SpatialStyle; } export module SpatialStyle { @@ -2018,7 +2327,7 @@ declare namespace H { lineCap?: H.map.SpatialStyle.LineCap; lineJoin?: H.map.SpatialStyle.LineJoin; miterLimit?: number; - lineDash: Array; + lineDash?: Array; lineDashOffset?: number; } } diff --git a/humps/humps-tests.ts b/humps/humps-tests.ts new file mode 100644 index 0000000000..66017b065c --- /dev/null +++ b/humps/humps-tests.ts @@ -0,0 +1,71 @@ +/// + +// Tests evaluated from: +// https://github.com/domchristie/humps/blob/master/README.md + +import * as humps from "humps"; + +let someObject = { attr_one: 'foo', attr_two: 'bar' }; +let someArray = [{ attr_one: 'foo' }, { attr_one: 'bar' }] + +let someOptions: humps.HumpsOptions = { + separator: '-' +}; +let someOptions2: humps.HumpsOptions = { + split: /^[A-Z0-9_]+$/ +}; +let someOptions3: humps.HumpsOptions = { + separator: '-', + process: function (key: string, convert: humps.HumpsProcessorParameter, options: humps.HumpsOptions) { + return /^[A-Z0-9_]+$/.test(key) ? key : convert(key, options); + } +}; + + +humps.camelize('hello_world') + +humps.decamelize('fooBar') +humps.decamelize('fooBarBaz', someOptions) + +humps.camelizeKeys(someObject); + +humps.camelizeKeys(someArray); + +humps.camelizeKeys(someObject, function (key, convert) { + return /^[A-Z0-9_]+$/.test(key) ? key : convert(key); +}); + +humps.decamelizeKeys(someObject, function (key, convert, options) { + return /^[A-Z0-9_]+$/.test(key) ? key : convert(key, options); +}); + + +humps.camelize('hello_world-foo bar'); + +humps.pascalize('hello_world-foo bar'); + +humps.decamelize('helloWorldFooBar'); +humps.decamelize('helloWorldFooBar', someOptions); +humps.decamelize('helloWorld1', { split: /(?=[A-Z0-9])/ }) + +humps.depascalize('helloWorldFooBar'); + +humps.camelizeKeys(someObject); +humps.pascalizeKeys(someObject); +humps.decamelizeKeys(someObject); +humps.depascalizeKeys(someObject); + +humps.camelizeKeys(someObject, someOptions); +humps.pascalizeKeys(someObject, someOptions); +humps.decamelizeKeys(someObject, someOptions); +humps.depascalizeKeys(someObject, someOptions); + +humps.camelizeKeys(someObject, someOptions2); +humps.pascalizeKeys(someObject, someOptions2); +humps.decamelizeKeys(someObject, someOptions2); +humps.depascalizeKeys(someObject, someOptions2); + +humps.camelizeKeys(someObject, someOptions3); +humps.pascalizeKeys(someObject, someOptions3); +humps.decamelizeKeys(someObject, someOptions3); +humps.depascalizeKeys(someObject, someOptions3); diff --git a/humps/humps.d.ts b/humps/humps.d.ts new file mode 100644 index 0000000000..87f3bbd991 --- /dev/null +++ b/humps/humps.d.ts @@ -0,0 +1,39 @@ +// Type definitions for humps v1.1.0 +// Project: https://github.com/domchristie/humps +// Definitions by: Niklas Mollenhauer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace humps { + + function camelize(value: string): string; + function pascalize(value: string): string; + function decamelize(value: string, optionsOrProcessor?: OptionOrProcessor): string; + function depascalize(value: string, optionsOrProcessor?: OptionOrProcessor): string; + + function camelizeKeys(str: Object, optionsOrProcessor?: OptionOrProcessor): Object; + function pascalizeKeys(str: Object, optionsOrProcessor?: OptionOrProcessor): Object; + function decamelizeKeys(str: Object, optionsOrProcessor?: OptionOrProcessor): Object; + function depascalizeKeys(str: Object, optionsOrProcessor?: OptionOrProcessor): Object; + + function camelizeKeys(str: Object[], optionsOrProcessor?: OptionOrProcessor): Object[]; + function pascalizeKeys(str: Object[], optionsOrProcessor?: OptionOrProcessor): Object[]; + function decamelizeKeys(str: Object[], optionsOrProcessor?: OptionOrProcessor): Object[]; + function depascalizeKeys(str: Object[], optionsOrProcessor?: OptionOrProcessor): Object[]; + + interface HumpsOptions { + separator?: string; + split?: RegExp; + process?: HumpsProcessor; + } + interface HumpsProcessor { + (key: string, convert: HumpsProcessorParameter, options?: HumpsOptions): string; + } + interface HumpsProcessorParameter { + (key: string, options?: HumpsOptions): string; + } + type OptionOrProcessor = HumpsOptions | HumpsProcessor; +} + +declare module "humps" { + export = humps; +} diff --git a/incremental-dom/incremental-dom.d.ts b/incremental-dom/incremental-dom.d.ts index 56fd84542f..5a80e82d70 100644 --- a/incremental-dom/incremental-dom.d.ts +++ b/incremental-dom/incremental-dom.d.ts @@ -27,7 +27,7 @@ declare module "incremental-dom" { * @param {...*} var_args Attribute name/value pairs of the dynamic attributes * for the Element. */ - export var elementOpen: (tag: string, key?: string, statics?: any[], ...var_args: any[]) => void; + export var elementOpen: (tag: string, key?: string, statics?: any[], ...var_args: any[]) => HTMLElement; /** * Declares a virtual Element at the current location in the document. This * corresponds to an opening tag and a elementClose tag is required. This is @@ -54,11 +54,11 @@ declare module "incremental-dom" { /** * Closes an open tag started with elementOpenStart. */ - export var elementOpenEnd: () => void; + export var elementOpenEnd: () => HTMLElement; /** * Closes an open virtual Element. */ - export var elementClose: (tag: string) => void; + export var elementClose: (tag: string) => HTMLElement; /** * Declares a virtual Element at the current location in the document that has * no children. @@ -72,11 +72,11 @@ declare module "incremental-dom" { * @param {...*} var_args Attribute name/value pairs of the dynamic attributes * for the Element. */ - export var elementVoid: (tag: string, key?: string, statics?: any, ...var_args: any[]) => void; + export var elementVoid: (tag: string, key?: string, statics?: any, ...var_args: any[]) => HTMLElement; /** * Declares a virtual Text at this point in the document. * * @param {string} value The text of the Text. */ - export var text: (value: string) => void; + export var text: (value: string) => Text; } diff --git a/ionic/ionic-tests.ts b/ionic/ionic-tests.ts index d8c98ae25f..140d102a8c 100644 --- a/ionic/ionic-tests.ts +++ b/ionic/ionic-tests.ts @@ -176,6 +176,7 @@ class IonicTestController { var currentStateName: string = this.$ionicHistory.currentStateName(); this.$ionicHistory.goBack(5); + this.$ionicHistory.removeBackView(); this.$ionicHistory.clearHistory(); this.$ionicHistory.clearCache().then(() => console.log("done clearing cache!")); this.$ionicHistory.nextViewOptions({ diff --git a/ionic/ionic.d.ts b/ionic/ionic.d.ts index fae9cdbf63..1df593037b 100644 --- a/ionic/ionic.d.ts +++ b/ionic/ionic.d.ts @@ -213,6 +213,7 @@ declare namespace ionic { currentStateName(): string; goBack(backCount?: number): void; + removeBackView(): void; clearHistory(): void; clearCache(): angular.IPromise; nextViewOptions(options: IonicHistoryNextViewOptions): void; diff --git a/ioredis/ioredis.d.ts b/ioredis/ioredis.d.ts index 983ed39f10..60eccd0272 100644 --- a/ioredis/ioredis.d.ts +++ b/ioredis/ioredis.d.ts @@ -197,6 +197,8 @@ declare module IORedis { hmget(...args: any[]): any; hincrby(args: any[], callback?: ResCallbackT): any; hincrby(...args: any[]): any; + hincrbyfloat(args: any[], callback?: ResCallbackT): any; + hincrbyfloat(...args: any[]): any; hdel(args: any[], callback?: ResCallbackT): any; hdel(...args: any[]): any; hlen(args: any[], callback?: ResCallbackT): any; @@ -478,6 +480,8 @@ declare module IORedis { hmget(...args: any[]): Pipeline; hincrby(args: any[], callback?: ResCallbackT): Pipeline; hincrby(...args: any[]): Pipeline; + hincrbyfloat(args: any[], callback?: ResCallbackT): Pipeline; + hincrbyfloat(...args: any[]): Pipeline; hdel(args: any[], callback?: ResCallbackT): Pipeline; hdel(...args: any[]): Pipeline; hlen(args: any[], callback?: ResCallbackT): Pipeline; diff --git a/is-plain-object/is-plain-object-tests.ts b/is-plain-object/is-plain-object-tests.ts new file mode 100644 index 0000000000..eb57b12434 --- /dev/null +++ b/is-plain-object/is-plain-object-tests.ts @@ -0,0 +1,25 @@ +/// + +import * as isPlainObject from 'is-plain-object'; + +isPlainObject(Object.create({})); +//=> true +isPlainObject(Object.create(Object.prototype)); +//=> true +isPlainObject({foo: 'bar'}); +//=> true +isPlainObject({}); + +isPlainObject(1); +//=> false +isPlainObject(['foo', 'bar']); +//=> false +isPlainObject([]); +//=> false +class Foo {} +isPlainObject(new Foo); +//=> false +isPlainObject(null); +//=> false +isPlainObject(Object.create(null)); +//=> false \ No newline at end of file diff --git a/is-plain-object/is-plain-object.d.ts b/is-plain-object/is-plain-object.d.ts new file mode 100644 index 0000000000..47d277f186 --- /dev/null +++ b/is-plain-object/is-plain-object.d.ts @@ -0,0 +1,10 @@ +// Type definitions for is-plain-object +// Project: https://github.com/jonschlinkert/is-plain-object +// Definitions by: Kevin Zeng +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "is-plain-object" { + namespace isPlainObject {} + function isPlainObject(obj: any): boolean; + export = isPlainObject; +} \ No newline at end of file diff --git a/jest/jest.d.ts b/jest/jest.d.ts index 10949a6691..b2484dfcc5 100644 --- a/jest/jest.d.ts +++ b/jest/jest.d.ts @@ -44,6 +44,7 @@ declare namespace jest { interface Matchers { not: Matchers; toThrow(expected?: any): boolean; + toThrowError(expected?: any): boolean; toBe(expected: any): boolean; toEqual(expected: any): boolean; toBeFalsy(): boolean; diff --git a/joi/joi-tests.ts b/joi/joi-tests.ts index 37848203df..c75309b45e 100644 --- a/joi/joi-tests.ts +++ b/joi/joi-tests.ts @@ -752,6 +752,10 @@ schema = Joi.alternatives(schema, anySchema, boolSchema); // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- +schema = Joi.lazy(() => schema) + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + Joi.validate(value, obj); Joi.validate(value, schema); Joi.validate(value, schema, validOpts); diff --git a/joi/joi.d.ts b/joi/joi.d.ts index 3ba51d7383..b827903f9b 100644 --- a/joi/joi.d.ts +++ b/joi/joi.d.ts @@ -816,6 +816,13 @@ declare module 'joi' { export function alternatives(): AlternativesSchema; export function alternatives(types: Schema[]): AlternativesSchema; export function alternatives(type1: Schema, type2: Schema, ...types: Schema[]): AlternativesSchema; + + /** + * Generates a placeholder schema for a schema that you would provide with the fn. + * Supports the same methods of the any() type. + * This is mostly useful for recursive schemas + */ + export function lazy(cb: () => Schema): Schema; /** * Validates a value using the given schema and options. diff --git a/jquery-mockjax/jquery-mockjax-tests.ts b/jquery-mockjax/jquery-mockjax-tests.ts index 6fae52eb07..36ebd7e64c 100644 --- a/jquery-mockjax/jquery-mockjax-tests.ts +++ b/jquery-mockjax/jquery-mockjax-tests.ts @@ -9,7 +9,7 @@ class Tests { run(): void { const self = this; - var t = QUnit.test; + let t = QUnit.test; QUnit.begin(() => { @@ -36,7 +36,7 @@ class Tests { responseText: 'Hello Word' }); - var xhr = $.ajax({ + let xhr = $.ajax({ url: '/xmlhttprequest', complete: () => { } }); @@ -67,7 +67,7 @@ class Tests { }); t('Intercept asynchronized proxy calls', (assert) => { - var done = assert.async(); + let done = assert.async(); $.mockjax({ url: '/proxy', proxy: 'test_proxy.json' @@ -85,7 +85,7 @@ class Tests { }); t('Intercept and proxy (sub-ajax request)', (assert) => { - var done = assert.async(); + let done = assert.async(); $.mockjax({ url: '/proxy', @@ -104,7 +104,7 @@ class Tests { }); t('Proxy type specification', (assert) => { - var done = assert.async(); + let done = assert.async(); $.mockjax({ url: '/proxy', @@ -124,7 +124,7 @@ class Tests { }); t('Support 1.5 $.ajax(url, settings) signature.', (assert) => { - var done = assert.async(); + let done = assert.async(); $.mockjax({ url: '/resource', @@ -141,9 +141,9 @@ class Tests { }); t('Dynamic response callback', (assert) => { - var done = assert.async(); + let done = assert.async(); - var settings: MockJaxSettings = { + let settings: MockJaxSettings = { url: '/response-callback', response: (settings) => { settings.responseText = settings.data.response + ' 2'; @@ -165,8 +165,36 @@ class Tests { } }); }); + + t('Asyncronous response callback', (assert) => { + let done = assert.async(); + + let settings: MockJaxSettings = { + url: '/async-response-callback', + response: (settings, completed) => { + setTimeout(() => { + settings.responseText = settings.data.response + ' 3'; + completed(); + }, 10); + } + }; + + $.mockjax(settings); + + $.ajax({ + url: '/async-response-callback', + dataType: 'text', + data: { + response: 'Hello world' + }, + error: self._noErrorCallbackExpected, + complete: (xhr) => { + assert.equal(xhr.responseText, 'Hello world 3', 'Response Text matches'); + done(); + } + }); + }); } } -var tests = new Tests(); -tests.run(); +new Tests().run(); diff --git a/jquery-mockjax/jquery-mockjax.d.ts b/jquery-mockjax/jquery-mockjax.d.ts index 7505a30e6f..c054f33317 100644 --- a/jquery-mockjax/jquery-mockjax.d.ts +++ b/jquery-mockjax/jquery-mockjax.d.ts @@ -22,7 +22,7 @@ interface MockJaxSettings { isTimeout?: boolean; dataType?: string; contentType?: string; - response?: (settings: any) => void; + response?: (settings: any, done?: Function) => void; responseText?: string | Object; responseXml?: string; proxy?: string; diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index 0f72c709cf..b08598cc53 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -2780,8 +2780,9 @@ interface JQuery { /** * Retrieve all the elements contained in the jQuery set, as an array. + * @name toArray */ - toArray(): any[]; + toArray(): HTMLElement[]; /** * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. @@ -2837,8 +2838,9 @@ interface JQuery { get(index: number): HTMLElement; /** * Retrieve the elements matched by the jQuery object. + * @alias toArray */ - get(): any[]; + get(): HTMLElement[]; /** * Search for a given element from among the matched elements. diff --git a/js-data-http/js-data-http-tests.ts b/js-data-http/js-data-http-tests.ts index 390e20aa9e..9f0c4c3169 100644 --- a/js-data-http/js-data-http-tests.ts +++ b/js-data-http/js-data-http-tests.ts @@ -1,9 +1,15 @@ +/// /// +import * as axios from 'axios'; + var adapter = new DSHttpAdapter(); var store = new JSData.DS(); store.registerAdapter('http', adapter, { default: true }); +adapter.defaults.basePath = '/api'; +adapter.http = axios; + var ADocument:JSData.DSResourceDefinition = store.defineResource('document'); ADocument.inject({ id: 5, author: 'John' }); diff --git a/js-data-http/js-data-http.d.ts b/js-data-http/js-data-http.d.ts index cde3b4a2e1..04d07f5a38 100644 --- a/js-data-http/js-data-http.d.ts +++ b/js-data-http/js-data-http.d.ts @@ -15,6 +15,8 @@ declare namespace JSData { forceTrailingSlash?: boolean; log?: boolean | ((message?:any, ...optionalParams:any[])=> void); error?: boolean | ((message?:any, ...optionalParams:any[])=> void); + basePath?: string; + verbsUseBasePath?: string; } interface DSHttpAdapterPromiseResolveType { @@ -28,6 +30,9 @@ declare namespace JSData { new(options?:DSHttpAdapterOptions):DSHttpAdapter; + defaults: DSHttpAdapterOptions; + http: any; + // DSHttpAdapter uses axios so options are axios config objects. HTTP(options?:Object):JSDataPromise; DEL(url:string, data?:Object, options?:Object):JSDataPromise; diff --git a/js-data/js-data-tests.ts b/js-data/js-data-tests.ts index 7c66952162..9bbbfdfd64 100644 --- a/js-data/js-data-tests.ts +++ b/js-data/js-data-tests.ts @@ -600,3 +600,5 @@ customActionResource.emit("DS.change", customActionResource, customActionResourc customActionResourceInstance.on("DS.change", myEvtHandler); customActionResourceInstance.off("DS.change", myEvtHandler); customActionResourceInstance.emit("DS.change", customActionResource, customActionResourceInstance); + +JSData.DSUtils.Promise = Promise; \ No newline at end of file diff --git a/js-data/js-data.d.ts b/js-data/js-data.d.ts index f7fc785c82..58bef671b1 100644 --- a/js-data/js-data.d.ts +++ b/js-data/js-data.d.ts @@ -342,6 +342,7 @@ declare namespace JSData { declare var JSData:{ DS: JSData.DS; DSErrors: JSData.DSErrors; + DSUtils: any; }; //Support node require diff --git a/jsdom/jsdom.d.ts b/jsdom/jsdom.d.ts index c6ebde2ce3..2efebc059f 100644 --- a/jsdom/jsdom.d.ts +++ b/jsdom/jsdom.d.ts @@ -68,6 +68,7 @@ declare module "jsdom" { export function createCookieJar(): CookieJar; export function nodeLocation(node: Node): any; export function reconfigureWindow(window: Window, newProps: WindowProperties): void; + export function changeURL(window: Window, url: string): void; export function jQueryify(window: Window, jqueryUrl: string, callback: (window: Window, jquery: JQuery) => any): void; diff --git a/jsts/jsts-tests.ts b/jsts/jsts-tests.ts index 3b37d0f185..e9c00fd52a 100644 --- a/jsts/jsts-tests.ts +++ b/jsts/jsts-tests.ts @@ -1,4 +1,7 @@ /// + +import * as jsts from 'jsts'; + var str: string; var n: number; var bool: boolean; @@ -142,4 +145,4 @@ obj = gjw.write(g); var wr: jsts.io.WKTReader = new jsts.io.WKTReader(); g = wr.read(str); -wr.reducePrecision(g); \ No newline at end of file +wr.reducePrecision(g); diff --git a/jsts/jsts.d.ts b/jsts/jsts.d.ts index 909dbbf7a1..f06b5c7f51 100644 --- a/jsts/jsts.d.ts +++ b/jsts/jsts.d.ts @@ -1664,3 +1664,7 @@ declare namespace jsts { } } } + +declare module "jsts" { + export = jsts; +} diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index 6321cff0a5..f0e9fe023f 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -61,8 +61,10 @@ interface KnockoutSubscription { } interface KnockoutSubscribable extends KnockoutSubscribableFunctions { - subscribe(callback: (newValue: T) => void, target?: any, event?: string): KnockoutSubscription; + subscribe(callback: (newValue: T) => void, target: any, event: "beforeChange"): KnockoutSubscription; + subscribe(callback: (newValue: T) => void, target?: any, event?: "change"): KnockoutSubscription; subscribe(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription; + extend(requestedExtenders: { [key: string]: any; }): KnockoutSubscribable; getSubscriptionsCount(): number; } @@ -91,6 +93,11 @@ interface KnockoutObservableArrayStatic { } interface KnockoutObservableArray extends KnockoutObservable, KnockoutObservableArrayFunctions { + subscribe(callback: (newValue: KnockoutArrayChange[]) => void, target: any, event: "arrayChange"): KnockoutSubscription; + subscribe(callback: (newValue: T[]) => void, target: any, event: "beforeChange"): KnockoutSubscription; + subscribe(callback: (newValue: T[]) => void, target?: any, event?: "change"): KnockoutSubscription; + subscribe(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription; + extend(requestedExtenders: { [key: string]: any; }): KnockoutObservableArray; } @@ -325,7 +332,7 @@ interface KnockoutUtils { } interface KnockoutArrayChange { - status: string; + status: "added" | "deleted"; value: T; index: number; moved?: number; diff --git a/knockout/knockoutamd-tests.ts b/knockout/knockoutamd-tests.ts index c874c6208b..9ee6658335 100644 --- a/knockout/knockoutamd-tests.ts +++ b/knockout/knockoutamd-tests.ts @@ -1,6 +1,6 @@ /// -import ko = require("knockout"); +import ko = require("knockout"); var myArray = ko.observableArray([1, 2, 3]); diff --git a/knockout/tests/knockout-tests.ts b/knockout/tests/knockout-tests.ts index 8da6c12950..122617b180 100644 --- a/knockout/tests/knockout-tests.ts +++ b/knockout/tests/knockout-tests.ts @@ -680,3 +680,38 @@ function test_tasks() { setTimeout(callback, 0); }; } + +function observableEventsTests() { + var observable = ko.observable(1); + observable.subscribe(value => { + var num: number = value; + }); + observable.subscribe(value => { + var num: number = value; + }, null, "change"); + observable.subscribe(value => { + var num: number = value; + }, null, "beforeChange"); +} + +function observableArrayEventsTests() { + var observableArray = ko.observableArray([1, 2, 3, 4]); + observableArray.subscribe(array => { + var arr: number[] = array; + }); + observableArray.subscribe(array => { + var arr: number[] = array; + }, null, "change"); + observableArray.subscribe(array => { + var arr: number[] = array; + }, null, "beforeChange"); + var count = 0; + observableArray.subscribe(changes => { + changes.forEach(change => { + if (change.status == "added") + count++; + else if (change.status == "deleted") + count--; + }); + }, null, "arrayChange"); +} \ No newline at end of file diff --git a/koa-compress/koa-compress.d.ts b/koa-compress/koa-compress.d.ts index c4cd2af582..49a0bb5f1b 100644 --- a/koa-compress/koa-compress.d.ts +++ b/koa-compress/koa-compress.d.ts @@ -37,5 +37,6 @@ declare module "koa-compress" { */ function compress(options?: CompressOptions): { (ctx: Koa.Context, next?: () => any): any }; + namespace compress {} export = compress; } diff --git a/koa-favicon/koa-favicon.d.ts b/koa-favicon/koa-favicon.d.ts index 618683fc76..e09c685173 100644 --- a/koa-favicon/koa-favicon.d.ts +++ b/koa-favicon/koa-favicon.d.ts @@ -31,5 +31,6 @@ declare module "koa-favicon" { }): { (ctx: Koa.Context, next?: () => any): any }; + namespace favicon {} export = favicon; } diff --git a/koa-json-error/koa-json-error-tests.ts b/koa-json-error/koa-json-error-tests.ts new file mode 100644 index 0000000000..37aae696b0 --- /dev/null +++ b/koa-json-error/koa-json-error-tests.ts @@ -0,0 +1,13 @@ +/// +/// +/// + +import * as Koa from "koa"; +import * as error from "koa-json-error"; +import { assign } from "lodash"; + +const app = new Koa(); + +app.use(error({ + preFormat: err => assign({}, err) +})); \ No newline at end of file diff --git a/koa-json-error/koa-json-error.d.ts b/koa-json-error/koa-json-error.d.ts new file mode 100644 index 0000000000..491ead463e --- /dev/null +++ b/koa-json-error/koa-json-error.d.ts @@ -0,0 +1,36 @@ +// Type definitions for koa-json-error v3.x +// Project: https://github.com/koajs/json-error +// Definitions by: Mudkip +// Definitions: https://github.com/mudkipme/DefinitelyTyped + +/// + +declare module "koa-json-error" { + + import * as Koa from "koa"; + + interface JSONErrorOptions { + /** + * Perform some task before calling `options.format`. Must be a function with the original err as its only argument. + */ + preFormat?: { (err: Error): any }; + + /** + * Runs inmediatly after `options.preFormat`. It receives two arguments: the original `err` and the output of `options.preFormat`. It should `return` a newly formatted error. + */ + format?: { (err: Error, obj: any): any }; + + /** + * Runs inmediatly after `options.format`. It receives two arguments: the original `err` and the output of `options.format`. It should `return` a newly formatted error. + */ + postFormat?: { (err: Error, obj: any): any }; + } + + /** + * Error handler for pure Koa 2.0.0+ JSON apps + */ + function jsonError(options?: JSONErrorOptions) : { (ctx: Koa.Context, next?: () => any): any }; + + namespace jsonError {} + export = jsonError; +} \ No newline at end of file diff --git a/koa-router/koa-router-tests.ts b/koa-router/koa-router-tests.ts index 36d3e6c1c8..d2bae290a4 100644 --- a/koa-router/koa-router-tests.ts +++ b/koa-router/koa-router-tests.ts @@ -23,11 +23,11 @@ router .put('/users/:id', function (ctx, next) { ctx.body = ctx.params.id; }) - .del('/users/:id', function (ctx, next) { + .del('/users/:id', function () { // ... }); -router.get('user', '/users/:id', function (ctx, next) { +router.get('user', '/users/:id', function (ctx) { ctx.body = "sdsd"; }); diff --git a/koa-router/koa-router.d.ts b/koa-router/koa-router.d.ts index 25ec962dad..81a961b93a 100644 --- a/koa-router/koa-router.d.ts +++ b/koa-router/koa-router.d.ts @@ -49,11 +49,11 @@ declare module "koa-router" { } export interface IMiddleware { - (ctx: Router.IRouterContext, next?: () => any): any; + (ctx: Router.IRouterContext, next: () => Promise): any; } export interface IParamMiddleware { - (param: string, ctx: Router.IRouterContext, next?: () => any): any; + (param: string, ctx: Router.IRouterContext, next: () => Promise): any; } export interface IRouterAllowedMethodsOptions { @@ -83,10 +83,8 @@ declare module "koa-router" { regexp: RegExp; path: string; - constructor(path: string, methods: string[], middleware: Router.IMiddleware, opts?: Layer.ILayerOptions); - constructor(path: string, methods: string[], middleware: Array, opts?: Layer.ILayerOptions); - constructor(path: RegExp, methods: string[], middleware: Router.IMiddleware, opts?: Layer.ILayerOptions); - constructor(path: RegExp, methods: string[], middleware: Array, opts?: Layer.ILayerOptions); + constructor(path: string | RegExp, methods: string[], middleware: Router.IMiddleware, opts?: Layer.ILayerOptions); + constructor(path: string | RegExp, methods: string[], middleware: Array, opts?: Layer.ILayerOptions); /** * Returns whether request `path` matches route. @@ -96,7 +94,7 @@ declare module "koa-router" { /** * Returns map of URL parameters for given `path` and `paramNames`. */ - params(path: string, captures: string[], existingParams?: Object): Object; + params(path: string | RegExp, captures: string[], existingParams?: Object): Object; /** * Returns array of regexp url path captures. @@ -138,61 +136,61 @@ declare module "koa-router" { * "down" the middleware stack. */ use(...middleware: Array): Router; - use(path: string, ...middleware: Array): Router; + use(path: string | RegExp, ...middleware: Array): Router; /** * HTTP get method */ - get(name: string, path: string, ...middleware: Array): Router; - get(path: string, ...middleware: Array): Router; + get(name: string, path: string | RegExp, ...middleware: Array): Router; + get(path: string | RegExp, ...middleware: Array): Router; /** * HTTP post method */ - post(name: string, path: string, ...middleware: Array): Router; - post(path: string, ...middleware: Array): Router; + post(name: string, path: string | RegExp, ...middleware: Array): Router; + post(path: string | RegExp, ...middleware: Array): Router; /** * HTTP put method */ - put(name: string, path: string, ...middleware: Array): Router; - put(path: string, ...middleware: Array): Router; + put(name: string, path: string | RegExp, ...middleware: Array): Router; + put(path: string | RegExp, ...middleware: Array): Router; /** * HTTP delete method */ - delete(name: string, path: string, ...middleware: Array): Router; - delete(path: string, ...middleware: Array): Router; + delete(name: string, path: string | RegExp, ...middleware: Array): Router; + delete(path: string | RegExp, ...middleware: Array): Router; /** * Alias for `router.delete()` because delete is a reserved word */ - del(name: string, path: string, ...middleware: Array): Router; - del(path: string, ...middleware: Array): Router; + del(name: string, path: string | RegExp, ...middleware: Array): Router; + del(path: string | RegExp, ...middleware: Array): Router; /** * HTTP head method */ - head(name: string, path: string, ...middleware: Array): Router; - head(path: string, ...middleware: Array): Router; + head(name: string, path: string | RegExp, ...middleware: Array): Router; + head(path: string | RegExp, ...middleware: Array): Router; /** * HTTP options method */ - options(name: string, path: string, ...middleware: Array): Router; - options(path: string, ...middleware: Array): Router; + options(name: string, path: string | RegExp, ...middleware: Array): Router; + options(path: string | RegExp, ...middleware: Array): Router; /** * HTTP path method */ - patch(name: string, path: string, ...middleware: Array): Router; - patch(path: string, ...middleware: Array): Router; + patch(name: string, path: string | RegExp, ...middleware: Array): Router; + patch(path: string | RegExp, ...middleware: Array): Router; /** * Register route with all methods. */ - all(name: string, path: string, ...middleware: Array): Router; - all(path: string, ...middleware: Array): Router; + all(name: string, path: string | RegExp, ...middleware: Array): Router; + all(path: string | RegExp, ...middleware: Array): Router; /** * Set the path prefix for a Router instance that was already initialized. @@ -226,7 +224,7 @@ declare module "koa-router" { /** * Create and register a route. */ - register(path: string, methods: string[], middleware: Router.IMiddleware, opts?: Object): Layer; + register(path: string | RegExp, methods: string[], middleware: Router.IMiddleware, opts?: Object): Layer; /** * Lookup route with given `name`. @@ -254,7 +252,7 @@ declare module "koa-router" { /** * Generate URL from url pattern and given `params`. */ - static url(path: string, params: Object): string; + static url(path: string | RegExp, params: Object): string; } export = Router; diff --git a/libxslt/libxslt-tests.ts b/libxslt/libxslt-tests.ts new file mode 100644 index 0000000000..544269b11e --- /dev/null +++ b/libxslt/libxslt-tests.ts @@ -0,0 +1,102 @@ +/// +/// + +import * as libxslt from 'libxslt'; +import * as libxmljs from 'libxmljs'; + +const document: libxmljs.XMLDocument = libxslt.libxmljs.parseXmlString(''); + +let stylesheet: libxslt.Stylesheet; + +stylesheet = libxslt.parse(''); + +stylesheet = libxslt.parse(document); + +libxslt.parse('', (err, result) => { + if (err == null) { + stylesheet = result; + } +}); + +libxslt.parse(document, (err, result) => { + if (err == null) { + stylesheet = result; + } +}); + +libxslt.parseFile('/path/to/file', (err, result) => { + if (err == null) { + stylesheet = result; + } +}); + +let applyOptions: libxslt.ApplyOptions = {}; + +applyOptions = { + outputFormat: 'string', + noWrapParams: true +}; + +let transformedString: string; + +let transformedDocument: libxmljs.XMLDocument; + +transformedString = stylesheet.apply(''); + +transformedString = stylesheet.apply('', {}); + +let applyResult = stylesheet.apply('', {}, applyOptions); + +if (typeof applyResult === 'string') { + transformedString = applyResult; +} else { + transformedDocument = applyResult; +} + +stylesheet.apply('', {}, applyOptions, (err, result) => { + if (err != null) { + return; + } + + if (typeof result === 'string') { + transformedString = result; + } else { + transformedDocument = result; + } +}); + +transformedDocument = stylesheet.apply(document); + +transformedDocument = stylesheet.apply(document, {}); + +applyResult = stylesheet.apply(document, {}, applyOptions); + +if (typeof applyResult === 'string') { + transformedString = applyResult; +} else { + transformedDocument = applyResult; +} + +stylesheet.apply(document, {}, applyOptions, (err, result) => { + if (err != null) { + return; + } + + if (typeof result === 'string') { + transformedString = result; + } else { + transformedDocument = result; + } +}); + +stylesheet.applyToFile('/path/to/file', {}, applyOptions, (err, result) => { + if (err == null) { + transformedString = result; + } +}); + +stylesheet.applyToFile('/path/to/file', (err, result) => { + if (err == null) { + transformedString = result; + } +}); diff --git a/libxslt/libxslt.d.ts b/libxslt/libxslt.d.ts new file mode 100644 index 0000000000..0cfd4e1bcd --- /dev/null +++ b/libxslt/libxslt.d.ts @@ -0,0 +1,61 @@ +// Type definitions for node-libxslt +// Project: https://github.com/albanm/node-libxslt +// Definitions by: Alejandro Sánchez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'libxslt' { + import * as xmljs from 'libxmljs'; + + export const libxmljs: typeof xmljs; + + type OutputFormat = 'document' | 'string'; + + export interface ApplyOptions { + outputFormat?: OutputFormat; + noWrapParams?: boolean; + } + + type ApplyResult = string | xmljs.XMLDocument; + + type ApplyCallback = (err: Error, result: ApplyResult) => void; + + type ApplyStringCallback = (err: Error, result: string) => void; + + type ApplyDocumentCallback = (err: Error, result: xmljs.XMLDocument) => void; + + export interface Stylesheet { + apply(source: string, params?: Object): string; + + apply(source: string, params: Object, options: ApplyOptions): ApplyResult; + + apply(source: string, params: Object, options: ApplyOptions, callback: ApplyCallback): void; + + apply(source: string, callback: ApplyStringCallback): void; + + apply(source: xmljs.XMLDocument, params?: Object): xmljs.XMLDocument; + + apply(source: xmljs.XMLDocument, params: Object, options: ApplyOptions): ApplyResult; + + apply(source: xmljs.XMLDocument, params: Object, options: ApplyOptions, callback: ApplyCallback): void; + + apply(source: xmljs.XMLDocument, callback: ApplyDocumentCallback): void; + + applyToFile(sourcePath: string, params: Object, options: ApplyOptions, callback: ApplyStringCallback): void; + + applyToFile(sourcePath: string, callback: ApplyStringCallback): void; + } + + type ParseCallback = (err: Error, stylesheet: Stylesheet) => void; + + export function parse(source: string): Stylesheet; + + export function parse(source: string, callback: ParseCallback): void; + + export function parse(source: xmljs.XMLDocument): Stylesheet; + + export function parse(source: xmljs.XMLDocument, callback: ParseCallback): void; + + export function parseFile(sourcePath: string, callback: ParseCallback): void; +} diff --git a/masonry-layout/masonry-layout-tests.ts b/masonry-layout/masonry-layout-tests.ts index e83a898f54..65f629db10 100644 --- a/masonry-layout/masonry-layout-tests.ts +++ b/masonry-layout/masonry-layout-tests.ts @@ -1,48 +1,48 @@ -// test file for masonry-layout.d.ts - -/// -/// - -//import {Masonry} from "./masonry-layout.d.ts"; - -// responsive layouts -function testResponsiveLayouts() { - $('.grid').masonry({ - itemSelector: '.grid-item', - columnWidth: '.grid-sizer', - percentPosition: true - }); -} - -// recommended Options -function testRecommendedOptions() { - $('.grid').masonry({ - columnWidth: 200, - itemSelector: '.grid-item' - }); - - var msnry = new Masonry.Masonry('.grid', { - columnWidth: 200, - itemSelector: '.grid-item' - }); -} - -// extended Options -function testExtendedOptions() { - var msnry = new Masonry.Masonry('.grid', { - itemSelector: '.grid-item', - columnWidth: '.grid-sizer', - percentPosition: true, - gutter: '.gutter-sizer', - stamp: '.stamp', - fitWidth: true, - originLeft: true, - originTop: true, - containerStyle: { - position: 'relative' - }, - transitionDuration: '0.4s', - resize: true, - initLayout: true - }); -} +// test file for masonry-layout.d.ts + +/// +/// + +//import {Masonry} from "./masonry-layout.d.ts"; + +// responsive layouts +function testResponsiveLayouts() { + $('.grid').masonry({ + itemSelector: '.grid-item', + columnWidth: '.grid-sizer', + percentPosition: true + }); +} + +// recommended Options +function testRecommendedOptions() { + $('.grid').masonry({ + columnWidth: 200, + itemSelector: '.grid-item' + }); + + var msnry = new Masonry.Masonry('.grid', { + columnWidth: 200, + itemSelector: '.grid-item' + }); +} + +// extended Options +function testExtendedOptions() { + var msnry = new Masonry.Masonry('.grid', { + itemSelector: '.grid-item', + columnWidth: '.grid-sizer', + percentPosition: true, + gutter: '.gutter-sizer', + stamp: '.stamp', + fitWidth: true, + originLeft: true, + originTop: true, + containerStyle: { + position: 'relative' + }, + transitionDuration: '0.4s', + resize: true, + initLayout: true + }); +} diff --git a/masonry-layout/masonry-layout.d.ts b/masonry-layout/masonry-layout.d.ts index 0923a8f463..a76796096b 100644 --- a/masonry-layout/masonry-layout.d.ts +++ b/masonry-layout/masonry-layout.d.ts @@ -1,70 +1,70 @@ -// Type definitions for Masonry 4.0.0 -// Project: https://github.com/desandro/masonry -// Definitions by: Mark Wilson -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -// Modified from original definitions by: -// Travis Brown < https://github.com/warriorrocker> - -declare module Masonry { - - class Masonry implements MasonryGrid { - constructor(options?: MasonryOptions); - constructor(selector: string, options?: MasonryOptions); - } - - interface MasonryGrid { - masonry?(): void; - masonry?(eventName: string, listener: any): void; - - // layout - layout?(): void; - layoutItems?(items: Array, isStill?: boolean): void; - stamp?(elements: Array): void; - unstamp?(elements: Array): void; - - // add and remove items - appended?(elements: Array): void; - prepended?(elements: Array): void; - addItems?(elements: Array): void; - remove?(elements: Array): void; - - // events - on?(eventName: string, listener: any): void; - off?(eventName: string, listener: any): void; - once?(eventName: string, listener: any): void; - - // utilities - reloadItems?(): void; - destroy?(): void; - getItemElements?(): Array; - data?(element: Element): Masonry; - } - - interface MasonryOptions { - - // layout - itemSelector?: string; - columnWidth?: any; - percentPosition?: boolean; - gutter?: any; - stamp?: string; - fitWidth?: boolean; - originLeft?: boolean; - originTop?: boolean; - - // setup - containerStyle?: Object; - transitionDuration?: any; - resize?: boolean; - initLayout?: boolean; - } -} - -interface JQuery { - masonry(options?: Masonry.MasonryOptions): JQuery; -} - - +// Type definitions for Masonry 4.0.0 +// Project: https://github.com/desandro/masonry +// Definitions by: Mark Wilson +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +// Modified from original definitions by: +// Travis Brown < https://github.com/warriorrocker> + +declare module Masonry { + + class Masonry implements MasonryGrid { + constructor(options?: MasonryOptions); + constructor(selector: string, options?: MasonryOptions); + } + + interface MasonryGrid { + masonry?(): void; + masonry?(eventName: string, listener: any): void; + + // layout + layout?(): void; + layoutItems?(items: Array, isStill?: boolean): void; + stamp?(elements: Array): void; + unstamp?(elements: Array): void; + + // add and remove items + appended?(elements: Array): void; + prepended?(elements: Array): void; + addItems?(elements: Array): void; + remove?(elements: Array): void; + + // events + on?(eventName: string, listener: any): void; + off?(eventName: string, listener: any): void; + once?(eventName: string, listener: any): void; + + // utilities + reloadItems?(): void; + destroy?(): void; + getItemElements?(): Array; + data?(element: Element): Masonry; + } + + interface MasonryOptions { + + // layout + itemSelector?: string; + columnWidth?: any; + percentPosition?: boolean; + gutter?: any; + stamp?: string; + fitWidth?: boolean; + originLeft?: boolean; + originTop?: boolean; + + // setup + containerStyle?: Object; + transitionDuration?: any; + resize?: boolean; + initLayout?: boolean; + } +} + +interface JQuery { + masonry(options?: Masonry.MasonryOptions): JQuery; +} + + diff --git a/material-ui/material-ui.d.ts b/material-ui/material-ui.d.ts index 2913c0bd57..2430923d9d 100644 --- a/material-ui/material-ui.d.ts +++ b/material-ui/material-ui.d.ts @@ -513,8 +513,8 @@ declare namespace __MaterialUI { iconClassNameRight?: string; iconElementLeft?: React.ReactElement; iconElementRight?: React.ReactElement; - iconStyleRight?: string; - iconStyleLeft?: string; + iconStyleRight?: React.CSSProperties; + iconStyleLeft?: React.CSSProperties; onLeftIconButtonTouchTap?: TouchTapEventHandler; onRightIconButtonTouchTap?: TouchTapEventHandler; onTitleTouchTap?: TouchTapEventHandler; @@ -556,7 +556,7 @@ declare namespace __MaterialUI { errorStyle?: React.CSSProperties; errorText?: string; filter?: (searchText: string, key: string, item: AutoCompleteDataItem) => boolean; - floatingLabelText?: string; + floatingLabelText?: React.ReactNode; fullWidth?: boolean; hintText?: string; listStyle?: React.CSSProperties; diff --git a/mongoose-sequence/mongoose-sequence-tests.ts b/mongoose-sequence/mongoose-sequence-tests.ts new file mode 100644 index 0000000000..7962afeeb4 --- /dev/null +++ b/mongoose-sequence/mongoose-sequence-tests.ts @@ -0,0 +1,52 @@ +/// +/// +/// + +/** + * Based on the examples on: https://github.com/ramiel/mongoose-sequence + * Created by Linus Brolin . + */ + +import { SequenceDocument, SequenceOptions, SequenceSchema, Document, Schema, Model, model } from 'mongoose'; +import * as mongooseSequence from 'mongoose-sequence'; + +//#region Test Models +interface User extends SequenceDocument { + name: string; + country: string; + city: string; + inhabitant_number: number; +} + +const UserSchema: SequenceSchema = new Schema({ + name: String, + country: String, + city: String, + inhabitant_number: Number +}); + +let seqOpts: SequenceOptions = { id: 'inhabitant_seq', inc_field: 'inhabitant_number', reference_fields: ['country', 'city'] }; +UserSchema.plugin(mongooseSequence, seqOpts); + +let UserModel: Model = model('User', UserSchema); +//#endregion + +//#region Test Sequence +let user: User = new UserModel({ + name: 'Patrice', + country: 'France', + city: 'Paris' +}); +user.save(); +console.log(user.inhabitant_number); + +user.setNext('inhabitant_seq', function(err: any, user: User) { + if (err) { + console.log(err); + return; + } + if (user) { + console.log(user.inhabitant_number); + } +}); +//#endregion diff --git a/mongoose-sequence/mongoose-sequence.d.ts b/mongoose-sequence/mongoose-sequence.d.ts new file mode 100644 index 0000000000..b0dec033bd --- /dev/null +++ b/mongoose-sequence/mongoose-sequence.d.ts @@ -0,0 +1,36 @@ +// Type definitions for mongoose-sequence 3.0.2 +// Project: https://github.com/ramiel/mongoose-sequence +// Definitions by: Linus Brolin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'mongoose' { + export interface SequenceOptions { + inc_field: string; // The name of the field to increment. Mandatory, default is _id + id?: string; // Id of the sequence. Is mandatory only for scoped sequences but its use is strongly encouraged. + reference_fields?: Array; // The field to reference for a scoped counter. Optional + disable_hooks?: boolean; // If true, the counter will not be incremented on saving a new document. Default to false + collection_name?: string; // By default the collection name to mantain the status of the counters is counters. You can override it using this option + } + + export interface SequenceDocument extends Document { + setNext(sequenceId: string, callback: (err: any, res: SequenceDocument) => void): void; + } + + export interface SequenceSchema extends Schema { + plugin( + plugin: (schema: SequenceSchema, options: SequenceOptions) => void, + options: SequenceOptions + ): this; + + // overload for the default mongoose plugin function + plugin(plugin: (schema: Schema, options?: Object) => void, opts?: Object): this; + } +} + +declare module 'mongoose-sequence' { + import mongoose = require('mongoose'); + var _: (schema: mongoose.Schema, options?: Object) => void; + export = _; +} diff --git a/mongoose/README.md b/mongoose/README.md index 411f6ace2e..9becde8b89 100644 --- a/mongoose/README.md +++ b/mongoose/README.md @@ -49,7 +49,7 @@ interface IUser extends Document { data: any[]; } -var UserModel: Model = mongoose.model('User', UserSchema); +var UserModel: Model = model('User', UserSchema); var user = new UserModel({name: 'Jane'}); user.username; // IUser properties are available diff --git a/musicmetadata/musicmetadata.d.ts b/musicmetadata/musicmetadata.d.ts index b772468546..0e951f8d08 100644 --- a/musicmetadata/musicmetadata.d.ts +++ b/musicmetadata/musicmetadata.d.ts @@ -19,8 +19,8 @@ declare module "musicmetadata" { declare namespace MM { export interface Options { - duration: boolean; - fileSize: number; + duration?: boolean; + fileSize?: number; } export interface Metadata { @@ -45,4 +45,4 @@ declare namespace MM { format: string; data: Buffer; } -} \ No newline at end of file +} diff --git a/navigation/navigation-tests.ts b/navigation/navigation-tests.ts index c1b6e45ff9..52e6bfded4 100644 --- a/navigation/navigation-tests.ts +++ b/navigation/navigation-tests.ts @@ -37,10 +37,11 @@ namespace NavigationTests { person.navigated = (data) => {}; person.urlEncode = function urlEncode(state: Navigation.State, key: string, val: string, queryString: boolean): string { return queryString ? val.replace(/\s/g, '+') : encodeURIComponent(val); - } + }; person.urlDecode = function urlDecode(state: Navigation.State, key: string, val: string, queryString: boolean): string { return queryString ? val.replace(/\+/g, ' ') : decodeURIComponent(val); - } + }; + person.validate = (data: any) => data.id > 0; // Navigation Event var navigationListener = (oldState: Navigation.State, state: Navigation.State, data: any, asyncData: any) => { diff --git a/navigation/navigation.d.ts b/navigation/navigation.d.ts index ad3c1c8e23..1ae460a9f3 100644 --- a/navigation/navigation.d.ts +++ b/navigation/navigation.d.ts @@ -138,6 +138,12 @@ declare namespace Navigation { * @param queryString A value indicating the Url value's location */ urlDecode(state: State, key: string, val: string, queryString: boolean): string; + /** + * Validates the NavigationData before navigating to the new State + * @param data The new NavigationData + * @returns Validation success indicator + */ + validate(data: any): boolean; /** * Truncates the crumb trail whenever a repeated or initial State is * encountered @@ -178,9 +184,9 @@ declare namespace Navigation { */ getHref(url: string): string; /** - * Gets a Url from the anchor + * Gets a Url from the anchor or location */ - getUrl(anchor: HTMLAnchorElement): string; + getUrl(hrefElement: HTMLAnchorElement | Location): string; /** * Removes browser history event listeners */ @@ -230,9 +236,9 @@ declare namespace Navigation { */ getHref(url: string): string; /** - * Gets a Url from the anchor + * Gets a Url from the anchor or location */ - getUrl(anchor: HTMLAnchorElement): string; + getUrl(hrefElement: HTMLAnchorElement | Location): string; /** * Removes a listener for the hashchange event */ @@ -281,9 +287,9 @@ declare namespace Navigation { */ getHref(url: string): string; /** - * Gets a Url from the anchor + * Gets a Url from the anchor or location */ - getUrl(anchor: HTMLAnchorElement): string; + getUrl(hrefElement: HTMLAnchorElement | Location): string; /** * Removes a listener for the popstate event */ @@ -381,10 +387,6 @@ declare namespace Navigation { * Crumb first */ crumbs: Crumb[]; - /** - * Gets the crumb trail - */ - crumbTrail: string[]; /** * Gets the next crumb */ diff --git a/ncp/ncp-tests.ts b/ncp/ncp-tests.ts index f1ce04c21e..06f818e0f8 100644 --- a/ncp/ncp-tests.ts +++ b/ncp/ncp-tests.ts @@ -8,6 +8,9 @@ opts = {}; opts = { filter: /abc/ }; +opts = { + filter: (filename: string) => true +}; opts = { transform: (read: NodeJS.ReadableStream, write: NodeJS.WritableStream) => { diff --git a/ncp/ncp.d.ts b/ncp/ncp.d.ts index 50393195e6..b76fa5c912 100644 --- a/ncp/ncp.d.ts +++ b/ncp/ncp.d.ts @@ -10,7 +10,7 @@ declare module 'ncp' { function ncp (source: string, destination: string, options: Options, callback: (err: Error) => void): void; interface Options { - filter? : RegExp; + filter? : RegExp | ((filename: string) => boolean); transform? : (read: NodeJS.ReadableStream, write: NodeJS.WritableStream) => void; clobber? : boolean; stopOnErr? : boolean; diff --git a/nock/nock-tests.ts b/nock/nock-tests.ts index bc936a05b8..ffb456b420 100644 --- a/nock/nock-tests.ts +++ b/nock/nock-tests.ts @@ -97,6 +97,12 @@ inst = inst.log(() => { }); +inst = inst.delay(2000); +inst = inst.delayBody(2000); +inst = inst.delayConnection(2000); +inst.getTotalDelay(); +inst = inst.socketDelay(2000); + inst.done(); bool = inst.isDone(); inst.restore(); diff --git a/nock/nock.d.ts b/nock/nock.d.ts index b82721da78..615ec0d3ca 100644 --- a/nock/nock.d.ts +++ b/nock/nock.d.ts @@ -96,7 +96,10 @@ declare module "nock" { log(out: () => void): Scope; delay(timeMs: number): Scope; + delayBody(timeMs: number): Scope; delayConnection(timeMs: number): Scope; + getTotalDelay(): number; + socketDelay(timeMs: number): Scope; times(repeats: number): Scope; once(): Scope; diff --git a/node-7z/node-7z-tests.ts b/node-7z/node-7z-tests.ts new file mode 100644 index 0000000000..7de496f683 --- /dev/null +++ b/node-7z/node-7z-tests.ts @@ -0,0 +1,20 @@ +/// + +import Zip = require('node-7z'); // Name the class as you want! +var myTask = new Zip(); +myTask.extractFull('myArchive.7z', 'destination', { p: 'myPassword' }) + +// Equivalent to `on('data', function (files) { // ... });` +.progress(function (files: Array): void { + console.log('Some files are extracted: %s', files); +}) + +// When all is done +.then(function () { + console.log('Extracting done!'); +}) + +// On error +.catch(function (err: any) { + console.error(err); +}); diff --git a/node-7z/node-7z.d.ts b/node-7z/node-7z.d.ts new file mode 100644 index 0000000000..506b3da952 --- /dev/null +++ b/node-7z/node-7z.d.ts @@ -0,0 +1,39 @@ +// Type definitions for node-7z v0.4.1 +// Project: https://github.com/quentinrossetti/node-7z +// Definitions by: Erik Rothoff Andersson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/ + +declare module "node-7z" { + // node-7z uses `when` promises which have a progress method, however they are deprecated + // internally node-7z uses the progress events to emit files that are extracted, + // (also the progress event emits an array of strings, which doesn't correlate with any promise) + // so instead of patching `when` promises I'm extending the generic Promise for use internally + interface PromiseWithProgress extends Promise { + progress(progress: (files: Array) => void): this; + } + + // Options are mapped to the 7z program so there is no idea to define all possible types here + interface CommandLineSwitches { + raw?: Array; + [key: string]: any + } + + interface FileSpec { + path: string; + type: string; + method: string; + physicalSize: number; + } + + class Zip { + add(archive: string, files: string | Array, options: CommandLineSwitches): PromiseWithProgress<{}>; + delete(archive: string, files: string | Array, options: CommandLineSwitches): PromiseWithProgress<{}>; + extract(archive: string, dest: string, options: CommandLineSwitches): PromiseWithProgress<{}>; + extractFull(archive: string, dest: string, options: CommandLineSwitches): PromiseWithProgress<{}>; + list(archive: string, options: CommandLineSwitches): PromiseWithProgress; + test(archive: string, options: CommandLineSwitches): PromiseWithProgress<{}>; + update(archive: string, files: string | Array, options: CommandLineSwitches): PromiseWithProgress<{}>; + } + + export = Zip; +} diff --git a/node/node-0.10.d.ts b/node/node-0.10.d.ts index 80b46a475c..9055ec82a7 100644 --- a/node/node-0.10.d.ts +++ b/node/node-0.10.d.ts @@ -688,6 +688,7 @@ declare module "child_process" { pid: number; kill(signal?: string): void; send(message: any, sendHandle: any): void; + connected: boolean; disconnect(): void; } diff --git a/node/node-0.11.d.ts b/node/node-0.11.d.ts index 212768c21a..91cfef468d 100644 --- a/node/node-0.11.d.ts +++ b/node/node-0.11.d.ts @@ -611,6 +611,7 @@ declare module "child_process" { pid: number; kill(signal?: string): void; send(message: any, sendHandle: any): void; + connected: boolean; disconnect(): void; } diff --git a/node/node-0.12.d.ts b/node/node-0.12.d.ts index 49091419a8..4459ebe96a 100644 --- a/node/node-0.12.d.ts +++ b/node/node-0.12.d.ts @@ -829,6 +829,7 @@ declare module "child_process" { pid: number; kill(signal?: string): void; send(message: any, sendHandle?: any): void; + connected: boolean; disconnect(): void; unref(): void; } diff --git a/node/node-0.8.8.d.ts b/node/node-0.8.8.d.ts index 321c386655..2be7c6aae3 100644 --- a/node/node-0.8.8.d.ts +++ b/node/node-0.8.8.d.ts @@ -545,6 +545,7 @@ declare module "child_process" { pid: number; kill(signal?: string): void; send(message: any, sendHandle: any): void; + connected: boolean; disconnect(): void; } diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 9db708b910..2de910db67 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -24,22 +24,43 @@ import * as string_decoder from "string_decoder"; // Specifically test buffer module regression. import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer"; -assert(1 + 1 - 2 === 0, "The universe isn't how it should."); +////////////////////////////////////////////////////////// +/// Assert Tests : https://nodejs.org/api/assert.html /// +////////////////////////////////////////////////////////// -assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP"); +namespace assert_tests{ + { + assert(1 + 1 - 2 === 0, "The universe isn't how it should."); + + assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP"); + + assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator"); + + assert.doesNotThrow(() => { + const b = false; + if (b) { throw "a hammer at your face"; } + }, undefined, "What the...*crunch*"); + + assert.equal(3, "3", "uses == comparator"); -assert.equal(3, "3", "uses == comparator"); - -assert.notStrictEqual(2, "2", "uses === comparator"); - -assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses === comparator"); - -assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); - -assert.doesNotThrow(() => { - const b = false; - if (b) { throw "a hammer at your face"; } -}, undefined, "What the...*crunch*"); + assert.fail(1, 2, undefined, '>'); + + assert.ifError(0); + + assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator"); + + assert.notEqual(1, 2, "uses != comparator"); + + assert.notStrictEqual(2, "2", "uses === comparator"); + + assert.ok(true); + assert.ok(1); + + assert.strictEqual(1, 1, "uses === comparator"); + + assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); + } +} //////////////////////////////////////////////////// /// Events tests : http://nodejs.org/api/events.html @@ -87,59 +108,75 @@ namespace events_tests { result = emitter.emit(event, any, any); result = emitter.emit(event, any, any, any); } + + { + class Networker extends events.EventEmitter { + constructor() { + super(); + + this.emit("mingling"); + } + } + } } //////////////////////////////////////////////////// /// File system tests : http://nodejs.org/api/fs.html //////////////////////////////////////////////////// -fs.writeFile("thebible.txt", - "Do unto others as you would have them do unto you.", - assert.ifError); -fs.write(1234, "test"); - -fs.writeFile("Harry Potter", - "\"You be wizzing, Harry,\" jived Dumbledore.", +namespace fs_tests { { - encoding: "ascii" - }, - assert.ifError); + fs.writeFile("thebible.txt", + "Do unto others as you would have them do unto you.", + assert.ifError); -var content: string, - buffer: Buffer; + fs.write(1234, "test"); -content = fs.readFileSync('testfile', 'utf8'); -content = fs.readFileSync('testfile', {encoding : 'utf8'}); -buffer = fs.readFileSync('testfile'); -buffer = fs.readFileSync('testfile', {flag : 'r'}); -fs.readFile('testfile', 'utf8', (err, data) => content = data); -fs.readFile('testfile', {encoding : 'utf8'}, (err, data) => content = data); -fs.readFile('testfile', (err, data) => buffer = data); -fs.readFile('testfile', {flag : 'r'}, (err, data) => buffer = data); - -class Networker extends events.EventEmitter { - constructor() { - super(); - - this.emit("mingling"); + fs.writeFile("Harry Potter", + "\"You be wizzing, Harry,\" jived Dumbledore.", + { + encoding: "ascii" + }, + assert.ifError); } + + { + var content: string; + var buffer: Buffer; + + content = fs.readFileSync('testfile', 'utf8'); + content = fs.readFileSync('testfile', {encoding : 'utf8'}); + buffer = fs.readFileSync('testfile'); + buffer = fs.readFileSync('testfile', {flag : 'r'}); + fs.readFile('testfile', 'utf8', (err, data) => content = data); + fs.readFile('testfile', {encoding : 'utf8'}, (err, data) => content = data); + fs.readFile('testfile', (err, data) => buffer = data); + fs.readFile('testfile', {flag : 'r'}, (err, data) => buffer = data); + } + + { + var errno: number; + fs.readFile('testfile', (err, data) => { + if (err && err.errno) { + errno = err.errno; + } + }); + } + + { + fs.mkdtemp('/tmp/foo-', (err, folder) => { + console.log(folder); + // Prints: /tmp/foo-itXde2 + }); + } + + { + var tempDir: string; + tempDir = fs.mkdtempSync('/tmp/foo-'); + } + } -var errno: number; -fs.readFile('testfile', (err, data) => { - if (err && err.errno) { - errno = err.errno; - } -}); - -fs.mkdtemp('/tmp/foo-', (err, folder) => { - console.log(folder); - // Prints: /tmp/foo-itXde2 -}); - -var tempDir: string; -tempDir = fs.mkdtempSync('/tmp/foo-'); - /////////////////////////////////////////////////////// /// Buffer tests : https://nodejs.org/api/buffer.html /////////////////////////////////////////////////////// @@ -235,23 +272,36 @@ function bufferTests() { /// Url tests : http://nodejs.org/api/url.html //////////////////////////////////////////////////// -url.format(url.parse('http://www.example.com/xyz')); +namespace url_tests { + { + url.format(url.parse('http://www.example.com/xyz')); + + // https://google.com/search?q=you're%20a%20lizard%2C%20gary + url.format({ + protocol: 'https', + host: "google.com", + pathname: 'search', + query: { q: "you're a lizard, gary" } + }); + } -// https://google.com/search?q=you're%20a%20lizard%2C%20gary -url.format({ - protocol: 'https', - host: "google.com", - pathname: 'search', - query: { q: "you're a lizard, gary" } -}); + { + var helloUrl = url.parse('http://example.com/?hello=world', true) + assert.equal(helloUrl.query.hello, 'world'); + } +} -var helloUrl = url.parse('http://example.com/?hello=world', true) -assert.equal(helloUrl.query.hello, 'world'); +///////////////////////////////////////////////////// +/// util tests : https://nodejs.org/api/util.html /// +///////////////////////////////////////////////////// - -// Old and new util.inspect APIs -util.inspect(["This is nice"], false, 5); -util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); +namespace util_tests { + { + // Old and new util.inspect APIs + util.inspect(["This is nice"], false, 5); + util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); + } +} //////////////////////////////////////////////////// /// Stream tests : http://nodejs.org/api/stream.html @@ -266,51 +316,57 @@ function stream_readable_pipe_test() { r.close(); } -//////////////////////////////////////////////////// -/// Crypto tests : http://nodejs.org/api/crypto.html -//////////////////////////////////////////////////// +//////////////////////////////////////////////////////// +/// Crypto tests : http://nodejs.org/api/crypto.html /// +//////////////////////////////////////////////////////// -var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); +namespace crypto_tests { + { + var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); + } + + { + let hmac: crypto.Hmac; + (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { + let hash: Buffer | string = hmac.read(); + }); + } + + { + //crypto_cipher_decipher_string_test + let key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let clearText: string = "This is the clear text."; + let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherText: string = cipher.update(clearText, "utf8", "hex"); + cipherText += cipher.final("hex"); -{ - let hmac: crypto.Hmac; - (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { - let hash: Buffer|string = hmac.read(); - }); -} + let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let clearText2: string = decipher.update(cipherText, "hex", "utf8"); + clearText2 += decipher.final("utf8"); -function crypto_cipher_decipher_string_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:string = "This is the clear text."; - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherText:string = cipher.update(clearText, "utf8", "hex"); - cipherText += cipher.final("hex"); + assert.equal(clearText2, clearText); + } - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var clearText2:string = decipher.update(cipherText, "hex", "utf8"); - clearText2 += decipher.final("utf8"); + { + //crypto_cipher_decipher_buffer_test + let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let clearText: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); + let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherBuffers: Buffer[] = []; + cipherBuffers.push(cipher.update(clearText)); + cipherBuffers.push(cipher.final()); - assert.equal(clearText2, clearText); -} + let cipherText: Buffer = Buffer.concat(cipherBuffers); -function crypto_cipher_decipher_buffer_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherBuffers:Buffer[] = []; - cipherBuffers.push(cipher.update(clearText)); - cipherBuffers.push(cipher.final()); + let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let decipherBuffers: Buffer[] = []; + decipherBuffers.push(decipher.update(cipherText)); + decipherBuffers.push(decipher.final()); - var cipherText:Buffer = Buffer.concat(cipherBuffers); + let clearText2: Buffer = Buffer.concat(decipherBuffers); - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var decipherBuffers:Buffer[] = []; - decipherBuffers.push(decipher.update(cipherText)); - decipherBuffers.push(decipher.final()); - - var clearText2:Buffer = Buffer.concat(decipherBuffers); - - assert.deepEqual(clearText2, clearText); + assert.deepEqual(clearText2, clearText); + } } //////////////////////////////////////////////////// @@ -329,27 +385,18 @@ var tlsOpts: tls.TlsOptions = { }; var tlsSocket = tls.connect(tlsOpts); - +//////////////////////////////////////////////////// +/// Http tests : http://nodejs.org/api/http.html /// //////////////////////////////////////////////////// -// Make sure .listen() and .close() retuern a Server instance -http.createServer().listen(0).close().address(); -net.createServer().listen(0).close().address(); - -var request = http.request('http://0.0.0.0'); -request.once('error', function () {}); -request.setNoDelay(true); -request.abort(); - -//////////////////////////////////////////////////// -/// Http tests : http://nodejs.org/api/http.html -//////////////////////////////////////////////////// namespace http_tests { - // Status codes - var code = 100; - var codeMessage = http.STATUS_CODES['400']; - var codeMessage = http.STATUS_CODES[400]; + { + // Status codes + var codeMessage = http.STATUS_CODES['400']; + var codeMessage = http.STATUS_CODES[400]; + } + { var agent: http.Agent = new http.Agent({ keepAlive: true, keepAliveMsecs: 10000, @@ -359,20 +406,29 @@ namespace http_tests { var agent: http.Agent = http.globalAgent; - http.request({ - agent: false - }); - http.request({ - agent: agent - }); - http.request({ - agent: undefined - }); + http.request({agent: false}); + http.request({agent: agent}); + http.request({agent: undefined}); + } + + { + // Make sure .listen() and .close() retuern a Server instance + http.createServer().listen(0).close().address(); + net.createServer().listen(0).close().address(); + } + + { + var request = http.request('http://0.0.0.0'); + request.once('error', function() { }); + request.setNoDelay(true); + request.abort(); + } } -//////////////////////////////////////////////////// -/// Https tests : http://nodejs.org/api/https.html -//////////////////////////////////////////////////// +////////////////////////////////////////////////////// +/// Https tests : http://nodejs.org/api/https.html /// +////////////////////////////////////////////////////// + namespace https_tests { var agent: https.Agent = new https.Agent({ keepAlive: true, @@ -416,11 +472,13 @@ namespace tty_tests { /// Dgram tests : http://nodejs.org/api/dgram.html //////////////////////////////////////////////////// -var ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => { -}); -var ai: dgram.AddressInfo = ds.address(); -ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { -}); +namespace dgram_tests { + var ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => { + }); + var ai: dgram.AddressInfo = ds.address(); + ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { + }); +} //////////////////////////////////////////////////// ///Querystring tests : https://nodejs.org/api/querystring.html @@ -516,82 +574,82 @@ namespace path_tests { path.isAbsolute('.') // false path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb') -// returns -// '..\\..\\impl\\bbb' + // returns + // '..\\..\\impl\\bbb' path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb') -// returns -// '../../impl/bbb' + // returns + // '../../impl/bbb' path.dirname('/foo/bar/baz/asdf/quux') -// returns -// '/foo/bar/baz/asdf' + // returns + // '/foo/bar/baz/asdf' path.basename('/foo/bar/baz/asdf/quux.html') -// returns -// 'quux.html' + // returns + // 'quux.html' path.basename('/foo/bar/baz/asdf/quux.html', '.html') -// returns -// 'quux' + // returns + // 'quux' path.extname('index.html') -// returns -// '.html' + // returns + // '.html' path.extname('index.coffee.md') -// returns -// '.md' + // returns + // '.md' path.extname('index.') -// returns -// '.' + // returns + // '.' path.extname('index') -// returns -// '' + // returns + // '' 'foo/bar/baz'.split(path.sep) -// returns -// ['foo', 'bar', 'baz'] + // returns + // ['foo', 'bar', 'baz'] 'foo\\bar\\baz'.split(path.sep) -// returns -// ['foo', 'bar', 'baz'] + // returns + // ['foo', 'bar', 'baz'] console.log(process.env.PATH) -// '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin' + // '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin' process.env.PATH.split(path.delimiter) -// returns -// ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin'] + // returns + // ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin'] console.log(process.env.PATH) -// 'C:\Windows\system32;C:\Windows;C:\Program Files\nodejs\' + // 'C:\Windows\system32;C:\Windows;C:\Program Files\nodejs\' process.env.PATH.split(path.delimiter) -// returns -// ['C:\Windows\system32', 'C:\Windows', 'C:\Program Files\nodejs\'] + // returns + // ['C:\Windows\system32', 'C:\Windows', 'C:\Program Files\nodejs\'] path.parse('/home/user/dir/file.txt') -// returns -// { -// root : "/", -// dir : "/home/user/dir", -// base : "file.txt", -// ext : ".txt", -// name : "file" -// } + // returns + // { + // root : "/", + // dir : "/home/user/dir", + // base : "file.txt", + // ext : ".txt", + // name : "file" + // } path.parse('C:\\path\\dir\\index.html') -// returns -// { -// root : "C:\", -// dir : "C:\path\dir", -// base : "index.html", -// ext : ".html", -// name : "index" -// } + // returns + // { + // root : "C:\", + // dir : "C:\path\dir", + // base : "index.html", + // ext : ".html", + // name : "index" + // } path.format({ root : "/", @@ -600,8 +658,8 @@ namespace path_tests { ext : ".txt", name : "file" }); -// returns -// '/home/user/dir/file.txt' + // returns + // '/home/user/dir/file.txt' } //////////////////////////////////////////////////// @@ -717,20 +775,28 @@ namespace string_decoder_tests { /// Child Process tests: https://nodejs.org/api/child_process.html /// ////////////////////////////////////////////////////////////////////// -childProcess.exec("echo test"); -childProcess.spawnSync("echo test"); +namespace child_process_tests { + { + childProcess.exec("echo test"); + childProcess.spawnSync("echo test"); + } +} ////////////////////////////////////////////////////////////////////// /// cluster tests: https://nodejs.org/api/cluster.html /// ////////////////////////////////////////////////////////////////////// -cluster.fork(); -Object.keys(cluster.workers).forEach(key => { - const worker = cluster.workers[key]; - if (worker.isDead()) { - console.log('worker %d is dead', worker.process.pid); +namespace cluster_tests { + { + cluster.fork(); + Object.keys(cluster.workers).forEach(key => { + const worker = cluster.workers[key]; + if (worker.isDead()) { + console.log('worker %d is dead', worker.process.pid); + } + }); } -}); +} //////////////////////////////////////////////////// /// os tests : https://nodejs.org/api/os.html @@ -839,4 +905,42 @@ namespace errors_tests { const myObject = {}; Error.captureStackTrace(myObject); } -} \ No newline at end of file +} + +/////////////////////////////////////////////////////////// +/// Process Tests : https://nodejs.org/api/process.html /// +/////////////////////////////////////////////////////////// + +import * as p from "process"; +namespace process_tests { + { + var eventEmitter: events.EventEmitter; + eventEmitter = process; // Test that process implements EventEmitter... + + var _p: NodeJS.Process = process; + _p = p; + } +} + +/////////////////////////////////////////////////////////// +/// Console Tests : https://nodejs.org/api/console.html /// +/////////////////////////////////////////////////////////// + +import * as c from "console"; +namespace console_tests { + { + var _c: Console = console; + _c = c; + } +} + +/////////////////////////////////////////////////// +/// Net Tests : https://nodejs.org/api/net.html /// +/////////////////////////////////////////////////// + +namespace net_tests { + { + // Make sure .listen() and .close() retuern a Server instance + net.createServer().listen(0).close().address(); + } +} diff --git a/node/node-4.d.ts b/node/node-4.d.ts index 4516331d7d..f05444336d 100644 --- a/node/node-4.d.ts +++ b/node/node-4.d.ts @@ -430,7 +430,7 @@ declare namespace NodeJS { interface NodeBuffer extends Uint8Array { write(string: string, offset?: number, length?: number, encoding?: string): number; toString(encoding?: string, start?: number, end?: number): string; - toJSON(): any; + toJSON(): {type: 'Buffer', data: any[]}; equals(otherBuffer: Buffer): boolean; compare(otherBuffer: Buffer): number; copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; @@ -1036,6 +1036,7 @@ declare module "child_process" { pid: number; kill(signal?: string): void; send(message: any, sendHandle?: any): void; + connected: boolean; disconnect(): void; unref(): void; } @@ -2402,8 +2403,63 @@ declare module "constants" { export var W_OK: number; export var X_OK: number; export var UV_UDP_REUSEADDR: number; + export var EDQUOT: number; + export var EMULTIHOP: number; + export var ESTALE: number; + export var O_DIRECT: number; + export var O_DIRECTORY: number; + export var O_NOCTTY: number; + export var O_NOFOLLOW: number; + export var O_NONBLOCK: number; + export var O_SYNC: number; + export var SIGALRM: number; + export var SIGBUS: number; + export var SIGCHLD: number; + export var SIGCONT: number; + export var SIGIO: number; + export var SIGIOT: number; + export var SIGPIPE: number; + export var SIGPOLL: number; + export var SIGPROF: number; + export var SIGPWR: number; + export var SIGQUIT: number; + export var SIGSTKFLT: number; + export var SIGSTOP: number; + export var SIGSYS: number; + export var SIGTRAP: number; + export var SIGTSTP: number; + export var SIGTTIN: number; + export var SIGTTOU: number; + export var SIGUNUSED: number; + export var SIGURG: number; + export var SIGUSR1: number; + export var SIGUSR2: number; + export var SIGVTALRM: number; + export var SIGXCPU: number; + export var SIGXFSZ: number; + export var S_IFBLK: number; + export var S_IFIFO: number; + export var S_IFSOCK: number; + export var S_IRGRP: number; + export var S_IROTH: number; + export var S_IRUSR: number; + export var S_IRWXG: number; + export var S_IRWXO: number; + export var S_IRWXU: number; + export var S_IWGRP: number; + export var S_IWOTH: number; + export var S_IWUSR: number; + export var S_IXGRP: number; + export var S_IXOTH: number; + export var S_IXUSR: number; + export var defaultCipherList: string; + export var defaultCoreCipherList: string; } declare module "process" { export = process; } + +declare module "console" { + export = console; +} diff --git a/node/node-tests.ts b/node/node-tests.ts index af214a4385..e0600d936d 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -21,26 +21,48 @@ import * as os from "os"; import * as vm from "vm"; import * as string_decoder from "string_decoder"; import * as stream from "stream"; +import * as timers from "timers"; // Specifically test buffer module regression. import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer"; -assert(1 + 1 - 2 === 0, "The universe isn't how it should."); +////////////////////////////////////////////////////////// +/// Assert Tests : https://nodejs.org/api/assert.html /// +////////////////////////////////////////////////////////// -assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP"); +namespace assert_tests{ + { + assert(1 + 1 - 2 === 0, "The universe isn't how it should."); + + assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP"); + + assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator"); + + assert.doesNotThrow(() => { + const b = false; + if (b) { throw "a hammer at your face"; } + }, undefined, "What the...*crunch*"); + + assert.equal(3, "3", "uses == comparator"); -assert.equal(3, "3", "uses == comparator"); - -assert.notStrictEqual(2, "2", "uses === comparator"); - -assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses === comparator"); - -assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); - -assert.doesNotThrow(() => { - const b = false; - if (b) { throw "a hammer at your face"; } -}, undefined, "What the...*crunch*"); + assert.fail(1, 2, undefined, '>'); + + assert.ifError(0); + + assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator"); + + assert.notEqual(1, 2, "uses != comparator"); + + assert.notStrictEqual(2, "2", "uses === comparator"); + + assert.ok(true); + assert.ok(1); + + assert.strictEqual(1, 1, "uses === comparator"); + + assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); + } +} //////////////////////////////////////////////////// /// Events tests : http://nodejs.org/api/events.html @@ -96,75 +118,110 @@ namespace events_tests { result = emitter.eventNames(); } + + { + class Networker extends events.EventEmitter { + constructor() { + super(); + + this.emit("mingling"); + } + } + } } //////////////////////////////////////////////////// /// File system tests : http://nodejs.org/api/fs.html //////////////////////////////////////////////////// -fs.writeFile("thebible.txt", - "Do unto others as you would have them do unto you.", - assert.ifError); -fs.write(1234, "test"); - -fs.writeFile("Harry Potter", - "\"You be wizzing, Harry,\" jived Dumbledore.", +namespace fs_tests { { - encoding: "ascii" - }, - assert.ifError); + fs.writeFile("thebible.txt", + "Do unto others as you would have them do unto you.", + assert.ifError); + + fs.write(1234, "test"); + + fs.writeFile("Harry Potter", + "\"You be wizzing, Harry,\" jived Dumbledore.", + { + encoding: "ascii" + }, + assert.ifError); + } -var content: string, - buffer: Buffer; - -content = fs.readFileSync('testfile', 'utf8'); -content = fs.readFileSync('testfile', {encoding : 'utf8'}); -buffer = fs.readFileSync('testfile'); -buffer = fs.readFileSync('testfile', {flag : 'r'}); -fs.readFile('testfile', 'utf8', (err, data) => content = data); -fs.readFile('testfile', {encoding : 'utf8'}, (err, data) => content = data); -fs.readFile('testfile', (err, data) => buffer = data); -fs.readFile('testfile', {flag : 'r'}, (err, data) => buffer = data); - -class Networker extends events.EventEmitter { - constructor() { - super(); - - this.emit("mingling"); + { + var content: string; + var buffer: Buffer; + + content = fs.readFileSync('testfile', 'utf8'); + content = fs.readFileSync('testfile', {encoding : 'utf8'}); + buffer = fs.readFileSync('testfile'); + buffer = fs.readFileSync('testfile', {flag : 'r'}); + fs.readFile('testfile', 'utf8', (err, data) => content = data); + fs.readFile('testfile', {encoding : 'utf8'}, (err, data) => content = data); + fs.readFile('testfile', (err, data) => buffer = data); + fs.readFile('testfile', {flag : 'r'}, (err, data) => buffer = data); + } + + { + var errno: string; + fs.readFile('testfile', (err, data) => { + if (err && err.errno) { + errno = err.errno; + } + }); + } + + { + fs.mkdtemp('/tmp/foo-', (err, folder) => { + console.log(folder); + // Prints: /tmp/foo-itXde2 + }); + } + + { + var tempDir: string; + tempDir = fs.mkdtempSync('/tmp/foo-'); + } + + { + fs.watch('/tmp/foo-', (event, filename) => { + console.log(event, filename); + }); + + fs.watch('/tmp/foo-', 'utf8', (event, filename) => { + console.log(event, filename); + }); + + fs.watch('/tmp/foo-', { + recursive: true, + persistent: true, + encoding: 'utf8' + }, (event, filename) => { + console.log(event, filename); + }); + } + + { + fs.access('/path/to/folder', (err) => {}); + + fs.access(Buffer.from(''), (err) => {}); + + fs.access('/path/to/folder', fs.constants.F_OK | fs.constants.R_OK, (err) => {}); + + fs.access(Buffer.from(''), fs.constants.F_OK | fs.constants.R_OK, (err) => {}); + + fs.accessSync('/path/to/folder'); + + fs.accessSync(Buffer.from('')); + + fs.accessSync('path/to/folder', fs.constants.W_OK | fs.constants.X_OK); + + fs.accessSync(Buffer.from(''), fs.constants.W_OK | fs.constants.X_OK); } } -var errno: number; -fs.readFile('testfile', (err, data) => { - if (err && err.errno) { - errno = err.errno; - } -}); - -fs.mkdtemp('/tmp/foo-', (err, folder) => { - console.log(folder); - // Prints: /tmp/foo-itXde2 -}); - -var tempDir: string; -tempDir = fs.mkdtempSync('/tmp/foo-'); - -fs.watch('/tmp/foo-', (event, filename) => { - console.log(event, filename); -}); - -fs.watch('/tmp/foo-', 'utf8', (event, filename) => { - console.log(event, filename); -}); - -fs.watch('/tmp/foo-', { - recursive: true, - persistent: true, - encoding: 'utf8' -}, (event, filename) => { - console.log(event, filename); -}); - /////////////////////////////////////////////////////// /// Buffer tests : https://nodejs.org/api/buffer.html /////////////////////////////////////////////////////// @@ -263,9 +320,11 @@ function bufferTests() { let buffer = new Buffer('123'); let val: [number, number]; + /* comment out for --target es5 for (let entry of buffer.entries()) { val = entry; } + */ } { @@ -286,18 +345,22 @@ function bufferTests() { let buffer = new Buffer('123'); let val: number; + /* comment out for --target es5 for (let key of buffer.keys()) { val = key; } + */ } { let buffer = new Buffer('123'); let val: number; + /* comment out for --target es5 for (let value of buffer.values()) { val = value; } + */ } // Imported Buffer from buffer module works properly @@ -320,23 +383,36 @@ function bufferTests() { /// Url tests : http://nodejs.org/api/url.html //////////////////////////////////////////////////// -url.format(url.parse('http://www.example.com/xyz')); +namespace url_tests { + { + url.format(url.parse('http://www.example.com/xyz')); + + // https://google.com/search?q=you're%20a%20lizard%2C%20gary + url.format({ + protocol: 'https', + host: "google.com", + pathname: 'search', + query: { q: "you're a lizard, gary" } + }); + } -// https://google.com/search?q=you're%20a%20lizard%2C%20gary -url.format({ - protocol: 'https', - host: "google.com", - pathname: 'search', - query: { q: "you're a lizard, gary" } -}); + { + var helloUrl = url.parse('http://example.com/?hello=world', true) + assert.equal(helloUrl.query.hello, 'world'); + } +} -var helloUrl = url.parse('http://example.com/?hello=world', true) -assert.equal(helloUrl.query.hello, 'world'); +///////////////////////////////////////////////////// +/// util tests : https://nodejs.org/api/util.html /// +///////////////////////////////////////////////////// - -// Old and new util.inspect APIs -util.inspect(["This is nice"], false, 5); -util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); +namespace util_tests { + { + // Old and new util.inspect APIs + util.inspect(["This is nice"], false, 5); + util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); + } +} //////////////////////////////////////////////////// /// Stream tests : http://nodejs.org/api/stream.html @@ -415,51 +491,57 @@ function simplified_stream_ctor_test() { }) } -//////////////////////////////////////////////////// -/// Crypto tests : http://nodejs.org/api/crypto.html -//////////////////////////////////////////////////// +//////////////////////////////////////////////////////// +/// Crypto tests : http://nodejs.org/api/crypto.html /// +//////////////////////////////////////////////////////// -var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); +namespace crypto_tests { + { + var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); + } + + { + let hmac: crypto.Hmac; + (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { + let hash: Buffer | string = hmac.read(); + }); + } + + { + //crypto_cipher_decipher_string_test + let key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let clearText: string = "This is the clear text."; + let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherText: string = cipher.update(clearText, "utf8", "hex"); + cipherText += cipher.final("hex"); -{ - let hmac: crypto.Hmac; - (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { - let hash: Buffer|string = hmac.read(); - }); -} + let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let clearText2: string = decipher.update(cipherText, "hex", "utf8"); + clearText2 += decipher.final("utf8"); -function crypto_cipher_decipher_string_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:string = "This is the clear text."; - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherText:string = cipher.update(clearText, "utf8", "hex"); - cipherText += cipher.final("hex"); + assert.equal(clearText2, clearText); + } - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var clearText2:string = decipher.update(cipherText, "hex", "utf8"); - clearText2 += decipher.final("utf8"); + { + //crypto_cipher_decipher_buffer_test + let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let clearText: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); + let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherBuffers: Buffer[] = []; + cipherBuffers.push(cipher.update(clearText)); + cipherBuffers.push(cipher.final()); - assert.equal(clearText2, clearText); -} + let cipherText: Buffer = Buffer.concat(cipherBuffers); -function crypto_cipher_decipher_buffer_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherBuffers:Buffer[] = []; - cipherBuffers.push(cipher.update(clearText)); - cipherBuffers.push(cipher.final()); + let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let decipherBuffers: Buffer[] = []; + decipherBuffers.push(decipher.update(cipherText)); + decipherBuffers.push(decipher.final()); - var cipherText:Buffer = Buffer.concat(cipherBuffers); + let clearText2: Buffer = Buffer.concat(decipherBuffers); - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var decipherBuffers:Buffer[] = []; - decipherBuffers.push(decipher.update(cipherText)); - decipherBuffers.push(decipher.final()); - - var clearText2:Buffer = Buffer.concat(decipherBuffers); - - assert.deepEqual(clearText2, clearText); + assert.deepEqual(clearText2, clearText); + } } //////////////////////////////////////////////////// @@ -472,33 +554,24 @@ var ctx: tls.SecureContext = tls.createSecureContext({ }); var blah = ctx.context; -var tlsOpts: tls.TlsOptions = { +var connOpts: tls.ConnectionOptions = { host: "127.0.0.1", port: 55 }; -var tlsSocket = tls.connect(tlsOpts); - +var tlsSocket = tls.connect(connOpts); //////////////////////////////////////////////////// - -// Make sure .listen() and .close() retuern a Server instance -http.createServer().listen(0).close().address(); -net.createServer().listen(0).close().address(); - -var request = http.request('http://0.0.0.0'); -request.once('error', function () {}); -request.setNoDelay(true); -request.abort(); - -//////////////////////////////////////////////////// -/// Http tests : http://nodejs.org/api/http.html +/// Http tests : http://nodejs.org/api/http.html /// //////////////////////////////////////////////////// + namespace http_tests { - // Status codes - var code = 100; - var codeMessage = http.STATUS_CODES['400']; - var codeMessage = http.STATUS_CODES[400]; + { + // Status codes + var codeMessage = http.STATUS_CODES['400']; + var codeMessage = http.STATUS_CODES[400]; + } + { var agent: http.Agent = new http.Agent({ keepAlive: true, keepAliveMsecs: 10000, @@ -508,20 +581,29 @@ namespace http_tests { var agent: http.Agent = http.globalAgent; - http.request({ - agent: false - }); - http.request({ - agent: agent - }); - http.request({ - agent: undefined - }); + http.request({agent: false}); + http.request({agent: agent}); + http.request({agent: undefined}); + } + + { + // Make sure .listen() and .close() retuern a Server instance + http.createServer().listen(0).close().address(); + net.createServer().listen(0).close().address(); + } + + { + var request = http.request('http://0.0.0.0'); + request.once('error', function() { }); + request.setNoDelay(true); + request.abort(); + } } -//////////////////////////////////////////////////// -/// Https tests : http://nodejs.org/api/https.html -//////////////////////////////////////////////////// +////////////////////////////////////////////////////// +/// Https tests : http://nodejs.org/api/https.html /// +////////////////////////////////////////////////////// + namespace https_tests { var agent: https.Agent = new https.Agent({ keepAlive: true, @@ -565,14 +647,16 @@ namespace tty_tests { /// Dgram tests : http://nodejs.org/api/dgram.html //////////////////////////////////////////////////// -var ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => { -}); -ds.bind(); -ds.bind(41234); -var ai: dgram.AddressInfo = ds.address(); -ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { -}); -ds.send(new Buffer("hello"), 5000, "127.0.0.1"); +namespace dgram_tests { + var ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => { + }); + ds.bind(); + ds.bind(41234); + var ai: dgram.AddressInfo = ds.address(); + ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { + }); + ds.send(new Buffer("hello"), 5000, "127.0.0.1"); +} //////////////////////////////////////////////////// ///Querystring tests : https://nodejs.org/api/querystring.html @@ -668,82 +752,82 @@ namespace path_tests { path.isAbsolute('.') // false path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb') -// returns -// '..\\..\\impl\\bbb' + // returns + // '..\\..\\impl\\bbb' path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb') -// returns -// '../../impl/bbb' + // returns + // '../../impl/bbb' path.dirname('/foo/bar/baz/asdf/quux') -// returns -// '/foo/bar/baz/asdf' + // returns + // '/foo/bar/baz/asdf' path.basename('/foo/bar/baz/asdf/quux.html') -// returns -// 'quux.html' + // returns + // 'quux.html' path.basename('/foo/bar/baz/asdf/quux.html', '.html') -// returns -// 'quux' + // returns + // 'quux' path.extname('index.html') -// returns -// '.html' + // returns + // '.html' path.extname('index.coffee.md') -// returns -// '.md' + // returns + // '.md' path.extname('index.') -// returns -// '.' + // returns + // '.' path.extname('index') -// returns -// '' + // returns + // '' 'foo/bar/baz'.split(path.sep) -// returns -// ['foo', 'bar', 'baz'] + // returns + // ['foo', 'bar', 'baz'] 'foo\\bar\\baz'.split(path.sep) -// returns -// ['foo', 'bar', 'baz'] + // returns + // ['foo', 'bar', 'baz'] console.log(process.env.PATH) -// '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin' + // '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin' process.env.PATH.split(path.delimiter) -// returns -// ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin'] + // returns + // ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin'] console.log(process.env.PATH) -// 'C:\Windows\system32;C:\Windows;C:\Program Files\nodejs\' + // 'C:\Windows\system32;C:\Windows;C:\Program Files\nodejs\' process.env.PATH.split(path.delimiter) -// returns -// ['C:\Windows\system32', 'C:\Windows', 'C:\Program Files\nodejs\'] + // returns + // ['C:\Windows\system32', 'C:\Windows', 'C:\Program Files\nodejs\'] path.parse('/home/user/dir/file.txt') -// returns -// { -// root : "/", -// dir : "/home/user/dir", -// base : "file.txt", -// ext : ".txt", -// name : "file" -// } + // returns + // { + // root : "/", + // dir : "/home/user/dir", + // base : "file.txt", + // ext : ".txt", + // name : "file" + // } path.parse('C:\\path\\dir\\index.html') -// returns -// { -// root : "C:\", -// dir : "C:\path\dir", -// base : "index.html", -// ext : ".html", -// name : "index" -// } + // returns + // { + // root : "C:\", + // dir : "C:\path\dir", + // base : "index.html", + // ext : ".html", + // name : "index" + // } path.format({ root : "/", @@ -752,8 +836,8 @@ namespace path_tests { ext : ".txt", name : "file" }); -// returns -// '/home/user/dir/file.txt' + // returns + // '/home/user/dir/file.txt' } //////////////////////////////////////////////////// @@ -872,20 +956,28 @@ namespace string_decoder_tests { /// Child Process tests: https://nodejs.org/api/child_process.html /// ////////////////////////////////////////////////////////////////////// -childProcess.exec("echo test"); -childProcess.spawnSync("echo test"); +namespace child_process_tests { + { + childProcess.exec("echo test"); + childProcess.spawnSync("echo test"); + } +} ////////////////////////////////////////////////////////////////////// /// cluster tests: https://nodejs.org/api/cluster.html /// ////////////////////////////////////////////////////////////////////// -cluster.fork(); -Object.keys(cluster.workers).forEach(key => { - const worker = cluster.workers[key]; - if (worker.isDead()) { - console.log('worker %d is dead', worker.process.pid); +namespace cluster_tests { + { + cluster.fork(); + Object.keys(cluster.workers).forEach(key => { + const worker = cluster.workers[key]; + if (worker.isDead()) { + console.log('worker %d is dead', worker.process.pid); + } + }); } -}); +} //////////////////////////////////////////////////// /// os tests : https://nodejs.org/api/os.html @@ -982,6 +1074,31 @@ namespace vm_tests { } } +///////////////////////////////////////////////////// +/// Timers tests : https://nodejs.org/api/timers.html +///////////////////////////////////////////////////// + +namespace timers_tests { + { + let immediateId = timers.setImmediate(function(){ console.log("immediate"); }); + timers.clearImmediate(immediateId); + } + { + let counter = 0; + let timeout = timers.setInterval(function(){ console.log("interval"); }, 20); + timeout.unref(); + timeout.ref(); + timers.clearInterval(timeout); + } + { + let counter = 0; + let timeout = timers.setTimeout(function(){ console.log("timeout"); }, 20); + timeout.unref(); + timeout.ref(); + timers.clearTimeout(timeout); + } +} + ///////////////////////////////////////////////////////// /// Errors Tests : https://nodejs.org/api/errors.html /// ///////////////////////////////////////////////////////// @@ -996,9 +1113,192 @@ namespace errors_tests { } } -namespace process_tests{ +/////////////////////////////////////////////////////////// +/// Process Tests : https://nodejs.org/api/process.html /// +/////////////////////////////////////////////////////////// + +import * as p from "process"; +namespace process_tests { { var eventEmitter: events.EventEmitter; - eventEmitter = process; // Test that process implements EventEmitter... + eventEmitter = process; // Test that process implements EventEmitter... + + var _p: NodeJS.Process = process; + _p = p; } -} \ No newline at end of file +} + +/////////////////////////////////////////////////////////// +/// Console Tests : https://nodejs.org/api/console.html /// +/////////////////////////////////////////////////////////// + +import * as c from "console"; +namespace console_tests { + { + var _c: Console = console; + _c = c; + } +} + +/////////////////////////////////////////////////// +/// Net Tests : https://nodejs.org/api/net.html /// +/////////////////////////////////////////////////// + +namespace net_tests { + { + // Make sure .listen() and .close() retuern a Server instance + net.createServer().listen(0).close().address(); + } +} + +/***************************************************************************** + * * + * The following tests are the modules not mentioned in document but existed * + * * + *****************************************************************************/ + +/////////////////////////////////////////////////////////// +/// Constants Tests /// +/////////////////////////////////////////////////////////// + +import * as constants from 'constants'; +namespace constants_tests { + var str: string; + var num: number; + num = constants.SIGHUP + num = constants.SIGINT + num = constants.SIGQUIT + num = constants.SIGILL + num = constants.SIGTRAP + num = constants.SIGABRT + num = constants.SIGIOT + num = constants.SIGBUS + num = constants.SIGFPE + num = constants.SIGKILL + num = constants.SIGUSR1 + num = constants.SIGSEGV + num = constants.SIGUSR2 + num = constants.SIGPIPE + num = constants.SIGALRM + num = constants.SIGTERM + num = constants.SIGCHLD + num = constants.SIGSTKFLT + num = constants.SIGCONT + num = constants.SIGSTOP + num = constants.SIGTSTP + num = constants.SIGTTIN + num = constants.SIGTTOU + num = constants.SIGURG + num = constants.SIGXCPU + num = constants.SIGXFSZ + num = constants.SIGVTALRM + num = constants.SIGPROF + num = constants.SIGWINCH + num = constants.SIGIO + num = constants.SIGPOLL + num = constants.SIGPWR + num = constants.SIGSYS + num = constants.SIGUNUSED + num = constants.O_RDONLY + num = constants.O_WRONLY + num = constants.O_RDWR + num = constants.S_IFMT + num = constants.S_IFREG + num = constants.S_IFDIR + num = constants.S_IFCHR + num = constants.S_IFBLK + num = constants.S_IFIFO + num = constants.S_IFLNK + num = constants.S_IFSOCK + num = constants.O_CREAT + num = constants.O_EXCL + num = constants.O_NOCTTY + num = constants.O_TRUNC + num = constants.O_APPEND + num = constants.O_DIRECTORY + num = constants.O_NOATIME + num = constants.O_NOFOLLOW + num = constants.O_SYNC + num = constants.O_DIRECT + num = constants.O_NONBLOCK + num = constants.S_IRWXU + num = constants.S_IRUSR + num = constants.S_IWUSR + num = constants.S_IXUSR + num = constants.S_IRWXG + num = constants.S_IRGRP + num = constants.S_IWGRP + num = constants.S_IXGRP + num = constants.S_IRWXO + num = constants.S_IROTH + num = constants.S_IWOTH + num = constants.S_IXOTH + num = constants.F_OK + num = constants.R_OK + num = constants.W_OK + num = constants.X_OK + num = constants.SSL_OP_ALL + num = constants.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION + num = constants.SSL_OP_CIPHER_SERVER_PREFERENCE + num = constants.SSL_OP_CISCO_ANYCONNECT + num = constants.SSL_OP_COOKIE_EXCHANGE + num = constants.SSL_OP_CRYPTOPRO_TLSEXT_BUG + num = constants.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS + num = constants.SSL_OP_EPHEMERAL_RSA + num = constants.SSL_OP_LEGACY_SERVER_CONNECT + num = constants.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER + num = constants.SSL_OP_MICROSOFT_SESS_ID_BUG + num = constants.SSL_OP_MSIE_SSLV2_RSA_PADDING + num = constants.SSL_OP_NETSCAPE_CA_DN_BUG + num = constants.SSL_OP_NETSCAPE_CHALLENGE_BUG + num = constants.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG + num = constants.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG + num = constants.SSL_OP_NO_COMPRESSION + num = constants.SSL_OP_NO_QUERY_MTU + num = constants.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION + num = constants.SSL_OP_NO_SSLv2 + num = constants.SSL_OP_NO_SSLv3 + num = constants.SSL_OP_NO_TICKET + num = constants.SSL_OP_NO_TLSv1 + num = constants.SSL_OP_NO_TLSv1_1 + num = constants.SSL_OP_NO_TLSv1_2 + num = constants.SSL_OP_PKCS1_CHECK_1 + num = constants.SSL_OP_PKCS1_CHECK_2 + num = constants.SSL_OP_SINGLE_DH_USE + num = constants.SSL_OP_SINGLE_ECDH_USE + num = constants.SSL_OP_SSLEAY_080_CLIENT_DH_BUG + num = constants.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG + num = constants.SSL_OP_TLS_BLOCK_PADDING_BUG + num = constants.SSL_OP_TLS_D5_BUG + num = constants.SSL_OP_TLS_ROLLBACK_BUG + num = constants.ENGINE_METHOD_RSA + num = constants.ENGINE_METHOD_DSA + num = constants.ENGINE_METHOD_DH + num = constants.ENGINE_METHOD_RAND + num = constants.ENGINE_METHOD_ECDH + num = constants.ENGINE_METHOD_ECDSA + num = constants.ENGINE_METHOD_CIPHERS + num = constants.ENGINE_METHOD_DIGESTS + num = constants.ENGINE_METHOD_STORE + num = constants.ENGINE_METHOD_PKEY_METHS + num = constants.ENGINE_METHOD_PKEY_ASN1_METHS + num = constants.ENGINE_METHOD_ALL + num = constants.ENGINE_METHOD_NONE + num = constants.DH_CHECK_P_NOT_SAFE_PRIME + num = constants.DH_CHECK_P_NOT_PRIME + num = constants.DH_UNABLE_TO_CHECK_GENERATOR + num = constants.DH_NOT_SUITABLE_GENERATOR + num = constants.NPN_ENABLED + num = constants.ALPN_ENABLED + num = constants.RSA_PKCS1_PADDING + num = constants.RSA_SSLV23_PADDING + num = constants.RSA_NO_PADDING + num = constants.RSA_PKCS1_OAEP_PADDING + num = constants.RSA_X931_PADDING + num = constants.RSA_PKCS1_PSS_PADDING + num = constants.POINT_CONVERSION_COMPRESSED + num = constants.POINT_CONVERSION_UNCOMPRESSED + num = constants.POINT_CONVERSION_HYBRID + str = constants.defaultCoreCipherList + str = constants.defaultCipherList +} diff --git a/node/node.d.ts b/node/node.d.ts index 6b043fbe83..81b13e4e1d 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -233,7 +233,7 @@ declare var Buffer: { ************************************************/ declare namespace NodeJS { export interface ErrnoException extends Error { - errno?: number; + errno?: string; code?: string; path?: string; syscall?: string; @@ -281,8 +281,8 @@ declare namespace NodeJS { } export interface ReadWriteStream extends ReadableStream, WritableStream { - pause(): ReadWriteStream; - resume(): ReadWriteStream; + pause(): ReadWriteStream; + resume(): ReadWriteStream; } export interface Events extends EventEmitter { } @@ -372,7 +372,7 @@ declare namespace NodeJS { arch: string; platform: string; memoryUsage(): MemoryUsage; - nextTick(callback: Function): void; + nextTick(callback: Function, ...args: any[]): void; umask(mask?: number): number; uptime(): number; hrtime(time?: number[]): number[]; @@ -456,15 +456,17 @@ declare namespace NodeJS { } } +interface IterableIterator { } + /** * @deprecated */ interface NodeBuffer extends Uint8Array { write(string: string, offset?: number, length?: number, encoding?: string): number; toString(encoding?: string, start?: number, end?: number): string; - toJSON(): any; + toJSON(): {type: 'Buffer', data: any[]}; equals(otherBuffer: Buffer): boolean; - compare(otherBuffer: Buffer): number; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; slice(start?: number, end?: number): Buffer; writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; @@ -586,10 +588,11 @@ declare module "http" { agent?: Agent | boolean; } - export interface Server extends events.EventEmitter, net.Server { + export interface Server extends net.Server { setTimeout(msecs: number, callback: Function): void; maxHeadersCount: number; timeout: number; + listening: boolean; } /** * @deprecated Use IncomingMessage @@ -597,7 +600,7 @@ declare module "http" { export interface ServerRequest extends IncomingMessage { connection: net.Socket; } - export interface ServerResponse extends events.EventEmitter, stream.Writable { + export interface ServerResponse extends stream.Writable { // Extended base methods write(buffer: Buffer): boolean; write(buffer: Buffer, cb?: Function): boolean; @@ -627,7 +630,7 @@ declare module "http" { end(str: string, encoding?: string, cb?: Function): void; end(data?: any, encoding?: string): void; } - export interface ClientRequest extends events.EventEmitter, stream.Writable { + export interface ClientRequest extends stream.Writable { // Extended base methods write(buffer: Buffer): boolean; write(buffer: Buffer, cb?: Function): boolean; @@ -653,8 +656,11 @@ declare module "http" { end(str: string, encoding?: string, cb?: Function): void; end(data?: any, encoding?: string): void; } - export interface IncomingMessage extends events.EventEmitter, stream.Readable { + export interface IncomingMessage extends stream.Readable { httpVersion: string; + httpVersionMajor: string; + httpVersionMinor: string; + connection: net.Socket; headers: any; rawHeaders: string[]; trailers: any; @@ -736,17 +742,30 @@ declare module "http" { declare module "cluster" { import * as child from "child_process"; import * as events from "events"; + import * as net from "net"; + // interfaces export interface ClusterSettings { + execArgv?: string[]; // default: process.execArgv exec?: string; args?: string[]; silent?: boolean; + stdio?: any[]; + uid?: number; + gid?: number; + } + + export interface ClusterSetupMasterSettings { + exec?: string; // default: process.argv[1] + args?: string[]; // default: process.argv.slice(2) + silent?: boolean; // default: false + stdio?: any[]; } export interface Address { address: string; port: number; - addressType: string; + addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" } export class Worker extends events.EventEmitter { @@ -761,33 +780,153 @@ declare module "cluster" { isDead(): boolean; } - export var settings: ClusterSettings; + export interface Cluster extends events.EventEmitter { + Worker: Worker; + disconnect(callback?: Function): void; + fork(env?: any): Worker; + isMaster: boolean; + isWorker: boolean; + // TODO: cluster.schedulingPolicy + settings: ClusterSettings; + setupMaster(settings?: ClusterSetupMasterSettings): void; + worker: Worker; + workers: { + [index: string]: Worker + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: Function): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: any) => void): this; + + on(event: string, listener: Function): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: any) => void): this; + + once(event: string, listener: Function): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: any) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: any) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: any) => void): this; + + } + + export function disconnect(callback ?: Function): void; + export function fork(env?: any): Worker; export var isMaster: boolean; export var isWorker: boolean; - export function setupMaster(settings?: ClusterSettings): void; - export function fork(env?: any): Worker; - export function disconnect(callback?: Function): void; + // TODO: cluster.schedulingPolicy + export var settings: ClusterSettings; + export function setupMaster(settings?: ClusterSetupMasterSettings): void; export var worker: Worker; export var workers: { [index: string]: Worker }; - // Event emitter - export function addListener(event: string, listener: Function): void; - export function on(event: "disconnect", listener: (worker: Worker) => void): void; - export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): void; - export function on(event: "fork", listener: (worker: Worker) => void): void; - export function on(event: "listening", listener: (worker: Worker, address: any) => void): void; - export function on(event: "message", listener: (worker: Worker, message: any) => void): void; - export function on(event: "online", listener: (worker: Worker) => void): void; - export function on(event: "setup", listener: (settings: any) => void): void; - export function on(event: string, listener: Function): any; - export function once(event: string, listener: Function): void; - export function removeListener(event: string, listener: Function): void; - export function removeAllListeners(event?: string): void; - export function setMaxListeners(n: number): void; + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + export function addListener(event: string, listener: Function): Cluster; + export function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function addListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function on(event: string, listener: Function): Cluster; + export function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function on(event: "fork", listener: (worker: Worker) => void): Cluster; + export function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function on(event: "online", listener: (worker: Worker) => void): Cluster; + export function on(event: "setup", listener: (settings: any) => void): Cluster; + + export function once(event: string, listener: Function): Cluster; + export function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function once(event: "fork", listener: (worker: Worker) => void): Cluster; + export function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function once(event: "online", listener: (worker: Worker) => void): Cluster; + export function once(event: "setup", listener: (settings: any) => void): Cluster; + + export function removeListener(event: string, listener: Function): Cluster; + export function removeAllListeners(event?: string): Cluster; + export function setMaxListeners(n: number): Cluster; + export function getMaxListeners(): number; export function listeners(event: string): Function[]; export function emit(event: string, ...args: any[]): boolean; + export function listenerCount(type: string): number; + + export function prependListener(event: string, listener: Function): Cluster; + export function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function prependOnceListener(event: string, listener: Function): Cluster; + export function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function eventNames(): string[]; } declare module "zlib" { @@ -880,21 +1019,142 @@ declare module "os" { internal: boolean; } - export function tmpdir(): string; - export function homedir(): string; - export function endianness(): "BE" | "LE"; export function hostname(): string; - export function type(): string; - export function platform(): string; - export function arch(): string; - export function release(): string; - export function uptime(): number; export function loadavg(): number[]; - export function totalmem(): number; + export function uptime(): number; export function freemem(): number; + export function totalmem(): number; export function cpus(): CpuInfo[]; + export function type(): string; + export function release(): string; export function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; + export function homedir(): string; + export function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: any, homedir: string } + export var constants: { + UV_UDP_REUSEADDR: number, + errno: { + SIGHUP: number; + SIGINT: number; + SIGQUIT: number; + SIGILL: number; + SIGTRAP: number; + SIGABRT: number; + SIGIOT: number; + SIGBUS: number; + SIGFPE: number; + SIGKILL: number; + SIGUSR1: number; + SIGSEGV: number; + SIGUSR2: number; + SIGPIPE: number; + SIGALRM: number; + SIGTERM: number; + SIGCHLD: number; + SIGSTKFLT: number; + SIGCONT: number; + SIGSTOP: number; + SIGTSTP: number; + SIGTTIN: number; + SIGTTOU: number; + SIGURG: number; + SIGXCPU: number; + SIGXFSZ: number; + SIGVTALRM: number; + SIGPROF: number; + SIGWINCH: number; + SIGIO: number; + SIGPOLL: number; + SIGPWR: number; + SIGSYS: number; + SIGUNUSED: number; + }, + signals: { + E2BIG: number; + EACCES: number; + EADDRINUSE: number; + EADDRNOTAVAIL: number; + EAFNOSUPPORT: number; + EAGAIN: number; + EALREADY: number; + EBADF: number; + EBADMSG: number; + EBUSY: number; + ECANCELED: number; + ECHILD: number; + ECONNABORTED: number; + ECONNREFUSED: number; + ECONNRESET: number; + EDEADLK: number; + EDESTADDRREQ: number; + EDOM: number; + EDQUOT: number; + EEXIST: number; + EFAULT: number; + EFBIG: number; + EHOSTUNREACH: number; + EIDRM: number; + EILSEQ: number; + EINPROGRESS: number; + EINTR: number; + EINVAL: number; + EIO: number; + EISCONN: number; + EISDIR: number; + ELOOP: number; + EMFILE: number; + EMLINK: number; + EMSGSIZE: number; + EMULTIHOP: number; + ENAMETOOLONG: number; + ENETDOWN: number; + ENETRESET: number; + ENETUNREACH: number; + ENFILE: number; + ENOBUFS: number; + ENODATA: number; + ENODEV: number; + ENOENT: number; + ENOEXEC: number; + ENOLCK: number; + ENOLINK: number; + ENOMEM: number; + ENOMSG: number; + ENOPROTOOPT: number; + ENOSPC: number; + ENOSR: number; + ENOSTR: number; + ENOSYS: number; + ENOTCONN: number; + ENOTDIR: number; + ENOTEMPTY: number; + ENOTSOCK: number; + ENOTSUP: number; + ENOTTY: number; + ENXIO: number; + EOPNOTSUPP: number; + EOVERFLOW: number; + EPERM: number; + EPIPE: number; + EPROTO: number; + EPROTONOSUPPORT: number; + EPROTOTYPE: number; + ERANGE: number; + EROFS: number; + ESPIPE: number; + ESRCH: number; + ESTALE: number; + ETIME: number; + ETIMEDOUT: number; + ETXTBSY: number; + EWOULDBLOCK: number; + EXDEV: number; + }, + }; + export function arch(): string; + export function platform(): string; + export function tmpdir(): string; export var EOL: string; + export function endianness(): "BE" | "LE"; } declare module "https" { @@ -914,7 +1174,7 @@ declare module "https" { requestCert?: boolean; rejectUnauthorized?: boolean; NPNProtocols?: any; - SNICallback?: (servername: string, cb:(err:Error,ctx:tls.SecureContext)=>any) => any; + SNICallback?: (servername: string, cb: (err: Error, ctx: tls.SecureContext) => any) => any; } export interface RequestOptions extends http.RequestOptions { @@ -967,7 +1227,7 @@ declare module "punycode" { declare module "repl" { import * as stream from "stream"; - import * as events from "events"; + import * as readline from "readline"; export interface ReplOptions { prompt?: string; @@ -979,8 +1239,17 @@ declare module "repl" { useGlobal?: boolean; ignoreUndefined?: boolean; writer?: Function; + completer?: Function; + replMode?: any; + breakEvalOnSigint?: any; } - export function start(options: ReplOptions): events.EventEmitter; + + export interface REPLServer extends readline.ReadLine { + defineCommand(keyword: string, cmd: Function | { help: string, action: Function }): void; + displayPrompt(preserveCursor?: boolean): void + } + + export function start(options: ReplOptions): REPLServer; } declare module "readline" { @@ -1261,18 +1530,50 @@ declare module "url" { } declare module "dns" { + export interface MxRecord { + exchange: string, + priority: number + } + export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string; export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string; export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolve6(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveMx(domain: string, callback: (err: Error, addresses: MxRecord[]) =>void ): string[]; export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function reverse(ip: string, callback: (err: Error, domains: string[]) => void): string[]; + export function setServers(servers: string[]): void; + + //Error codes + export var NODATA: string; + export var FORMERR: string; + export var SERVFAIL: string; + export var NOTFOUND: string; + export var NOTIMP: string; + export var REFUSED: string; + export var BADQUERY: string; + export var BADNAME: string; + export var BADFAMILY: string; + export var BADRESP: string; + export var CONNREFUSED: string; + export var TIMEOUT: string; + export var EOF: string; + export var FILE: string; + export var NOMEM: string; + export var DESTRUCTION: string; + export var BADSTR: string; + export var BADFLAGS: string; + export var NONAME: string; + export var BADHINTS: string; + export var NOTINITIALIZED: string; + export var LOADIPHLPAPI: string; + export var ADDRGETNETWORKPARAMS: string; + export var CANCELLED: string; } declare module "net" { @@ -1375,19 +1676,35 @@ declare module "dgram" { port: number; } - export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + interface BindOptions { + port: number; + address?: string; + exclusive?: boolean; + } - interface Socket extends events.EventEmitter { - send(buf: Buffer, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; - send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + interface SocketOptions { + type: "udp4" | "udp6"; + reuseAddr?: boolean; + } + + export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + export function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + + export interface Socket extends events.EventEmitter { + send(msg: Buffer | String | any[], port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + send(msg: Buffer | String | any[], offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; bind(port?: number, address?: string, callback?: () => void): void; - close(): void; + bind(options: BindOptions, callback?: Function): void; + close(callback?: any): void; address(): AddressInfo; setBroadcast(flag: boolean): void; + setTTL(ttl: number): void; setMulticastTTL(ttl: number): void; setMulticastLoopback(flag: boolean): void; addMembership(multicastAddress: string, multicastInterface?: string): void; dropMembership(multicastAddress: string, multicastInterface?: string): void; + ref(): void; + unref(): void; } } @@ -1660,14 +1977,23 @@ declare module "fs" { export function watch(filename: string, options: { persistent?: boolean; recursive?: boolean; encoding?: string }, listener?: (event: string, filename: string | Buffer) => any): FSWatcher; export function exists(path: string | Buffer, callback?: (exists: boolean) => void): void; export function existsSync(path: string | Buffer): boolean; - /** Constant for fs.access(). File is visible to the calling process. */ - export var F_OK: number; - /** Constant for fs.access(). File can be read by the calling process. */ - export var R_OK: number; - /** Constant for fs.access(). File can be written by the calling process. */ - export var W_OK: number; - /** Constant for fs.access(). File can be executed by the calling process. */ - export var X_OK: number; + + interface Constants { + /** Constant for fs.access(). File is visible to the calling process. */ + F_OK: number; + + /** Constant for fs.access(). File can be read by the calling process. */ + R_OK: number; + + /** Constant for fs.access(). File can be written by the calling process. */ + W_OK: number; + + /** Constant for fs.access(). File can be executed by the calling process. */ + X_OK: number; + } + + export const constants: Constants; + /** Tests a user's permissions for the file specified by path. */ export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; @@ -1688,6 +2014,8 @@ declare module "fs" { fd?: number; mode?: number; }): WriteStream; + export function fdatasync(fd: number, callback: Function): void; + export function fdatasyncSync(fd: number): void; } declare module "path" { @@ -1997,18 +2325,26 @@ declare module "tls" { export interface TlsOptions { host?: string; port?: number; - pfx?: any; //string or buffer - key?: any; //string or buffer + pfx?: string | Buffer[]; + key?: string | string[] | Buffer | any[]; passphrase?: string; - cert?: any; - ca?: any; //string or buffer - crl?: any; //string or string array + cert?: string | string[] | Buffer | Buffer[]; + ca?: string | string[] | Buffer | Buffer[]; + crl?: string | string[]; ciphers?: string; - honorCipherOrder?: any; + honorCipherOrder?: boolean; requestCert?: boolean; rejectUnauthorized?: boolean; - NPNProtocols?: any; //array or Buffer; - SNICallback?: (servername: string, cb:(err:Error,ctx:SecureContext)=>any) => any; + NPNProtocols?: string[] | Buffer; + SNICallback?: (servername: string, cb: (err: Error, ctx: SecureContext) => any) => any; + ecdhCurve?: string; + dhparam?: string | Buffer; + handshakeTimeout?: number; + ALPNProtocols?: string[] | Buffer; + sessionTimeout?: number; + ticketKeys?: any; + sessionIdContext?: string; + secureProtocol?: string; } export interface ConnectionOptions { @@ -2016,13 +2352,20 @@ declare module "tls" { port?: number; socket?: net.Socket; pfx?: string | Buffer - key?: string | Buffer + key?: string | string[] | Buffer | Buffer[]; passphrase?: string; - cert?: string | Buffer - ca?: (string | Buffer)[]; + cert?: string | string[] | Buffer | Buffer[]; + ca?: string | Buffer | (string | Buffer)[]; rejectUnauthorized?: boolean; NPNProtocols?: (string | Buffer)[]; servername?: string; + path?: string; + ALPNProtocols?: (string | Buffer)[]; + checkServerIdentity?: (servername: string, cert: string | Buffer | (string | Buffer)[]) => any; + secureProtocol?: string; + secureContext?: Object; + session?: Buffer; + minDHSize?: number; } export interface Server extends net.Server { @@ -2075,7 +2418,7 @@ declare module "tls" { } export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) => void): Server; - export function connect(options: TlsOptions, secureConnectionListener?: () => void): ClearTextStream; + export function connect(options: ConnectionOptions, secureConnectionListener?: () => void): ClearTextStream; export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; @@ -2083,6 +2426,18 @@ declare module "tls" { } declare module "crypto" { + export interface Certificate { + exportChallenge(spkac: string | Buffer): Buffer; + exportPublicKey(spkac: string | Buffer): Buffer; + verifySpkac(spkac: Buffer): boolean; + } + export var Certificate: { + new (): Certificate; + (): Certificate; + } + + export var fips: boolean; + export interface CredentialDetails { pfx: string; key: string; @@ -2095,70 +2450,93 @@ declare module "crypto" { export interface Credentials { context?: any; } export function createCredentials(details: CredentialDetails): Credentials; export function createHash(algorithm: string): Hash; - export function createHmac(algorithm: string, key: string): Hmac; - export function createHmac(algorithm: string, key: Buffer): Hmac; - export interface Hash { - update(data: any, input_encoding?: string): Hash; - digest(encoding: 'buffer'): Buffer; - digest(encoding: string): any; + export function createHmac(algorithm: string, key: string | Buffer): Hmac; + + type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1"; + type HexBase64Latin1Encoding = "latin1" | "hex" | "base64"; + type Utf8AsciiBinaryEncoding = "utf8" | "ascii" | "binary"; + type HexBase64BinaryEncoding = "binary" | "base64" | "hex"; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + + export interface Hash extends NodeJS.ReadWriteStream { + update(data: string | Buffer): Hash; + update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Hash; digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; } export interface Hmac extends NodeJS.ReadWriteStream { - update(data: any, input_encoding?: string): Hmac; - digest(encoding: 'buffer'): Buffer; - digest(encoding: string): any; + update(data: string | Buffer): Hmac; + update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Hmac; digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; } export function createCipher(algorithm: string, password: any): Cipher; export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; export interface Cipher extends NodeJS.ReadWriteStream { update(data: Buffer): Buffer; - update(data: string, input_encoding: "utf8" | "ascii" | "binary"): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: "binary" | "base64" | "hex"): string; - update(data: string, input_encoding: "utf8" | "ascii" | "binary", output_encoding: "binary" | "base64" | "hex"): string; + update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: HexBase64BinaryEncoding): string; + update(data: string, input_encoding: Utf8AsciiBinaryEncoding, output_encoding: HexBase64BinaryEncoding): string; final(): Buffer; final(output_encoding: string): string; - setAutoPadding(auto_padding: boolean): void; + setAutoPadding(auto_padding?: boolean): void; getAuthTag(): Buffer; + setAAD(buffer: Buffer): void; } export function createDecipher(algorithm: string, password: any): Decipher; export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; export interface Decipher extends NodeJS.ReadWriteStream { update(data: Buffer): Buffer; - update(data: string, input_encoding: "binary" | "base64" | "hex"): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: "utf8" | "ascii" | "binary"): string; - update(data: string, input_encoding: "binary" | "base64" | "hex", output_encoding: "utf8" | "ascii" | "binary"): string; + update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: Utf8AsciiBinaryEncoding): string; + update(data: string, input_encoding: HexBase64BinaryEncoding, output_encoding: Utf8AsciiBinaryEncoding): string; final(): Buffer; final(output_encoding: string): string; - setAutoPadding(auto_padding: boolean): void; + setAutoPadding(auto_padding?: boolean): void; setAuthTag(tag: Buffer): void; + setAAD(buffer: Buffer): void; } export function createSign(algorithm: string): Signer; export interface Signer extends NodeJS.WritableStream { - update(data: any): void; - sign(private_key: string, output_format: string): string; + update(data: string | Buffer): Signer; + update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Signer; + sign(private_key: string | { key: string; passphrase: string }): Buffer; + sign(private_key: string | { key: string; passphrase: string }, output_format: HexBase64Latin1Encoding): string; } export function createVerify(algorith: string): Verify; export interface Verify extends NodeJS.WritableStream { - update(data: any): void; - verify(object: string, signature: string, signature_format?: string): boolean; + update(data: string | Buffer): Verify; + update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Verify; + verify(object: string, signature: Buffer): boolean; + verify(object: string, signature: string, signature_format: HexBase64Latin1Encoding): boolean; } - export function createDiffieHellman(prime_length: number): DiffieHellman; - export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman; + export function createDiffieHellman(prime_length: number, generator?: number): DiffieHellman; + export function createDiffieHellman(prime: Buffer): DiffieHellman; + export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding): DiffieHellman; + export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: number | Buffer): DiffieHellman; + export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: string, generator_encoding: HexBase64Latin1Encoding): DiffieHellman; export interface DiffieHellman { - generateKeys(encoding?: string): string; - computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; - getPrime(encoding?: string): string; - getGenerator(encoding: string): string; - getPublicKey(encoding?: string): string; - getPrivateKey(encoding?: string): string; - setPublicKey(public_key: string, encoding?: string): void; - setPrivateKey(public_key: string, encoding?: string): void; + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: Buffer): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrime(): Buffer; + getPrime(encoding: HexBase64Latin1Encoding): string; + getGenerator(): Buffer; + getGenerator(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + setPublicKey(public_key: Buffer): void; + setPublicKey(public_key: string, encoding: string): void; + setPrivateKey(private_key: Buffer): void; + setPrivateKey(private_key: string, encoding: string): void; + verifyError: number; } export function getDiffieHellman(group_name: string): DiffieHellman; - export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; - export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number): Buffer; export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string): Buffer; export function randomBytes(size: number): Buffer; export function randomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; @@ -2166,119 +2544,269 @@ declare module "crypto" { export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; export interface RsaPublicKey { key: string; - padding?: any; + padding?: number; } export interface RsaPrivateKey { key: string; passphrase?: string, - padding?: any; + padding?: number; } export function publicEncrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer export function privateDecrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer + export function privateEncrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer + export function publicDecrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer export function getCiphers(): string[]; export function getCurves(): string[]; export function getHashes(): string[]; + export interface ECDH { + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding): string; + generateKeys(encoding: HexBase64Latin1Encoding, format: ECDHKeyFormat): string; + computeSecret(other_public_key: Buffer): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding): string; + getPublicKey(encoding: HexBase64Latin1Encoding, format: ECDHKeyFormat): string; + setPrivateKey(private_key: Buffer): void; + setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void; + } + export function createECDH(curve_name: string): ECDH; + export var DEFAULT_ENCODING: string; } declare module "stream" { import * as events from "events"; - export class Stream extends events.EventEmitter { + class internal extends events.EventEmitter { pipe(destination: T, options?: { end?: boolean; }): T; } + namespace internal { - export interface ReadableOptions { - highWaterMark?: number; - encoding?: string; - objectMode?: boolean; - read?: (size?: number) => any; + export class Stream extends internal { } + + export interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + read?: (size?: number) => any; + } + + export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { + readable: boolean; + constructor(opts?: ReadableOptions); + _read(size: number): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): Readable; + resume(): Readable; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. readable + * 5. error + **/ + addListener(event: string, listener: Function): this; + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + + removeListener(event: string, listener: Function): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: Buffer | string) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + } + + export interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + objectMode?: boolean; + write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; + writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; + } + + export class Writable extends events.EventEmitter implements NodeJS.WritableStream { + writable: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + **/ + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "drain", chunk: Buffer | string): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + + removeListener(event: string, listener: Function): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + } + + export interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + readableObjectMode?: boolean; + writableObjectMode?: boolean; + } + + // Note: Duplex extends both Readable and Writable. + export class Duplex extends Readable implements NodeJS.ReadWriteStream { + // Readable + pause(): Duplex; + resume(): Duplex; + // Writeable + writable: boolean; + constructor(opts?: DuplexOptions); + _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export interface TransformOptions extends ReadableOptions, WritableOptions { + transform?: (chunk: string | Buffer, encoding: string, callback: Function) => any; + flush?: (callback: Function) => any; + } + + // Note: Transform lacks the _read and _write methods of Readable/Writable. + export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { + readable: boolean; + writable: boolean; + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: string, callback: Function): void; + _flush(callback: Function): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): Transform; + resume(): Transform; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export class PassThrough extends Transform { } } - export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { - readable: boolean; - constructor(opts?: ReadableOptions); - _read(size: number): void; - read(size?: number): any; - setEncoding(encoding: string): void; - pause(): Readable; - resume(): Readable; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: any): void; - wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; - push(chunk: any, encoding?: string): boolean; - } - - export interface WritableOptions { - highWaterMark?: number; - decodeStrings?: boolean; - objectMode?: boolean; - write?: (chunk: string|Buffer, encoding: string, callback: Function) => any; - writev?: (chunks: {chunk: string|Buffer, encoding: string}[], callback: Function) => any; - } - - export class Writable extends events.EventEmitter implements NodeJS.WritableStream { - writable: boolean; - constructor(opts?: WritableOptions); - _write(chunk: any, encoding: string, callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } - - export interface DuplexOptions extends ReadableOptions, WritableOptions { - allowHalfOpen?: boolean; - readableObjectMode?: boolean; - writableObjectMode?: boolean; - } - - // Note: Duplex extends both Readable and Writable. - export class Duplex extends Readable implements NodeJS.ReadWriteStream { - // Readable - pause(): Duplex; - resume(): Duplex; - // Writeable - writable: boolean; - constructor(opts?: DuplexOptions); - _write(chunk: any, encoding: string, callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } - - export interface TransformOptions extends ReadableOptions, WritableOptions { - transform?: (chunk: string|Buffer, encoding: string, callback: Function) => any; - flush?: (callback: Function) => any; - } - - // Note: Transform lacks the _read and _write methods of Readable/Writable. - export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { - readable: boolean; - writable: boolean; - constructor(opts?: TransformOptions); - _transform(chunk: any, encoding: string, callback: Function): void; - _flush(callback: Function): void; - read(size?: number): any; - setEncoding(encoding: string): void; - pause(): Transform; - resume(): Transform; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: any): void; - wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; - push(chunk: any, encoding?: string): boolean; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } - - export class PassThrough extends Transform { } + export = internal; } declare module "util" { @@ -2303,6 +2831,18 @@ declare module "util" { export function isError(object: any): boolean; export function inherits(constructor: any, superConstructor: any): void; export function debuglog(key: string): (msg: string, ...param: any[]) => void; + export function isBoolean(object: any): boolean; + export function isBuffer(object: any): boolean; + export function isFunction(object: any): boolean; + export function isNull(object: any): boolean; + export function isNullOrUndefined(object: any): boolean; + export function isNumber(object: any): boolean; + export function isObject(object: any): boolean; + export function isPrimitive(object: any): boolean; + export function isString(object: any): boolean; + export function isSymbol(object: any): boolean; + export function isUndefined(object: any): boolean; + export function deprecate(fn: Function, message: string): Function; } declare module "assert" { @@ -2322,7 +2862,7 @@ declare module "assert" { }); } - export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; + export function fail(actual: any, expected: any, message: string, operator: string): void; export function ok(value: any, message?: string): void; export function equal(actual: any, expected: any, message?: string): void; export function notEqual(actual: any, expected: any, message?: string): void; @@ -2378,6 +2918,9 @@ declare module "domain" { bind(cb: (err: Error, data: any) => any): any; intercept(cb: (data: any) => any): any; dispose(): void; + members: any[]; + enter(): void; + exit(): void; } export function create(): Domain; @@ -2628,8 +3171,63 @@ declare module "constants" { export var W_OK: number; export var X_OK: number; export var UV_UDP_REUSEADDR: number; + export var SIGQUIT: number; + export var SIGTRAP: number; + export var SIGIOT: number; + export var SIGBUS: number; + export var SIGUSR1: number; + export var SIGUSR2: number; + export var SIGPIPE: number; + export var SIGALRM: number; + export var SIGCHLD: number; + export var SIGSTKFLT: number; + export var SIGCONT: number; + export var SIGSTOP: number; + export var SIGTSTP: number; + export var SIGTTIN: number; + export var SIGTTOU: number; + export var SIGURG: number; + export var SIGXCPU: number; + export var SIGXFSZ: number; + export var SIGVTALRM: number; + export var SIGPROF: number; + export var SIGIO: number; + export var SIGPOLL: number; + export var SIGPWR: number; + export var SIGSYS: number; + export var SIGUNUSED: number; + export var defaultCoreCipherList: string; + export var defaultCipherList: string; + export var ENGINE_METHOD_RSA: number; + export var ALPN_ENABLED: number; } declare module "process" { export = process; } + +declare module "v8" { + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + export function getHeapStatistics(): { total_heap_size: number, total_heap_size_executable: number, total_physical_size: number, total_avaialble_size: number, used_heap_size: number, heap_size_limit: number }; + export function getHeapSpaceStatistics(): HeapSpaceInfo[]; + export function setFlagsFromString(flags: string): void; +} + +declare module "timers" { + export function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; + export function clearTimeout(timeoutId: NodeJS.Timer): void; + export function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; + export function clearInterval(intervalId: NodeJS.Timer): void; + export function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; + export function clearImmediate(immediateId: any): void; +} + +declare module "console" { + export = console; +} diff --git a/notify.js/notify.js.d.ts b/notify.js/notify.js.d.ts index ae31ea6317..49fd3415ec 100644 --- a/notify.js/notify.js.d.ts +++ b/notify.js/notify.js.d.ts @@ -1,131 +1,131 @@ -// Type definitions for notify.js -// Project: https://github.com/notifyjs/notifyjs -// Definitions by: Bahman Nikkhahan -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace NotifyJS { - interface NotificationOptions { - // whether to hide the notification on click - clickToHide: boolean; - // whether to auto-hide the notification - autoHide: boolean; - // if autoHide, hide after milliseconds - autoHideDelay: number; - // show the arrow pointing at the element - arrowShow: boolean; - // arrow size in pixels - arrowSize: number; - // position defines the notification position though uses the defaults below - position: string; - // default positions - elementPosition: string; - globalPosition: string; - // default style - style: string; - // default class (string or [string]) - className: string; - // show animation - showAnimation: string; - // show animation duration - showDuration: number; - // hide animation - hideAnimation: string; - // hide animation duration - hideDuration: number; - // padding between element and notification - gap: number; - } - - interface JQueryStaticNotify { - /** - * notify user - * @param element a jquery element - * @param notificationdata global notification data - * @param options notification options - */ - (element?: any, notificationdata?: any, options?: NotificationOptions): JQueryStatic; - - /** - * Add style - * @param styleName style name - * @param styleDefinition style definition object - */ - addStyle(styleName: string, styleDefinition: any): any; - - /** - * Remove style - * @param styleName style name - */ - removeStyle(styleName: string): any; - - /** - * Get style - * @param styleName style name - */ - getStyle(styleName: string): any; - - /** - * Insert css - * @param cssText css text to insert - */ - insertCSS(cssText: string): any; - - /** - * Set defaults for notifications - * @param options notification iptions - */ - defaults(options: NotificationOptions): any; - } - - interface JQueryStatic { - notify: JQueryStaticNotify; - } - - interface JQueryNotify { - /** - * notify user - * @param element a jquery element - * @param notificationdata global notification data - * @param options notification options - */ - (element?: any, notificationdata?: any, options?: NotificationOptions): JQuery; - - /** - * Add style - * @param styleName style name - * @param styleDefinition style definition object - */ - addStyle(styleName: string, styleDefinition: any): any; - - /** - * Remove style - * @param styleName style name - */ - removeStyle(styleName: string): any; - - /** - * Get style - * @param styleName style name - */ - getStyle(styleName: string): any; - - /** - * Insert css - * @param cssText css text to insert - */ - insertCSS(cssText: string): any; - - /** - * Set defaults for notifications - * @param options notification iptions - */ - defaults(options: NotificationOptions): any; - - } - - interface JQuery { - notify: JQueryStaticNotify; - } -} +// Type definitions for notify.js +// Project: https://github.com/notifyjs/notifyjs +// Definitions by: Bahman Nikkhahan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace NotifyJS { + interface NotificationOptions { + // whether to hide the notification on click + clickToHide: boolean; + // whether to auto-hide the notification + autoHide: boolean; + // if autoHide, hide after milliseconds + autoHideDelay: number; + // show the arrow pointing at the element + arrowShow: boolean; + // arrow size in pixels + arrowSize: number; + // position defines the notification position though uses the defaults below + position: string; + // default positions + elementPosition: string; + globalPosition: string; + // default style + style: string; + // default class (string or [string]) + className: string; + // show animation + showAnimation: string; + // show animation duration + showDuration: number; + // hide animation + hideAnimation: string; + // hide animation duration + hideDuration: number; + // padding between element and notification + gap: number; + } + + interface JQueryStaticNotify { + /** + * notify user + * @param element a jquery element + * @param notificationdata global notification data + * @param options notification options + */ + (element?: any, notificationdata?: any, options?: NotificationOptions): JQueryStatic; + + /** + * Add style + * @param styleName style name + * @param styleDefinition style definition object + */ + addStyle(styleName: string, styleDefinition: any): any; + + /** + * Remove style + * @param styleName style name + */ + removeStyle(styleName: string): any; + + /** + * Get style + * @param styleName style name + */ + getStyle(styleName: string): any; + + /** + * Insert css + * @param cssText css text to insert + */ + insertCSS(cssText: string): any; + + /** + * Set defaults for notifications + * @param options notification iptions + */ + defaults(options: NotificationOptions): any; + } + + interface JQueryStatic { + notify: JQueryStaticNotify; + } + + interface JQueryNotify { + /** + * notify user + * @param element a jquery element + * @param notificationdata global notification data + * @param options notification options + */ + (element?: any, notificationdata?: any, options?: NotificationOptions): JQuery; + + /** + * Add style + * @param styleName style name + * @param styleDefinition style definition object + */ + addStyle(styleName: string, styleDefinition: any): any; + + /** + * Remove style + * @param styleName style name + */ + removeStyle(styleName: string): any; + + /** + * Get style + * @param styleName style name + */ + getStyle(styleName: string): any; + + /** + * Insert css + * @param cssText css text to insert + */ + insertCSS(cssText: string): any; + + /** + * Set defaults for notifications + * @param options notification iptions + */ + defaults(options: NotificationOptions): any; + + } + + interface JQuery { + notify: JQueryStaticNotify; + } +} diff --git a/notify.js/notify.js.tests.ts b/notify.js/notify.js.tests.ts index f533b47288..505f3c4ec5 100644 --- a/notify.js/notify.js.tests.ts +++ b/notify.js/notify.js.tests.ts @@ -1,53 +1,53 @@ -/// -/// - -// setting defaults for notification plugin -$.notify.defaults({ - clickToHide: true, - autoHide: false, - autoHideDelay: 5000, - arrowShow: true, - arrowSize: 5, - position: 'top center', - elementPosition: 'bottom left', - globalPosition: 'top center', - style: 'bootstrap', - className: 'error', - showAnimation: 'slideDown', - showDuration: 400, - hideAnimation: 'slideUp', - hideDuration: 200, - gap: 2 -}); - -$(".elem-demo").notify("Hello Box"); -$.notify("Access granted", "success"); -$.notify("Do not press this button", "info"); -$.notify('hello !!', { - style: 'happyblue' -}); -$.notify('hello !!', { - style: 'happyblue' -}); -//add a new style 'foo' -$.notify.addStyle('foo', { - html: - "
" + - "
" + - "
" + - "
" + - "" + - "" + - "
" + - "
" + - "
" -}); - -$.notify({ - title: 'Would you like some Foo ?', - button: 'Confirm' -}, { - style: 'foo', - autoHide: false, - clickToHide: false +/// +/// + +// setting defaults for notification plugin +$.notify.defaults({ + clickToHide: true, + autoHide: false, + autoHideDelay: 5000, + arrowShow: true, + arrowSize: 5, + position: 'top center', + elementPosition: 'bottom left', + globalPosition: 'top center', + style: 'bootstrap', + className: 'error', + showAnimation: 'slideDown', + showDuration: 400, + hideAnimation: 'slideUp', + hideDuration: 200, + gap: 2 +}); + +$(".elem-demo").notify("Hello Box"); +$.notify("Access granted", "success"); +$.notify("Do not press this button", "info"); +$.notify('hello !!', { + style: 'happyblue' +}); +$.notify('hello !!', { + style: 'happyblue' +}); +//add a new style 'foo' +$.notify.addStyle('foo', { + html: + "
" + + "
" + + "
" + + "
" + + "" + + "" + + "
" + + "
" + + "
" +}); + +$.notify({ + title: 'Would you like some Foo ?', + button: 'Confirm' +}, { + style: 'foo', + autoHide: false, + clickToHide: false }); \ No newline at end of file diff --git a/openlayers/openlayers.d.ts b/openlayers/openlayers.d.ts index ec180bf45d..7cc216f1c2 100644 --- a/openlayers/openlayers.d.ts +++ b/openlayers/openlayers.d.ts @@ -1,4 +1,4 @@ -// Type definitions for OpenLayers v3.6.0 +// Type definitions for OpenLayers v3.18.2 // Project: http://openlayers.org/ // Definitions by: Wouter Goedhart // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -48,6 +48,46 @@ declare namespace olx { extent: ol.Extent; } + interface OverviewMapOptions { + /*** Whether the control should start collapsed or not (expanded). Default to true.*/ + collapsed?: boolean; + /*** Text label to use for the expanded overviewmap button. Default is «. Instead of text, also a Node (e.g. a span element) can be used.*/ + collapseLabel? :string | Node; + /*** Whether the control can be collapsed or not. Default to true.*/ + collapsible?: boolean; + /*** Text label to use for the collapsed overviewmap button. Default is ». Instead of text, also a Node (e.g. a span element) can be used.*/ + label?: string | Node; + /*** Layers for the overview map. If not set, then all main map layers are used instead.*/ + layers?: ol.layer.Layer[] | ol.Collection; + /*** Function called when the control should be re-rendered. This is called in a requestAnimationFrame callback.*/ + render?: Function; + /*** Specify a target if you want the control to be rendered outside of the map's viewport.*/ + target?: Element; + /*** Text label to use for the button tip. Default is Overview map*/ + tipLabel?: string; + /*** Custom view for the overview map. If not provided, a default view with an EPSG:3857 projection will be used.*/ + view?: ol.View; + } + + interface RotateOptions { + /*** CSS class name. Default is ol-rotate.*/ + className?: string; + /*** Text label to use for the rotate button. Default is ⇧. Instead of text, also a Node (e.g. a span element) can be used.*/ + label?: string | Element; + /*** Text label to use for the rotate tip. Default is Reset rotation.*/ + tipLabel?: string; + /*** Animation duration in milliseconds. Default is 250.*/ + duration?: number; + /*** Hide the control when rotation is 0. Default is true.*/ + autoHide?: boolean; + /*** Function called when the control should be re-rendered. This is called in a requestAnimationFrame callback.*/ + render?: Function; + /*** Function called when the control is clicked. This will override the default resetNorth.*/ + resetNorth?: Function; + /*** Target.*/ + target?: Element; + } + interface AttributionOptions { /** HTML markup for this attribution. */ @@ -211,6 +251,30 @@ declare namespace olx { /** experimental Whether to wrap the world horizontally. When set to false, only one world will be rendered. When true, tiles will be requested for one world only, but they will be wrapped horizontally to render multiple worlds. The default is true. */ wrapX?: boolean; } + interface OSMOptions { + /** Attributions */ + attributions?: ol.AttributionLike; + /** Cache size. Default is 2048. */ + cacheSize?: number; + /** + * The crossOrigin attribute for loaded images. Note that you must provide a crossOrigin value if you are using the WebGL + * renderer or if you want to access pixel data with the Canvas renderer. + * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail. Default is anonymous. + */ + crossOrigin?: string; + /** Max zoom. Default is 19. */ + maxZoom?: number; + /** Whether the layer is opaque. Default is true. */ + opaque?: boolean; + /** Maximum allowed reprojection error (in pixels). Default is 0.5. Higher values can increase reprojection performance, but decrease precision. */ + reprojectionErrorThreshold?: number; + /** Optional function to load a tile given a URL. */ + tileLoadFunction?: ol.TileLoadFunctionType; + /** URL template. Must include {x}, {y} or {-y}, and {z} placeholders. Default is https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png. */ + url?: string; + /** Whether to wrap the world horizontally. Default is true. */ + wrapX?: boolean; + } /** * Object literal with config options for the map logo. */ @@ -562,46 +626,365 @@ declare namespace olx { namespace interaction { interface DefaultsOptions { + /*** Whether Alt-Shift-drag rotate is desired. Default is true.*/ altShiftDragRotate?: boolean; + /*** Whether double click zoom is desired. Default is true.*/ doubleClickZoom?: boolean; + /*** Whether keyboard interaction is desired. Default is true.*/ keyboard?: boolean; + /*** Whether mousewheel zoom is desired. Default is true.*/ mouseWheelZoom?: boolean; + /*** Whether Shift-drag zoom is desired. Default is true.*/ shiftDragZoom?: boolean; + /*** Whether drag pan is desired. Default is true.*/ dragPan?: boolean; + /*** Whether pinch rotate is desired. Default is true.*/ pinchRotate?: boolean; + /*** Whether pinch zoom is desired. Default is true.*/ pinchZoom?: boolean; + /*** Zoom delta*/ zoomDelta?: number; + /*** Zoom duration*/ zoomDuration?: number; } + interface InteractionOptions { + /** + * Method called by the map to notify the interaction that a browser event was dispatched to the map. + * The function may return false to prevent the propagation of the event to other interactions in + * the map's interactions chain. Required. + */ + handleEvent: Function; + } interface ModifyOptions { + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event will + * be considered to add or move a vertex to the sketch. Default is ol.events.condition.primaryAction. + */ + condition?: ol.events.ConditionType; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should + * be handled. By default, ol.events.condition.singleClick with ol.events.condition.noModifierKeys results + * in a vertex deletion. + */ deleteCondition?: ol.events.ConditionType; + /*** Pixel tolerance for considering the pointer close enough to a segment or vertex for editing. Default is 10.*/ pixelTolerance?: number; + /*** Style used for the features being modified. By default the default edit style is used (see ol.style).*/ style?: ol.style.Style | Array | ol.style.StyleFunction; + /*** The features the interaction works on. Required.*/ features: ol.Collection; + /*** Wrap the world horizontally on the sketch overlay. Default is false.*/ wrapX?: boolean; } + interface DragBoxOptions { + /*** CSS class name for styling the box. The default is ol-dragbox.*/ + className?: string; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * Default is ol.events.condition.always. + */ + condition?: ol.events.ConditionType; + /*** A function that takes a ol.MapBrowserEvent and two ol.Pixels to indicate whether a boxend event should be fired.*/ + boxEndCondition?: ol.interaction.DragBoxEndConditionType; + } interface DrawOptions { + /** + * The maximum distance in pixels between "down" and "up" for a "up" event to be considered a "click" event and actually + * add a point/vertex to the geometry being drawn. Default is 6 pixels. That value was chosen for the draw interaction + * to behave correctly on mouse as well as on touch devices. + */ clickTolerance?: number; + /** + * Destination collection for the drawn features. + */ features?: ol.Collection; + /** + * Destination source for the drawn features. + */ source?: ol.source.Vector; + /** + * Pixel distance for snapping to the drawing finish. Default is 12. + */ snapTolerance?: number; + /** + * Drawing type ('Point', 'LineString', 'Polygon', 'MultiPoint', 'MultiLineString', 'MultiPolygon' or 'Circle'). Required. + */ type: ol.geom.GeometryType; + /** + * The number of points that can be drawn before a polygon ring or line string is finished. The default is no restriction. + */ maxPoints?: number; + /** + * The number of points that must be drawn before a polygon ring or line string can be finished. Default is 3 for polygon + * rings and 2 for line strings. + */ minPoints?: number; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether the drawing can be finished. + */ + finishCondition?: ol.events.ConditionType; + /** + * Style for sketch features. + */ style?: ol.style.Style | Array | ol.style.StyleFunction; + /** + * Function that is called when a geometry's coordinates are updated. + */ geometryFunction?: ol.interaction.DrawGeometryFunctionType; + /** + * Geometry name to use for features created by the draw interaction. + */ + geometryName?: string; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * By default ol.events.condition.noModifierKeys, i.e. a click, adds a vertex or deactivates freehand drawing. + */ + condition?: ol.events.ConditionType; + /** + * Condition that activates freehand drawing for lines and polygons. This function takes an ol.MapBrowserEvent and returns + * a boolean to indicate whether that event should be handled. The default is ol.events.condition.shiftKeyOnly, meaning that + * the Shift key activates freehand drawing. + */ + freehandCondition?: ol.events.ConditionType; + /** + * Wrap the world horizontally on the sketch overlay. Default is false. + */ wrapX?: boolean; } - interface SelectOptions { - addCondition?: ol.events.ConditionType; + interface DoubleClickZoomOptions { + /** + * Animation duration in milliseconds. Default is 250. + */ + duration?: number; + /** + * The zoom delta applied on each double click, default is 1. + */ + delta?: number; + } + interface DragAndDropOptions { + /** + * Format constructors. + */ + formatConstructors?: Array; + /** + * Target projection. By default, the map's view's projection is used. + */ + projection: ol.proj.ProjectionLike; + /** + * The element that is used as the drop target, default is the viewport element. + */ + target?: Element; + } + interface DragPanOptions { + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * Default is ol.events.condition.noModifierKeys. + */ condition?: ol.events.ConditionType; - layers?: Array | ((layer: ol.layer.Layer) => boolean); - style?: ol.style.Style | Array | ol.style.StyleFunction; - removeCondition?: ol.events.ConditionType; - toggleCondition?: ol.events.ConditionType; - multi?: boolean; + /** + * Kinetic inertia to apply to the pan. + */ + kinetic?: ol.Kinetic; + } + interface DragRotateOptions { + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * Default is ol.events.condition.altShiftKeysOnly. + */ + condition?: ol.events.ConditionType; + /** + * Animation duration in milliseconds. Default is 250. + */ + duration?: number; + } + interface DragRotateAndZoomOptions { + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * Default is ol.events.condition.shiftKeyOnly. + */ + condition?: ol.events.ConditionType; + /** + * Animation duration in milliseconds. Default is 400. + */ + duration?: number; + } + interface DragZoomOptions { + /** + * CSS class name for styling the box. The default is ol-dragzoom. + */ + className?: string; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * Default is ol.events.condition.shiftKeyOnly. + */ + condition?: ol.events.ConditionType; + /** + * Animation duration in milliseconds. Default is 200. + */ + duration?: number; + /** + * Use interaction for zooming out. Default is false. + */ + out?: boolean; + } + interface KeyboardPanOptions { + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * Default is ol.events.condition.noModifierKeys and ol.events.condition.targetNotEditable. + */ + condition?: ol.events.ConditionType; + /** + * Animation duration in milliseconds. Default is 100. + */ + duration?: number; + /** + * Pixel The amount to pan on each key press. Default is 128 pixels. + */ + pixelDelta?: number; + } + interface KeyboardZoomOptions { + /** + * Animation duration in milliseconds. Default is 100. + */ + duration?: number; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * Default is ol.events.condition.targetNotEditable. + */ + condition?: ol.events.ConditionType; + /** + * The amount to zoom on each key press. Default is 1. + */ + delta?: number; + } + interface MouseWheelZoomOptions { + /** + * Animation duration in milliseconds. Default is 250. + */ + duration?: number; + /** + * Enable zooming using the mouse's location as the anchor. Default is true. + * When set to false, zooming in and out will zoom to the center of the screen instead of zooming on the mouse's location. + */ + useAnchor?: boolean; + } + interface PinchRotateOptions { + /** + * The duration of the animation in milliseconds. Default is 250. + */ + duration?: number; + /** + * Minimal angle in radians to start a rotation. Default is 0.3. + */ + threshold?: number; + } + interface PinchZoomOptions { + /** + * Animation duration in milliseconds. Default is 400. + */ + duration?: number; + } + interface PointerOptions { + /** + * Function handling "down" events. If the function returns true then a drag sequence is started. + */ + handleDownEvent?: Function; + /** + * Function handling "drag" events. This function is called on "move" events during a drag sequence. + */ + handleDragEvent?: Function; + /** + * Method called by the map to notify the interaction that a browser event was dispatched to the map. + * The function may return false to prevent the propagation of the event to other interactions in the map's interactions chain. + */ + handleEvent?: Function; + /** + * Function handling "move" events. This function is called on "move" events, also during a drag sequence + * (so during a drag sequence both the handleDragEvent function and this function are called). + */ + handleMoveEvent?: Function; + /** + * Function handling "up" events. If the function returns false then the current drag sequence is stopped. + */ + handleUpEvent?: Function; + } + interface SnapOptions { + /** + * Snap to these features. Either this option or source should be provided. + */ features?: ol.Collection; + /** + * Snap to edges. Default is true. + */ + edge?: boolean; + /** + * Snap to vertices. Default is true. + */ + vertex?: boolean; + /** + * Pixel tolerance for considering the pointer close enough to a segment or vertex for snapping. Default is 10 pixels. + */ + pixelTolerance?: number; + /** + * Snap to features from this source. Either this option or features should be provided. + */ + source?: ol.source.Vector; + } + interface SelectOptions { + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * By default, this is ol.events.condition.never. + * Use this if you want to use different events for add and remove instead of toggle. + */ + addCondition?: ol.events.ConditionType; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * This is the event for the selected features as a whole. By default, this is ol.events.condition.singleClick. + * Clicking on a feature selects that feature and removes any that were in the selection. + * Clicking outside any feature removes all from the selection. + * See toggle, add, remove options for adding/removing extra features to/ from the selection. + */ + condition?: ol.events.ConditionType; + /** + * A list of layers from which features should be selected. Alternatively, a filter function can be provided. + * The function will be called for each layer in the map and should return true for layers that you want to be selectable. + * If the option is absent, all visible layers will be considered selectable. + */ + layers?: Array | ((layer: ol.layer.Layer) => boolean); + /** + * Style for the selected features. By default the default edit style is used (see ol.style). + */ + style?: ol.style.Style | Array | ol.style.StyleFunction; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * By default, this is ol.events.condition.never. + * Use this if you want to use different events for add and remove instead of toggle. + */ + removeCondition?: ol.events.ConditionType; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * This is in addition to the condition event. By default, ol.events.condition.shiftKeyOnly, + * i.e. pressing shift as well as the condition event, adds that feature to the current selection if it is not currently + * selected, and removes it if it is. See add and remove if you want to use different events instead of a toggle. + */ + toggleCondition?: ol.events.ConditionType; + /** + * A boolean that determines if the default behaviour should select only single features or all (overlapping) + * features at the clicked map position. Default is false i.e single select + */ + multi?: boolean; + /** + * Collection where the interaction will place selected features. Optional. If not set the interaction will create a collection. + * In any case the collection used by the interaction is returned by ol.interaction.Select#getFeatures. + */ + features?: ol.Collection; + /** + * A function that takes an ol.Feature and an ol.layer.Layer and returns true if the feature may be selected or false otherwise. + */ filter?: ol.interaction.SelectFilterFunction; + /** + * Wrap the world horizontally on the selection overlay. Default is true. + */ wrapX?: boolean; } } @@ -791,24 +1174,24 @@ declare namespace olx { */ wrapX?: boolean; } - + interface ClusterOptions extends VectorOptions{ - + /** * Minimum distance in pixels between clusters. Default is 20. */ distance?: number; - + extent?: ol.Extent; - + geometryFunction?: any; - + projection?: ol.proj.ProjectionLike; - + source: ol.source.Vector; - + } - + interface WMTSOptions { attributions?: Array; crossOrigin?: string; @@ -1127,6 +1510,8 @@ declare namespace ol { interface ImageLoadFunctionType { (image: ol.Image, url: string): void } + type AttributionLike = string | Array | ol.Attribution | Array + /** * An attribution for a layer source. */ @@ -2422,9 +2807,9 @@ declare namespace ol { * @returns Control.s */ function defaults(options?: olx.control.DefaultsOptions): ol.Collection; - + namespace ScaleLine { - + /** * Units for the scale line. Supported values are 'degrees', 'imperial', 'nautical', 'metric', 'us'. */ @@ -2433,29 +2818,29 @@ declare namespace ol { class Control extends ol.Object{ constructor(options: olx.control.ControlOptions); - + /** * Get the map associated with this control. */ getMap():ol.Map; - + /** - * Remove the control from its current map and attach it to the new map. + * Remove the control from its current map and attach it to the new map. * Subclasses may set up event handlers to get notified about changes to the map here. */ setMap(map: ol.Map):void; - + /** - * This function is used to set a target element for the control. - * It has no effect if it is called after the control has been added to the map (i.e. after setMap is called on the control). - * If no target is set in the options passed to the control constructor and if setTarget is not called then the control is + * This function is used to set a target element for the control. + * It has no effect if it is called after the control has been added to the map (i.e. after setMap is called on the control). + * If no target is set in the options passed to the control constructor and if setTarget is not called then the control is * added to the map's overlay container. */ setTarget(target: Element | string):void; - - + + } - + class Attribution extends Control { } @@ -2466,23 +2851,58 @@ declare namespace ol { } class OverviewMap extends Control { + constructor(options?: olx.OverviewMapOptions); + + /** + * Update the overview map element. + * @param mapEvent + */ + render(mapEvent: ol.MapEvent): void; + + /** + * Determine if the overview map is collapsed. + */ + getCollapsed(): boolean; + + /** + * Return true if the overview map is collapsible, false otherwise. + */ + getCollapsible(): boolean; + + /** + * Return the overview map. + */ + getOverviewMap(): ol.Map; + + /** + * Collapse or expand the overview map according to the passed parameter. Will not do anything if the overview map isn't collapsible or if the current collapsed state is already the one requested. + * @param collapsed + */ + setCollapsed(collapsed: boolean): void; + + /** + * Set whether the overview map should be collapsible. + * @param collapsible + */ + setCollapsible(collapsible: boolean): void; } class Rotate extends Control { + constructor(opt_options?: olx.RotateOptions); } class ScaleLine extends Control { - + /** * Return the units to use in the scale line. */ getUnits(): ScaleLine.Units; - + /** * Set the units to use in the scale line. */ setUnits(units: ScaleLine.Units): void; - + } class Zoom extends Control{ @@ -3653,79 +4073,262 @@ declare namespace ol { } namespace interaction { - - class DoubleClickZoom { + /** + * Allows the user to zoom by double-clicking on the map. + */ + class DoubleClickZoom extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.DoubleClickZoomOptions); } - - class DragAndDrop { + /** + * Handles input of vector data by drag and drop. + */ + class DragAndDrop extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.DragAndDropOptions); } - + /** + * Events emitted by ol.interaction.DragAndDrop instances are instances of this type. + */ class DragAndDropEvent extends ol.events.Event { } - - class DragBox { + /** + * Allows the user to draw a vector box by clicking and dragging on the map, + * normally combined with an ol.events.condition that limits it to when the shift or other key is held down. + * This is used, for example, for zooming to a specific area of the map + * (see ol.interaction.DragZoom and ol.interaction.DragRotateAndZoom). + * + * This interaction is only supported for mouse devices. + */ + class DragBox extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.DragBoxOptions); + /** + * Returns geometry of last drawn box. + */ + getGeometry(): ol.geom.Polygon; } - - class DragPan { + /** + * Allows the user to pan the map by dragging the map. + */ + class DragPan extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.DragPanOptions); } - - class DragRotate { + /** + * Allows the user to rotate the map by clicking and dragging on the map, + * normally combined with an ol.events.condition that limits it to when the alt and shift keys are held down. + * + * This interaction is only supported for mouse devices. + */ + class DragRotate extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.DragRotateOptions); } - - class DragRotateAndZoom { + /** + * Allows the user to zoom and rotate the map by clicking and dragging on the map. + * By default, this interaction is limited to when the shift key is held down. + * + * This interaction is only supported for mouse devices. + * + * And this interaction is not included in the default interactions. + */ + class DragRotateAndZoom extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.DragRotateAndZoomOptions); } - - class DragZoom { + /** + * Allows the user to zoom the map by clicking and dragging on the map, + * normally combined with an ol.events.condition that limits it to when a key, shift by default, is held down. + * + * To change the style of the box, use CSS and the .ol-dragzoom selector, or your custom one configured with className. + */ + class DragZoom extends ol.interaction.DragBox { + constructor(opt_options?: olx.interaction.DragZoomOptions); } - + /** + * Interaction for drawing feature geometries. + */ class Draw extends ol.interaction.Pointer { - constructor(opt_options?: olx.interaction.DrawOptions) + constructor(opt_options?: olx.interaction.DrawOptions); } - + /** + * Events emitted by ol.interaction.Draw instances are instances of this type. + */ class DrawEvent extends ol.events.Event { + /** + * The feature being drawn. + */ + feature: ol.Feature; + /** + * The event target. + */ + target: ol.Object; + /** + * The event type. + */ + type: string; } - + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. + * User actions that change the state of the map. Some are similar to controls, but are not associated with a DOM element. + * For example, ol.interaction.KeyboardZoom is functionally the same as ol.control.Zoom, but triggered by a keyboard event + * not a button element event. Although interactions do not have a DOM element, + * some of them do render vectors and so are visible on the screen. + */ class Interaction extends ol.Object { + constructor (options: olx.interaction.InteractionOptions) + /** + * Return whether the interaction is currently active. + */ + getActive (): boolean; + /** + * Get the map associated with this interaction. + */ + getMap (): ol.Map; + /** + * Activate or deactivate the interaction. + */ + setActive (active: boolean): void; } - - class KeyboardPan { + /** + * Allows the user to pan the map using keyboard arrows. Note that, although this interaction is by default included in maps, + * the keys can only be used when browser focus is on the element to which the keyboard events are attached. + * By default, this is the map div, though you can change this with the keyboardEventTarget in ol.Map. + * document never loses focus but, for any other element, focus will have to be on, and returned to, + * this element if the keys are to function. See also ol.interaction.KeyboardZoom. + */ + class KeyboardPan extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.KeyboardPanOptions); } - - class KeyboardZoom { + /** + * Allows the user to zoom the map using keyboard + and -. Note that, although this interaction is by default included in maps, + * the keys can only be used when browser focus is on the element to which the keyboard events are attached. By default, + * this is the map div, though you can change this with the keyboardEventTarget in ol.Map. document never loses focus but, + * for any other element, focus will have to be on, and returned to, this element if the keys are to function. + * See also ol.interaction.KeyboardPan. + */ + class KeyboardZoom extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.KeyboardZoomOptions); } - + /** + * Interaction for modifying feature geometries. + */ class Modify extends ol.interaction.Pointer { - constructor(opt_options?: olx.interaction.ModifyOptions) + constructor(opt_options?: olx.interaction.ModifyOptions); } - - class MouseWheelZoom { + /** + * Allows the user to zoom the map by scrolling the mouse wheel. + */ + class MouseWheelZoom extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.MouseWheelZoomOptions); } - - class PinchRotate { + /** + * Allows the user to rotate the map by twisting with two fingers on a touch screen. + */ + class PinchRotate extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.PinchRotateOptions); } - - class PinchZoom { + /** + * Allows the user to zoom the map by pinching with two fingers on a touch screen. + */ + class PinchZoom extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.PinchZoomOptions); } - + /** + * Base class that calls user-defined functions on down, move and up events. This class also manages "drag sequences". + * + * When the handleDownEvent user function returns true a drag sequence is started. During a drag sequence the handleDragEvent + * user function is called on move events. The drag sequence ends when the handleUpEvent user function is called and returns false. + */ class Pointer extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.PointerOptions); } - + /** + * Interaction for selecting vector features. By default, selected features are styled differently, so this interaction can be used + * for visual highlighting, as well as selecting features for other actions, such as modification or output. There are three ways of + * controlling which features are selected: using the browser event as defined by the condition and optionally the toggle, + * add/remove, and multi options; a layers filter; and a further feature filter using the filter option. + * + * Selected features are added to an internal unmanaged layer. + */ class Select extends ol.interaction.Interaction { constructor(opt_options?: olx.interaction.SelectOptions); + /** + * Returns the associated vectorlayer of the (last) selected feature. + * Note that this will not work with any programmatic method like pushing features to collection. + */ getLayer(): ol.layer.Layer; + /** + * Get the selected features. + */ getFeatures(): ol.Collection; } - - class Snap { + /** + * Events emitted by ol.interaction.Select instances are instances of this type. + */ + class SelectEvent extends ol.events.Event { + /** + * Deselectd features array. + */ + deselected: Array; + /** + * Associated ol.MapBrowserEvent. + */ + mapBrowserEvent: ol.MapBrowserEvent; + /** + * Selected features array. + */ + selected: Array; + /** + * The event target. + */ + target: ol.Object; + /** + * The event type. + */ + type: string; + /** + * Stop event propagation. + */ + preventDefault(): void; + /** + * Stop event propagation. + */ + stopPropagation(): void; } - + /** + * Handles snapping of vector features while modifying or drawing them. The features can come from a ol.source.Vector or + * ol.Collection Any interaction object that allows the user to interact with the features using the mouse can benefit + * from the snapping, as long as it is added before. + * + *The snap interaction modifies map browser event coordinate and pixel properties to force the snap to occur + * to any interaction that them. + */ + class Snap extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.SnapOptions); + } + /** + * Set of interactions included in maps by default. Specific interactions can be excluded by setting the appropriate option + * to false in the constructor options, but the order of the interactions is fixed. If you want to specify a different order for + * interactions, you will need to create your own ol.interaction.Interaction instances and insert them into a ol.Collection in + * the order you want before creating your ol.Map instance. + */ function defaults(opts: olx.interaction.DefaultsOptions): ol.Collection; - interface DrawGeometryFunctionType { (coordinates: ol.Coordinate[], geom?: ol.geom.Geometry): ol.geom.Geometry; } + /** + * Function that takes coordinates and an optional existing geometry as arguments, and returns a geometry. + * The optional existing geometry is the geometry that is returned when the function is called without a second argument. + */ + interface DrawGeometryFunctionType { (coordinates: ol.Coordinate, geom?: ol.geom.Geometry): ol.geom.Geometry; } + /** + * A function that takes an ol.Feature or ol.render.Feature and an ol.layer.Layer and returns true if the feature + * may be selected or false otherwise. + */ interface SelectFilterFunction { (feature: ol.Feature | ol.render.Feature, layer: ol.layer.Layer): boolean; } + /** + * A function that takes a ol.MapBrowserEvent and two ol.Pixels and returns a {boolean}. + * If the condition is met, true should be returned. + */ + interface DragBoxEndConditionType { + (evt: ol.MapBrowserEvent, startPixel: ol.Pixel, endPixel: ol.Pixel): boolean + } } namespace layer { - /** * Abstract base class; normally only used for creating subclasses and not instantiated in apps. Note that with ol.layer.Base and all its subclasses, any property set in the options is set as a ol.Object property on the layer object, so is observable, and has get/set accessors. */ @@ -4061,7 +4664,7 @@ declare namespace ol { * @argument map. */ setMap(map: ol.Map): void; - + /** * Set Z-index of the layer, which is used to order layers before rendering. The default Z-index is 0. */ @@ -4254,12 +4857,13 @@ declare namespace ol { } class OSM extends XYZ { + constructor(opt_options?: olx.OSMOptions); } class Source extends ol.Object { - + constructor(options: any); - + /** * Get the projection of the source. * @return Projection. diff --git a/parse/parse.d.ts b/parse/parse.d.ts index 3a7d6b25f8..84fbc76027 100644 --- a/parse/parse.d.ts +++ b/parse/parse.d.ts @@ -1072,7 +1072,7 @@ declare namespace Parse { title?: string; } - interface SendOptions { + interface SendOptions extends UseMasterKeyOption { success?: () => void; error?: (error: Error) => void; } diff --git a/passport-local-mongoose/passport-local-mongoose.d.ts b/passport-local-mongoose/passport-local-mongoose.d.ts index ab2539a709..a3b5414c84 100644 --- a/passport-local-mongoose/passport-local-mongoose.d.ts +++ b/passport-local-mongoose/passport-local-mongoose.d.ts @@ -74,6 +74,9 @@ declare module 'mongoose' { plugin: (schema: PassportLocalSchema, options?: PassportLocalOptions) => void, options?: PassportLocalOptions ): this; + + // overload for the default mongoose plugin function + plugin(plugin: (schema: Schema, options?: Object) => void, opts?: Object): this; } export function model( diff --git a/pdfkit/pdfkit-tests.ts b/pdfkit/pdfkit-tests.ts index a21dfed815..86d6bc7e2e 100644 --- a/pdfkit/pdfkit-tests.ts +++ b/pdfkit/pdfkit-tests.ts @@ -24,7 +24,7 @@ doc.addPage({ }); doc.addPage({ - margin: { + margins: { top: 50, bottom: 50, left: 72, @@ -32,6 +32,10 @@ doc.addPage({ } }); +doc.addPage({ + layout: "landscape" +}); + doc.info.Title = "Sample"; doc.info.Author = "kila Mogrosso"; diff --git a/pdfkit/pdfkit.d.ts b/pdfkit/pdfkit.d.ts index 70836187e2..30c8d138da 100644 --- a/pdfkit/pdfkit.d.ts +++ b/pdfkit/pdfkit.d.ts @@ -231,7 +231,9 @@ declare namespace PDFKit { info?: DocumentInfo; autoFirstPage?: boolean; size?: number[]; - margin?: { top: number; left: number; bottom: number; right: number }|number; + margin?: number; + margins?: { top: number; left: number; bottom: number; right: number }; + layout?: "portrait" | "landscape"; bufferPages?: boolean; } diff --git a/phonegap-plugin-barcodescanner/phonegap-plugin-barcodescanner-tests.ts b/phonegap-plugin-barcodescanner/phonegap-plugin-barcodescanner-tests.ts new file mode 100644 index 0000000000..7b1f23a3fd --- /dev/null +++ b/phonegap-plugin-barcodescanner/phonegap-plugin-barcodescanner-tests.ts @@ -0,0 +1,29 @@ +/// +/// + +cordova.plugins.barcodeScanner.scan( + function (result) { + alert("We got a barcode\n" + + "Result: " + result.text + "\n" + + "Format: " + result.format + "\n" + + "Cancelled: " + result.cancelled); + }, + function (error) { + alert("Scanning failed: " + error); + }, + { + "preferFrontCamera" : true, // iOS and Android + "showFlipCameraButton" : true, // iOS and Android + "prompt" : "Place a barcode inside the scan area", // supported on Android only + "formats" : "QR_CODE,PDF_417", // default: all but PDF_417 and RSS_EXPANDED + "orientation" : "landscape" // Android only (portrait|landscape), default unset so it rotates with the device + } +); + + +cordova.plugins.barcodeScanner.encode(cordova.plugins.barcodeScanner.Encode.TEXT_TYPE, "http://www.nytimes.com", function(success) { + alert("encode success: " + success); + }, function(fail) { + alert("encoding failed: " + fail); + } +); \ No newline at end of file diff --git a/phonegap-plugin-barcodescanner/phonegap-plugin-barcodescanner.d.ts b/phonegap-plugin-barcodescanner/phonegap-plugin-barcodescanner.d.ts new file mode 100644 index 0000000000..85bde977b7 --- /dev/null +++ b/phonegap-plugin-barcodescanner/phonegap-plugin-barcodescanner.d.ts @@ -0,0 +1,37 @@ +// Type definitions for phonegap-plugin-barcodescanner +// Project: https://github.com/phonegap/phonegap-plugin-barcodescanner +// Definitions by: Nathan Ainslie +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface CordovaPlugins { + barcodeScanner: phonegapBarcode.BarcodeScanner; +} + +declare namespace phonegapBarcode { + interface BarcodeScanResult { + text: string; + format: string; + cancelled: boolean; + } + + interface BarcodeScanOptions { + preferFrontCamera?: boolean; + showFlipCameraButton?: boolean; + prompt?: string; + formats?: string; + orientation?: "landscape" | "portrait"; + } + + interface EncodingType { + TEXT_TYPE: any; + EMAIL_TYPE: any; + PHONE_TYPE: any; + SMS_TYPE: any; + } + + interface BarcodeScanner { + scan: (success: ((result: BarcodeScanResult) => any), failure?: ((err: any) => any), opts?: BarcodeScanOptions) => void; + encode: (encodingType: EncodingType, data: string, success: ((result: any) => any), failure?: ((err: any) => any)) => void; + Encode: EncodingType; + } +} \ No newline at end of file diff --git a/pino/pino-tests.ts b/pino/pino-tests.ts index 9a2c423222..4a1470db24 100644 --- a/pino/pino-tests.ts +++ b/pino/pino-tests.ts @@ -26,6 +26,12 @@ var instance = PINO({ } }) +var pretty = PINO.pretty() +var instance2 = PINO({ + name: 'app', + safe: true +}, pretty) + var logger = instance logger.child({ a: 'property' }).info('hello child!') diff --git a/pino/pino.d.ts b/pino/pino.d.ts index 1d7049cf05..0a51c49275 100644 --- a/pino/pino.d.ts +++ b/pino/pino.d.ts @@ -41,8 +41,8 @@ declare module 'pino' { } interface Pino { - (optionsOrStream?: LoggerOptions | stream.Writable): Logger - (options: LoggerOptions, stream: stream.Writable): Logger + (optionsOrStream?: LoggerOptions | stream.Writable | stream.Readable): Logger + (options: LoggerOptions, stream: stream.Writable | stream.Readable): Logger levels: { values: LevelLabelsToValues labels: LevelValuesToLabels diff --git a/point-in-polygon/point-in-polygon-tests.ts b/point-in-polygon/point-in-polygon-tests.ts new file mode 100644 index 0000000000..39851bd00e --- /dev/null +++ b/point-in-polygon/point-in-polygon-tests.ts @@ -0,0 +1,6 @@ +/// + +import inside from 'point-in-polygon'; + +const polygon = [ [ 1, 1 ], [ 1, 2 ], [ 2, 2 ], [ 2, 1 ] ]; +const inPolygon: boolean = inside([ 1.5, 1.5 ], polygon); diff --git a/point-in-polygon/point-in-polygon.d.ts b/point-in-polygon/point-in-polygon.d.ts new file mode 100644 index 0000000000..ceb85ecdec --- /dev/null +++ b/point-in-polygon/point-in-polygon.d.ts @@ -0,0 +1,8 @@ +// Type definitions for point-in-polygon +// Project: https://github.com/substack/point-in-polygon +// Definitions by: kogai +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'point-in-polygon' { + export default function inside(point: number[], polygon: number[][]): boolean; +} diff --git a/progress/progress.d.ts b/progress/progress.d.ts index 6eb55a917e..79c769deaa 100644 --- a/progress/progress.d.ts +++ b/progress/progress.d.ts @@ -114,6 +114,11 @@ declare module "progress" * Terminates a progress bar. */ terminate():void; + + /** + * Completed status of progress (Boolean) + */ + complete:boolean; } namespace ProgressBar { } diff --git a/protractor-helpers/protractor-helpers.d.ts b/protractor-helpers/protractor-helpers.d.ts index 20aad94c54..3966acd36e 100644 --- a/protractor-helpers/protractor-helpers.d.ts +++ b/protractor-helpers/protractor-helpers.d.ts @@ -108,4 +108,3 @@ declare module "protractor-helpers" { function getFilteredConsoleErrors() : webdriver.promise.IThenable; // TODO - discuss handling in IE } - diff --git a/quill/quill-tests.ts b/quill/quill-tests.ts index 3a87bd5948..172b5fd461 100644 --- a/quill/quill-tests.ts +++ b/quill/quill-tests.ts @@ -1,10 +1,6 @@ /// -/// - -//export var Quill = require("quill"); function test_quill() { - var quillEditor = new Quill('#editor', { modules: { @@ -14,6 +10,31 @@ function test_quill() { }); } +function test_deleteText() { + var quillEditor = new Quill('#editor'); + quillEditor.deleteText(0, 10); +} + +function test_disable() { + let quillEditor = new Quill('#Editor'); + quillEditor.disable(); +} + +function test_enable() { + let quillEditor = new Quill('#Editor'); + quillEditor.enable(); +} + +function test_getContents() { + var quillEditor = new Quill('#editor'); + var delta: QuillJS.DeltaStatic = quillEditor.getContents(); +} + +function test_getLength() { + var quillEditor = new Quill('#editor'); + var num: number = quillEditor.getLength(); +} + function test_getText() { var quillEditor = new Quill('#editor'); var strValue: string = quillEditor.getText(); @@ -29,26 +50,11 @@ function test_getText_substring() { var strValue: string = quillEditor.getText(0, 10); } -function test_getLength() { - var quillEditor = new Quill('#editor'); - var num: number = quillEditor.getLength(); -} - -function test_getContents() { - var quillEditor = new Quill('#editor'); - var delta: DeltaStatic = quillEditor.getContents(); -} - function test_insertText() { var quillEditor = new Quill('#editor'); quillEditor.insertText(0, "Hello World"); } -function test_deleteText() { - var quillEditor = new Quill('#editor'); - quillEditor.deleteText(0, 10); -} - function test_formatText() { var quillEditor = new Quill('#editor'); quillEditor.formatText(0, 5, 'bold', true); @@ -63,15 +69,28 @@ function test_formatText2() { }); } -function test_formatLine() { +function test_formatLine1() { + var quillEditor = new Quill('#editor'); + quillEditor.formatLine(1, 3, 'api'); +} + +function test_formatLine2() { var quillEditor = new Quill('#editor'); quillEditor.formatLine(1, 3, 'align', 'right'); } +function test_formatLine3() { + var quillEditor = new Quill('#editor'); + quillEditor.formatLine(1, 3, { + 'align': 'right', + 'bold': false, + }); +} + function test_insertEmbed() { var quillEditor = new Quill('#editor'); - quillEditor.insertEmbed(10, 'image', 'http://quilljs.com/images/cloud.png'); + quillEditor.insertEmbed(10, 'image', 'http://com/images/cloud.png'); } function test_updateContents() { @@ -96,12 +115,6 @@ function test_setContents() { ]); } -function test_setHTML() { - var quillEditor = new Quill('#editor'); - - quillEditor.setHTML('
Hello
'); -} - function test_setText() { var quillEditor = new Quill('#editor'); quillEditor.setText('Hello\n'); @@ -113,10 +126,10 @@ function test_getSelection() { var range = quillEditor.getSelection(); if (range) { - if (range.start == range.end) { - console.log('User cursor is at index', range.start); + if (range.index == range.length) { + console.log('User cursor is at index', range.index); } else { - var text = quillEditor.getText(range.start, range.end); + var text = quillEditor.getText(range.index, range.length); console.log('User has highlighted: ', text); } } else { @@ -129,11 +142,6 @@ function test_setSelection() { quillEditor.setSelection(0, 5); } -function test_prepareFormat() { - var quillEditor = new Quill('#editor'); - quillEditor.prepareFormat('bold', true); -} - function test_focus() { var quillEditor = new Quill('#editor'); quillEditor.focus(); @@ -144,14 +152,6 @@ function test_getBounds() { quillEditor.setText('Hello\nWorld\n'); } -function test_addModule() { - var quillEditor = new Quill('#editor'); - - var toolbar = quillEditor.addModule('toolbar', { - container: '#toolbar-container' - }); -} - function test_getModule() { var quillEditor = new Quill('#editor'); @@ -159,15 +159,28 @@ function test_getModule() var toolbar = quillEditor.getModule('toolbar'); } - -function test_addFormat() -{ - var quillEditor = new Quill('#editor'); - quillEditor.addFormat('strike', { tag: 'S', prepare: 'strikeThrough' }); -} - function test_addContainer() { var quillEditor = new Quill('#editor'); quillEditor.addContainer('ql-custom'); } + +function test_on_EventType1(){ + var quillEditor = new Quill('#editor'); + quillEditor.on('text-change', (newDelta, oldDelta, source)=>{ + // happened + }); + +} + +function test_PasteHTML() +{ + var quillEditor = new Quill('#editor'); + quillEditor.pasteHTML('

Quill Rocks

'); +} + +function test_PasteHTML2() +{ + var quillEditor = new Quill('#editor'); + quillEditor.pasteHTML(5, '

Quill Rocks

'); +} diff --git a/quill/quill.d.ts b/quill/quill.d.ts index 3cef088442..2e75e14c20 100644 --- a/quill/quill.d.ts +++ b/quill/quill.d.ts @@ -1,118 +1,95 @@ -// Type definitions for Quill +// Type definitions for Quill v1.0.3 // Project: http://quilljs.com // Definitions by: Sumit // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +declare namespace QuillJS { -declare interface DeltaStatic{ - ops? : Array; - retain?: any, - delete?: any, - insert?: any, - attributes?: any + export interface QuillOptionsStatic { + debug?: string, + modules?: { [key: string]: any }, + placeholder?: string, + readOnly?: boolean, + theme?: string + } + + export interface BoundsStatic { + left: number, + top: number, + height: number, + width: number + } + + export interface DeltaStatic { + ops?: Array; + retain?: any, + delete?: any, + insert?: any, + attributes?: any + } + + export interface RangeStatic { + new (): RangeStatic; + index: number; + length: number; + } + + type sourceType = "api" | "user" | "silent"; + type formatsType = { [key: string]: any }; + + export interface QuillStatic { + new (selector: string, options?: QuillOptionsStatic): QuillStatic; + deleteText(start: number, end: number, source?: sourceType): void; + disable(): void; + enable(enabled?: boolean): void; + getContents(start?: number, end?: number): DeltaStatic; + getLength(): number; + getText(start?: number, end?: number): string; + insertEmbed(index: number, type: string, url: string, source?: sourceType): void; + insertText(index: number, text: string, source?: sourceType): void; + insertText(index: number, text: string, format: string, value: string, source?: sourceType): void; + insertText(index: number, text: string, formats: formatsType, source?: sourceType): void; + pasteHTML(index: number, html: string, source?:sourceType): string; + pasteHTML(html:string, source?: sourceType): string; + setContents(delta: DeltaStatic, source?: sourceType): void; + setText(text: string, source?: sourceType): void; + update(source?: string): void; + updateContents(delta: DeltaStatic, source?: sourceType): void; + + format(name: string, value: any, source?: sourceType): void; + formatLine(index: number, length: number, source?: sourceType): void; + formatLine(index: number, length: number, format: string, value: any, source?: sourceType): void; + formatLine(index: number, length: number, formats: formatsType, source?: sourceType): void; + formatText(index: number, length: number, source?: sourceType): void; + formatText(index: number, length: number, format: string, value: any, source?: sourceType): void; + formatText(index: number, length: number, formats: formatsType, source?: sourceType): void; + getFormat(range?: RangeStatic): formatsType; + getFormat(index: number, length?: number): formatsType; + removeFormat(index: Number, length: Number, source?: sourceType): void; + + blur(): void; + focus(): void; + getBounds(index: number, length?: number): BoundsStatic; + getSelection(focus?: boolean): RangeStatic; + hasFocus(): boolean; + setSelection(index: number, length: number, source?: sourceType): void; + setSelection(range: RangeStatic, source?: sourceType): void; + + on(eventName: string, callback: ((delta: T, oldContents: T, source: string) => void) | + ((name: string, ...args: any[]) => void)): QuillStatic; + once(eventName: string, callback: (delta: DeltaStatic, source: string) => void): QuillStatic; + off(eventName: string, callback: (delta: DeltaStatic, source: string) => void): QuillStatic; + + debug(level: string): void; + import(path: string): any; + register(path: string, def: any, suppressWarning?: boolean): void; + register(defs: formatsType, suppressWarning?: boolean): void; + addContainer(className: string, refNode?: any): any; + getModule(name: string): any + } } -declare interface RangeStatic{ - new(): RangeStatic; - start: number; - end: number; -} - -declare interface QuillStatic { - new(selector: string, options?: Object):QuillStatic; - - on(eventName: string, callback: (delta: DeltaStatic, source: string) => void): EventEmitter2; - addModule(id: string, options: any) : Object; - - getText(): string; - getText(start: number): string; - getText(start: number, end: number): string; - - getLength(): number; - - getContents(): DeltaStatic; - getContents(start: number): DeltaStatic; - getContents(start: number, end: number): DeltaStatic; - - getHTML(): string; - - insertText(index: number, text: string): void; - insertText(index: number, text: string, name: string, value: string): void; - insertText(index: number, text: string, formats: any): void; - insertText(index: number, text: string, source: string) : void; - insertText(index: number, text: string, name: string, value: string, source: string): void; - insertText(index: number, text: string, formats: any, source: string): void; - - deleteText(start: number, end: number): void; - deleteText(start: number, end: number, source: string): void; - - formatText(start: number, end: number): void; - formatText(start: number, end: number, name: string, value: boolean): void; - formatText(start: number, end: number, formats: any): void; - formatText(start: number, end: number, source: string): void; - formatText(start: number, end: number, name: string, value: string, source: string): void; - formatText(start: number, end: number, formats: string, source: string): void; - - - formatLine(start: number, end: number): void; - formatLine(start: number, end: number, name: string, value: boolean): void; - formatLine(start: number, end: number, formats: any): void; - formatLine(start: number, end: number, source: string): void; - formatLine(start: number, end: number, name: string, value: string, source: string): void; - formatLine(start: number, end: number, formats: any, source: string): void; - - - insertEmbed(index: number, type: string, url: string): void; - insertEmbed(index: number, type: string, url: string, source: string): void; - - updateContents(delta: DeltaStatic): void; - - setContents(delta: DeltaStatic): void; - - setHTML(html: string): void; - - setText(text: string): void; - - getSelection(): RangeStatic; - - setSelection(start: number, end: number): void; - setSelection(start: number, end: number, source: string): void; - setSelection(range: RangeStatic): void; - setSelection(range: RangeStatic, source: string): void; - - prepareFormat(format: string, value: boolean): void; - - focus(): void; - - getBounds(index: number): any; - - registerModule(name: string, callback: (quill: QuillStatic, options: any) => {}): any; - - addModule(name: string, options: any): any; - - getModule(name: string): any; - - onModuleLoad(name: string, callback: (input: any) => {}): void; - - addFormat(name: string, config: any): void; - - addContainer(cssClass: string, before?: number): HTMLDivElement; -} - -declare module "Range" -{ - var Range: RangeStatic; - export = Range; -} - -declare var Delta: DeltaStatic; - -declare module "Delta"{ - export = Delta; -} - -declare var Quill: QuillStatic; +declare var Quill: QuillJS.QuillStatic; declare module "Quill" { export = Quill; diff --git a/radium/radium-tests.tsx b/radium/radium-tests.tsx index c8379b39b2..b8ad3928dd 100644 --- a/radium/radium-tests.tsx +++ b/radium/radium-tests.tsx @@ -43,6 +43,12 @@ class TestComponentWithConfig extends React.Component<{ a?: number }, {}> { }} > +
) diff --git a/radium/radium.d.ts b/radium/radium.d.ts index 1989156877..0cb4304d96 100644 --- a/radium/radium.d.ts +++ b/radium/radium.d.ts @@ -1,6 +1,6 @@ -// Type definitions for radium 0.17.1 +// Type definitions for radium 0.18.1 // Project: https://github.com/formidablelabs/radium -// Definitions by: Alex Gorbatchev , Philipp Holzer , Alexey Svetliakov +// Definitions by: Alex Gorbatchev , Philipp Holzer , Alexey Svetliakov , Mikael Hermansson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -19,10 +19,10 @@ declare module 'radium' { */ export interface StyleProps { /** - * An object of CSS rules to render. Each key of the rules object is a CSS selector and the value is an object - * of styles. If rules is empty, the component will render nothing. + * An object of styles, or an object of CSS rules to render. Each key of the rules object is a CSS + * selector and the value is an object of styles. If rules is empty, the component will render nothing. */ - rules: StyleRules; + rules: React.CSSProperties | StyleRules; /** * A string that any included selectors in rules will be appended to. * Use to scope styles in the component to a particular element. A good use case might be to generate a unique diff --git a/ravenjs/ravenjs-tests.ts b/ravenjs/ravenjs-tests.ts index db0ddd6932..eafa48871c 100644 --- a/ravenjs/ravenjs-tests.ts +++ b/ravenjs/ravenjs-tests.ts @@ -44,3 +44,5 @@ Raven.setUserContext({ Raven.captureMessage('Broken!'); Raven.captureMessage('Broken!', {tags: { key: "value" }}); + +Raven.showReportDialog(options); diff --git a/ravenjs/ravenjs.d.ts b/ravenjs/ravenjs.d.ts index ae891a7cda..e7e68b69aa 100644 --- a/ravenjs/ravenjs.d.ts +++ b/ravenjs/ravenjs.d.ts @@ -183,6 +183,8 @@ interface RavenStatic { /** If you need to conditionally check if raven needs to be initialized or not, you can use the isSetup function. It will return true if Raven is already initialized. */ isSetup(): boolean; + + showReportDialog(options: RavenOptions): void; } interface RavenTransportOptions { diff --git a/rbush/rbush-tests.ts b/rbush/rbush-tests.ts new file mode 100644 index 0000000000..305f4b7205 --- /dev/null +++ b/rbush/rbush-tests.ts @@ -0,0 +1,41 @@ +/// + +import * as rbush from 'rbush'; + +interface IndexedRect extends rbush.BBox { + index: number; +} + +function test_rbush() { + var index = rbush(); + + index + .clear() + .insert({ + minX: 0, + minY: 0, + maxX: 10, + maxY: 10, + index: 0, + }); + + index.all(); + index.fromJSON(index.toJSON()); + + index.search({ + minX: 5, + maxX: 15, + minY: 5, + maxY: 11, + }) + + index.load([ + { + minX: 0, + minY: 0, + maxX: 10, + maxY: 10, + index: 0, + } + ]) +} diff --git a/rbush/rbush.d.ts b/rbush/rbush.d.ts new file mode 100644 index 0000000000..6c04ce241c --- /dev/null +++ b/rbush/rbush.d.ts @@ -0,0 +1,110 @@ +// Type definitions for rbush 2.0.1 +// Project: https://github.com/mourner/rbush +// Definitions by: Dan Vanderkam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace rbush { + export interface BBox { + minX: number; + minY: number; + maxX: number; + maxY: number; + } + + export interface RBush { + /** + * Insert an item. To insert many items, use load(). + */ + insert(item: T): RBush; + + /** + * Bulk-insert the given data into the tree. + * + * Bulk insertion is usually ~2-3 times faster than inserting items one by one. + * After bulk loading (bulk insertion into an empty tree), subsequent query + * performance is also ~20-30% better. + * + * Note that when you do bulk insertion into an existing tree, it bulk-loads + * the given data into a separate tree and inserts the smaller tree into the + * larger tree. This means that bulk insertion works very well for clustered + * data (where items in one update are close to each other), but makes query + * performance worse if the data is scattered. + */ + load(items: T[]): RBush; + + /** + * Remove a previously inserted item. + * + * By default, RBush removes objects by reference. However, you can pass a + * custom equals function to compare by value for removal, which is useful + * when you only have a copy of the object you need removed (e.g. loaded + * from server). + */ + remove(item: T, equals?: (a: T, b: T) => boolean): RBush; + + /** Remove all items */ + clear(): RBush; + + /** + * Returns an array of data items (points or rectangles) that the given + * bounding box intersects. + * + * Note that the search method accepts a bounding box in {minX, minY, maxX, maxY} + * format regardless of the format specified in the constructor (which only + * affects inserted objects). + */ + search(bbox: BBox): T[]; + + /** Returns all items of the tree. */ + all(): T[]; + + /** + * Returns true if there are any items intersecting the given bounding box, + * otherwise false. + */ + collides(bbox: BBox): boolean; + + /** + * Export data as JSON object. + * + * Importing and exporting as JSON allows you to use RBush on both the server + * (using Node.js) and the browser combined, e.g. first indexing the data on + * the server and and then importing the resulting tree data on the client + * for searching. + * + * Note that the nodeSize option passed to the constructor must be the same + * in both trees for export/import to work properly. + */ + toJSON(): any; + + /** + * Import previously exported data. + * + * Importing and exporting as JSON allows you to use RBush on both the server + * (using Node.js) and the browser combined, e.g. first indexing the data on + * the server and and then importing the resulting tree data on the client + * for searching. + * + * Note that the nodeSize option passed to the constructor must be the same + * in both trees for export/import to work properly. + */ + fromJSON(data: any): RBush; + } + + interface IRBush { + /** + * Create a spatial index. + * + * An optional argument to rbush defines the maximum number of entries in a tree node. + * 9 (used by default) is a reasonable choice for most applications. Higher value means\ + * faster insertion and slower search, and vice versa. + */ + (nodeSize?: number): RBush; + (nodeSize: number, formatter: string[]): RBush; + } +} + +declare module 'rbush' { + const temp: rbush.IRBush; + export = temp; +} diff --git a/react-daterange-picker/react-daterange-picker-tests.tsx b/react-daterange-picker/react-daterange-picker-tests.tsx new file mode 100644 index 0000000000..98665fddb6 --- /dev/null +++ b/react-daterange-picker/react-daterange-picker-tests.tsx @@ -0,0 +1,178 @@ +/// +/// + +// Test app from https://github.com/onefinestay/react-daterange-picker/blob/master/example/index.jsx +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import * as moment from 'moment'; +import 'moment-range'; +import * as DateRangePicker from 'react-daterange-picker'; + +interface AppProps extends ReactDateRangePicker.Props { +} + +class App extends React.Component { + constructor(props: AppProps, context: any) { + super(props, context); + + this.state = {}; + } + + handleSelect(value: AppProps, states: any): void { + this.setState({value, states}); + } + + render(): any { + return ( +
+ +
+ + +
+
+ ); + } +} + +class DateSinglePicker extends React.Component { + constructor(props : AppProps, context: any) { + super(props, context); + + this.state = {}; + } + + handleSelect(value: AppProps) { + this.setState({value: value}); + } + + render() { + return ( +
+ +
+ +
+
+ ); + } +} + +export class Main extends React.Component { + + render() { + const stateDefinitions: ReactDateRangePicker.StateDefinitions = { + available: { + color: '#ffffff', + label: 'Available', + }, + enquire: { + color: '#ffd200', + label: 'Enquire', + }, + unavailable: { + selectable: false, + color: '#78818b', + label: 'Unavailable', + } + }; + + const dateRanges = [ + { + state: 'enquire', + range: moment.range( + moment().add(2, 'weeks').subtract(5, 'days'), + moment().add(2, 'weeks').add(6, 'days') + ), + }, + { + state: 'unavailable', + range: moment.range( + moment().add(3, 'weeks'), + moment().add(3, 'weeks').add(5, 'days') + ), + }, + ]; + + const initialStart = moment().add(1, 'weeks').startOf('day'); + const initialEnd = moment().add(1, 'weeks').add(3, 'days').startOf('day'); + const range = moment.range(initialStart, initialEnd); + + return ( +
+
+ +
+ +
+

Examples

+ +
+

Range with no date states

+ +
+ +
+

Range with day-long ranges allowed

+ +
+ +
+

Range with no minimum date

+ +
+
+

Single with no date states

+ +
+
+
+ ); + } +} + +const MainFactory = React.createFactory(Main); + +ReactDOM.render( + MainFactory(), + document.getElementById('app') +); diff --git a/react-daterange-picker/react-daterange-picker.d.ts b/react-daterange-picker/react-daterange-picker.d.ts new file mode 100644 index 0000000000..4754e77140 --- /dev/null +++ b/react-daterange-picker/react-daterange-picker.d.ts @@ -0,0 +1,77 @@ +// Type definitions for React Daterange Picker v1.1.0 +// Project: https://github.com/onefinestay/react-daterange-picker +// Definitions by: UNCOVER TRUTH Inc. +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// +/// + +declare module 'react-daterange-picker' { + import DateRangePicker = ReactDateRangePicker.DateRangePicker; + export = DateRangePicker; +} + +declare namespace ReactDateRangePicker { + import React = __React; + + interface Props extends React.Props<{}> { + bemBlock?: string; + bemNamespace?: string; + dateStates?: DateState[]; + defaultState?: string; + disableNavigation?: boolean; + // Use Number Literal Types after TypeScript 2.0 GA released. + firstOfWeek?: number; // React.PropTypes.oneOf([0, 1, 2, 3, 4, 5, 6]) + helpMessage?: string; + initialFromValue?: boolean; + initialDate?: Date; + initialMonth?: number; + initialYear?: number; + initialRange?: {}; + maximumDate?: Date; + minimumDate?: Date; + numberOfCalendars?: number; + onHighlightDate?(date: Date): void; + onHighlightRange?(date: Date): void; + onSelect?(value: Props): void; + onSelectStart?(value: moment.Moment): void; + paginationArrowComponent?: PaginationArrow; + selectedLabel?: string; + selectionType?: 'single' |'range'; + singleDateRange?: boolean; + showLegend?: boolean; + stateDefinitions?: StateDefinitions; + value?: moment.Moment | moment.Range; + } + + interface DateState { + state: string; + range: moment.Range; + } + + interface StateDefinitions { + [key: string]: StateDefinition; + } + + interface StateDefinition { + color: string; + label: string; + selectable?: boolean; + } + + interface PaginationArrowProps extends React.Props<{}> { + disabled?: boolean; + onTrigger?(): void; + direction?: 'next' | 'previous'; + } + + class PaginationArrow extends React.Component { + } + + class DateRangePicker extends React.Component { + } + + namespace DateRangePicker { + } +} diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index fb19dca42d..5df21529e6 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -247,7 +247,7 @@ declare namespace ReactRouter { isActive: (pathOrLoc: H.LocationDescriptor, indexOnly?: boolean) => boolean } - function withRouter>(component: C): C + function withRouter | React.StatelessComponent | React.PureComponent>(component: C): C /* utils */ diff --git a/react-select/react-select-tests.tsx b/react-select/react-select-tests.tsx index de45b52d32..3b2ce8b429 100644 --- a/react-select/react-select-tests.tsx +++ b/react-select/react-select-tests.tsx @@ -5,7 +5,7 @@ import * as React from "react"; import * as ReactDOM from "react-dom"; -import { Option, ReactSelectProps, ReactAsyncSelectProps, MenuRendererProps } from "react-select-props"; +import { Option, ReactSelectProps, ReactAsyncSelectProps, ReactCreatableSelectProps, MenuRendererProps } from "react-select-props"; import Select = require("react-select"); const CustomOption = React.createClass({ @@ -104,7 +104,6 @@ class SelectTest extends React.Component, {}> { key: "1", options: options, optionRenderer: optionRenderer, - allowCreate: true, autofocus: true, autosize: true, clearable: true, @@ -200,3 +199,28 @@ class SelectAsyncTest extends React.Component, {}> { } } + +class SelectCreatableTest extends React.Component, {}> { + + render() { + const options: Option[] = [{ label: "Foo", value: "bar" }]; + const onChange = (value: any) => console.log(value); + + const creatableSelectProps: ReactCreatableSelectProps = { + name: "test-creatable-select", + value: "bar", + options: options, + onChange: onChange, + isOptionUnique: () => { return true; }, + isValidNewOption: () => { return true; }, + newOptionCreator: () => { return { label: "NewFoo", value: "newBar" }; }, + promptTextCreator: () => { return ""; }, + shouldKeyDownEventCreateNewOption: () => { return true; } + }; + + return
+ +
+ } + +} diff --git a/react-select/react-select.d.ts b/react-select/react-select.d.ts index f58cdafbdb..701d5efc4a 100644 --- a/react-select/react-select.d.ts +++ b/react-select/react-select.d.ts @@ -1,6 +1,6 @@ // Type definitions for react-select v1.0.0 // Project: https://github.com/JedWatson/react-select -// Definitions by: ESQUIBET Hugo , Gilad Gray +// Definitions by: ESQUIBET Hugo , Gilad Gray , Izaak Baker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -68,12 +68,6 @@ declare namespace ReactSelect { * @default 'Add "{label}"?' */ addLabelText?: string; - /** - * allow new options to be created in multi mode (displays an "Add