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-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/angularjs/angular.d.ts b/angularjs/angular.d.ts index 3d5e5a7b19..1831bc0493 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -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; @@ -1411,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/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-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index 90f56d0702..b950790058 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; diff --git a/azure-mobile-apps/azure-mobile-apps-tests.ts b/azure-mobile-apps/azure-mobile-apps-tests.ts index 093932c2fb..6b994b4f05 100644 --- a/azure-mobile-apps/azure-mobile-apps-tests.ts +++ b/azure-mobile-apps/azure-mobile-apps-tests.ts @@ -84,4 +84,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..436d88b3cb 100644 --- a/azure-mobile-apps/azure-mobile-apps.d.ts +++ b/azure-mobile-apps/azure-mobile-apps.d.ts @@ -215,7 +215,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 +223,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/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/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/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 816f0e7c70..aa17cd331e 100644 --- a/cucumber/cucumber-tests.ts +++ b/cucumber/cucumber-tests.ts @@ -1,7 +1,9 @@ /// +/// function StepSample() { type Callback = cucumber.CallbackStepDefinition; + type Table = cucumber.TableDefinition; var step = this; var hook = this; @@ -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 dc5c44ef33..a415a478e2 100644 --- a/cucumber/cucumber.d.ts +++ b/cucumber/cucumber.d.ts @@ -10,8 +10,17 @@ declare namespace cucumber { (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/dva/dva.d.ts b/dva/dva.d.ts index b6d7e78248..0cf7206e63 100644 --- a/dva/dva.d.ts +++ b/dva/dva.d.ts @@ -14,13 +14,13 @@ declare module 'dva' { use: (hooks:Object)=>void, /** dva bootstrap */ - start: (selector?:Object)=>void, + start: (selector?:String|HTMLElement)=>void, /** dva add model */ model: (model:Object)=>void, /** dva setting router */ - router: (router:Object)=>void, + router: (router:Object)=>Object|JSX.Element, }; } @@ -34,7 +34,7 @@ declare module 'dva/router' { history?: Object } export class Router extends React.Component { - render(): JSX.Element + render():JSX.Element } @@ -43,15 +43,14 @@ declare module 'dva/router' { component?: React.ReactNode } export class Route extends React.Component { - render(): JSX.Element + render():JSX.Element } -} -/** - * https://github.com/reactjs/react-router-redux - */ -declare module 'dva/routerRedux' { - export default Object; + /** + * https://github.com/reactjs/react-router-redux + */ + export class routerRedux {} + } /** 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/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/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/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/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/material-ui/material-ui.d.ts b/material-ui/material-ui.d.ts index 2913c0bd57..f9dcbcfb38 100644 --- a/material-ui/material-ui.d.ts +++ b/material-ui/material-ui.d.ts @@ -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/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-4-tests.ts b/node/node-4-tests.ts index 5a25f1fa20..0162951454 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -24,22 +24,44 @@ 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"); + + // TODO: assert.deepStrictEqual + + 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*"); + // TODO: assert.fail + + // TODO: assert.ifError + + assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses === comparator"); + + // TODO: assert.notDeepStrictEqual + + // TODO: assert.notEqual + + assert.notStrictEqual(2, "2", "uses === comparator"); + + // TODO: assert.ok + + // TODO: assert.strictEqual + + assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); + } +} //////////////////////////////////////////////////// /// Events tests : http://nodejs.org/api/events.html @@ -92,30 +114,59 @@ namespace events_tests { //////////////////////////////////////////////////// /// 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); + 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-'); + } + +} class Networker extends events.EventEmitter { constructor() { @@ -125,21 +176,6 @@ class Networker extends events.EventEmitter { } } -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 +271,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 @@ -416,11 +465,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 +567,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 +651,8 @@ namespace path_tests { ext : ".txt", name : "file" }); -// returns -// '/home/user/dir/file.txt' + // returns + // '/home/user/dir/file.txt' } //////////////////////////////////////////////////// @@ -717,20 +768,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 @@ -841,6 +900,22 @@ namespace errors_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... + + var _p: NodeJS.Process = process; + _p = p; + assert(p === process); + } +} + /////////////////////////////////////////////////////////// /// Console Tests : https://nodejs.org/api/console.html /// /////////////////////////////////////////////////////////// @@ -851,4 +926,3 @@ namespace console_tests{ assert(c === console); } } - diff --git a/node/node-4.d.ts b/node/node-4.d.ts index 6c45fa2f75..daebb4585e 100644 --- a/node/node-4.d.ts +++ b/node/node-4.d.ts @@ -2403,6 +2403,57 @@ 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" { diff --git a/node/node-tests.ts b/node/node-tests.ts index b250a732dc..651df8ca09 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -26,22 +26,44 @@ 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"); + + // TODO: assert.deepStrictEqual + + 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*"); + // TODO: assert.fail + + // TODO: assert.ifError + + assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses === comparator"); + + // TODO: assert.notDeepStrictEqual + + // TODO: assert.notEqual + + assert.notStrictEqual(2, "2", "uses === comparator"); + + // TODO: assert.ok + + // TODO: assert.strictEqual + + assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); + } +} //////////////////////////////////////////////////// /// Events tests : http://nodejs.org/api/events.html @@ -102,30 +124,94 @@ namespace events_tests { //////////////////////////////////////////////////// /// 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); + { + 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); + } +} class Networker extends events.EventEmitter { constructor() { @@ -135,37 +221,6 @@ class Networker extends events.EventEmitter { } } -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); -}); - /////////////////////////////////////////////////////// /// Buffer tests : https://nodejs.org/api/buffer.html /////////////////////////////////////////////////////// @@ -327,23 +382,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 @@ -479,11 +547,11 @@ 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); //////////////////////////////////////////////////// @@ -572,14 +640,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 @@ -675,82 +745,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 : "/", @@ -759,8 +829,8 @@ namespace path_tests { ext : ".txt", name : "file" }); -// returns -// '/home/user/dir/file.txt' + // returns + // '/home/user/dir/file.txt' } //////////////////////////////////////////////////// @@ -879,20 +949,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 @@ -1028,10 +1106,19 @@ namespace errors_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; + assert(p === process); } } @@ -1045,3 +1132,155 @@ namespace console_tests{ assert(c === console); } } + +/***************************************************************************** + * * + * 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 12d87d2c1e..820521e43c 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -885,22 +885,144 @@ 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 userInfo(options?: {encoding: string}): { username: string, uid: number, gid: number, shell: any, homedir: string } + 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 function tmpDir(): string; + export function getNetworkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; export var EOL: string; + export function endianness(): "BE" | "LE"; } declare module "https" { @@ -1423,14 +1545,14 @@ declare module "dgram" { } interface SocketOptions { - type: string; + 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; - interface Socket extends events.EventEmitter { + 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; @@ -1717,14 +1839,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; @@ -2056,18 +2187,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; + 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 { @@ -2075,13 +2214,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 { @@ -2134,7 +2280,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; @@ -2142,6 +2288,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; @@ -2154,72 +2312,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): Buffer; - sign(private_key: string, output_format: 'latin1' | 'hex' | 'base64'): 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; + 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: 'latin1' | 'hex' | 'base64'): 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; @@ -2227,25 +2406,34 @@ 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 { - computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string | Buffer; - generateKeys(encoding?: string, format?: string): string | Buffer; - getPrivateKey(encoding?: string): string | Buffer; - getPublicKey(encodind?: string): string | Buffer; - setPrivateKey(private_key: string | Buffer, encoding?: string): void; - setPublicKey(publick_key: string | Buffer, encoding?: string): void; + 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; } @@ -2253,102 +2441,108 @@ declare module "crypto" { 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; + } + + 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 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" { @@ -2740,12 +2934,27 @@ declare module "constants" { 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; @@ -2757,4 +2966,4 @@ declare module "timers" { declare module "console" { export = console; -} \ No newline at end of file +} diff --git a/openlayers/openlayers.d.ts b/openlayers/openlayers.d.ts index 319b770cc3..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,27 @@ 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; @@ -230,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. */ @@ -581,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; } } @@ -1146,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. */ @@ -2485,6 +2851,40 @@ 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 { @@ -3673,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. */ @@ -4274,6 +4857,7 @@ declare namespace ol { } class OSM extends XYZ { + constructor(opt_options?: olx.OSMOptions); } class Source extends ol.Object { 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/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/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