diff --git a/acl/acl.d.ts b/acl/acl.d.ts index 06defa2449..d222f9ebb6 100644 --- a/acl/acl.d.ts +++ b/acl/acl.d.ts @@ -3,7 +3,7 @@ // Definitions by: Qubo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /// /// diff --git a/amcharts/AmCharts.d.ts b/amcharts/AmCharts.d.ts index 27998956b8..bbd732bb1c 100644 --- a/amcharts/AmCharts.d.ts +++ b/amcharts/AmCharts.d.ts @@ -961,6 +961,10 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val @Default 150 */ hideBalloonTime: number; + /** Allows changing language easily. + * Note, you should include the language.js file from amcharts/lang or ammap/lang folder and then use variable name used in this file, like chart.language = "de"; + * Note, for maps this works differently - you use language only for country names, as there are no other strings in the maps application. */ + language: string; /** Legend of a chart. */ legend: AmLegend; /** Reference to the div of the legend. */ @@ -989,6 +993,8 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val prefixesOfBigNumbers: any[]; /** Prefixes which are used to make small numbers shorter: 2μ instead of 0.000002, etc. Prefixes are used on value axes and in the legend. To enable prefixes, set usePrefixes property to true. [{number:1e-24, prefix:"y"},{number:1e-21, prefix:"z"},{number:1e-18, prefix:"a"},{number:1e-15, prefix:"f"},{number:1e-12, prefix:"p"},{number:1e-9, prefix:"n"},{number:1e-6, prefix:"μ"},{number:1e-3, prefix:"m"}] */ prefixesOfSmallNumbers: any[]; + /** A config object for Responsive plugin. */ + responsive: any; /** Theme of a chart. Config files of themes can be found in amcharts/themes/ folder. More info about using themes. */ theme: string; /** Thousands separator. diff --git a/amplitude-js/v2/amplitude-js-tests.ts b/amplitude-js/v2/amplitude-js-tests.ts new file mode 100644 index 0000000000..3e69d7c867 --- /dev/null +++ b/amplitude-js/v2/amplitude-js-tests.ts @@ -0,0 +1,87 @@ +// Tests for Amplitude SDK TypeScript definitions + +/// + +module Amplitude.Tests { + function all() { + amplitude.init('YOUR_API_KEY_HERE', null, { + // optional configuration options + saveEvents: true, + includeUtm: true, + includeReferrer: true, + batchEvents: true, + eventUploadThreshold: 50 + }); + amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE', null, () => {}); + + amplitude.logEvent('EVENT_IDENTIFIER_HERE'); + amplitude.setUserId('USER_ID_HERE'); + amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE'); + amplitude.setUserId(null); // not string 'null' + amplitude.setVersionName('VERSION_NAME_HERE'); + + amplitude.regenerateDeviceId(); + amplitude.setDeviceId('CUSTOM_DEVICE_ID'); + + amplitude.logEvent('EVENT_IDENTIFIER_HERE', { + 'color': 'blue', + 'age': 20, + 'key': 'value' + }); + amplitude.logEvent("EVENT_IDENTIFIER_HERE", null, (httpCode, response) => { }); + + let identify = new amplitude.Identify().set('gender', 'female').set('age', 20); + amplitude.identify(identify); + + identify = new amplitude.Identify().setOnce('sign_up_date', '08/24/2015'); + amplitude.identify(identify); + + identify = new amplitude.Identify().setOnce('sign_up_date', '09/14/2015'); + amplitude.identify(identify); + + identify = new amplitude.Identify().unset('gender').unset('age'); + amplitude.identify(identify); + + identify = new amplitude.Identify().add('karma', 1).add('friends', 1); + amplitude.identify(identify); + + identify = new amplitude.Identify().append('ab-tests', 'new-user-test').append('some_list', [1, 2, 3, 4, 'values']); + amplitude.identify(identify); + + identify = new amplitude.Identify().prepend('ab-tests', 'new-user-test').prepend('some_list', [1, 2, 3, 4, 'values']); + amplitude.identify(identify); + + identify = new amplitude.Identify() + .set('karma', 10) + .add('karma', 1) + .unset('karma'); + amplitude.identify(identify); + + identify = new amplitude.Identify() + .set('colors', ['rose', 'gold']) + .append('ab-tests', 'campaign_a') + .append('existing_list', [4, 5]); + amplitude.identify(identify); + + amplitude.setUserProperties({ + gender: 'female', + age: 20 + }); + + amplitude.clearUserProperties(); + + amplitude.setOptOut(true); + amplitude.setOptOut(false); + + amplitude.setGroup('orgId', '15'); + amplitude.setGroup('sport', ['soccer', 'tennis']); + + // TODO: Implement those. + /* + var revenue = new amplitude.Revenue().setProductId('com.company.productId').setPrice(3.99).setQuantity(3); + amplitude.logRevenueV2(revenue); + + amplitude.logEventWithGroups('initialize_game', { 'key': 'value' }, { 'sport': 'soccer' }); + */ + } +} diff --git a/amplitude-js/v2/amplitude-js.d.ts b/amplitude-js/v2/amplitude-js.d.ts new file mode 100644 index 0000000000..613f5ad5d8 --- /dev/null +++ b/amplitude-js/v2/amplitude-js.d.ts @@ -0,0 +1,61 @@ +// Type definitions for Amplitude SDK 2.12.1 +// Project: https://github.com/amplitude/Amplitude-Javascript +// Definitions by: Arvydas Sidorenko +// Definitions: https://github.com/Asido/DefinitelyTyped + +declare module amplitude { + interface Config { + batchEvents?: boolean; + cookieExpiration?: number; + cookieName?: string; + deviceId?: string; + domain?: string; + eventUploadPeriodMillis?: number; + eventUploadThreshold?: number; + includeReferrer?: boolean; + includeUtm?: boolean; + language?: string; + optOut?: boolean; + platform?: string; + saveEvents?: boolean; + savedMaxCount?: number; + sessionTimeout?: number; + uploadBatchSize?: number; + } + + export class Identify { + set(key: string, value: any): Identify; + setOnce(key: string, value: any): Identify; + add(key: string, value: number): Identify; + append(key: string, value: any): Identify; + prepend(key: string, value: any): Identify; + + unset(key: string): Identify; + } + + export function init(apiKey: string): void; + export function init(apiKey: string, userId: string): void; + export function init(apiKey: string, userId: string, options: Config): void; + export function init(apiKey: string, userId: string, options: Config, callback: () => void): void; + + export function setVersionName(version: string): void; + export function setUserId(userId: string): void; + + export function setDeviceId(id: string): void; + export function regenerateDeviceId(): void; + + export function identify(identify: Identify): void; + + export function setUserProperties(properties: Object): void; + export function clearUserProperties(): void; + + export function setOptOut(optOut: boolean): void; + + export function setGroup(groupType: string, groupName: string | string[]): void; + + export function logEvent(event: string): void; + export function logEvent(event: string, data: Object): void; + export function logEvent(event: string, data: Object, callback: (httpCode: number, response: any) => void): void; + + export var options: Config; +} diff --git a/angular-es/angular-es-tests.ts b/angular-es/angular-es-tests.ts new file mode 100644 index 0000000000..2e44d5d0a8 --- /dev/null +++ b/angular-es/angular-es-tests.ts @@ -0,0 +1,157 @@ +/// + +// +// @Component +// +import { Component } from 'angular-es'; +@Component({ + selector: '', + template: '' +}) +class MyComponentController { + +} + +// +// @Config +// +import { Config } from 'angular-es'; + +@Config() +class MyConfig { + +} + +// +// @Constant +// +import { Constant } from 'angular-es'; + +@Constant('MyConstant') +class MyConstant { + foo = 'foo'; + bar = 'bar'; +} + +// +// @Controller +// +import { Controller } from 'angular-es'; + +@Controller('MyController') +class MyController { + +} + +// +// @Decorator +// +import { Decorator } from 'angular-es'; + +@Decorator('MyServiceDecorator') +class MyServiceDecorator { + +} + +// +// @Directive +// +import { Directive } from 'angular-es'; + +@Directive('MyDirective') +class MyDirective { + +} + +// +// @Factory +// +import { Factory } from 'angular-es'; + +@Factory('MyFactory') +class MyFactory { +} + +// +// @Filter +// +import { Filter } from 'angular-es'; + +@Filter('MyFilter') +class MyFilter { +} + +// +// @Inject +// +import { Inject } from 'angular-es'; + +@Inject('fooBar') +class MyFooService { + + @Inject('bazBar') + myMethod(bazBar: Object) { + } + + constructor(fooBar: Object) { + } +} + +// +// @InjectAsProperty +// +import { InjectAsProperty } from 'angular-es'; + +@InjectAsProperty('fooBar') +class MyFooBarService { + fooBar: Object; + + myMethod() { + this.fooBar !== undefined; + } +} + +// +// @Module +// +import { Module } from 'angular-es'; + +@Module('my.module') +@Service('MyModuleService') +class MyModuleService { +} + +// +// @Provider +// +import { Provider } from 'angular-es'; + +@Provider('MyProvider') +class MyProvider { +} + +// +// @Run +// +import { Run } from 'angular-es'; + +@Run() +class MyRunBlock { +} + +// +// @Service +// +import { Service } from 'angular-es'; + +@Service('MyService') +class MyService { +} +// +// @Value +// +import { Value } from 'angular-es'; + +@Value('MyValue') +class MyValue { +} diff --git a/angular-es/angular-es.d.ts b/angular-es/angular-es.d.ts new file mode 100644 index 0000000000..10979ae15c --- /dev/null +++ b/angular-es/angular-es.d.ts @@ -0,0 +1,187 @@ +// Type definitions for angular-es v0.0.3 +// Project: https://github.com/mbutsykin/angular-es +// Definitions by: mbutsykin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'angular-es' { + + interface ClassDecorator { + (target: TFunction): TFunction|void; + } + + interface MethodDecorator { + (target: Object, propertyKey: string|symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor|void; + } + + /** + * Decorated target + */ + interface ngESDecorator extends ClassDecorator, MethodDecorator { + (target: Object|Function, + ngName?: string, + ngArguments?: Array, + ngType?: string, + injectAsProperty?: Array): void; + } + + /** + * Component interface + * @see https://docs.angularjs.org/guide/component + */ + interface iComponent { + template: string, + selector: string, + controllerAs?: string, + require?: string, + templateUrl?: string, + transclude?: string, + bindings?: Object + } + + /** + * Register component + * + * @param {Object} component - component config + * + * @returns {ngESDecorator} - decorated class + */ + var Component: (component: iComponent) => ngESDecorator; + + /** + * Register config block + */ + var Config: () => ngESDecorator; + + /** + * Register constant + * + * @param {string} name - constant name + * + * @returns {ngESDecorator} - decorated class + */ + var Constant: (name: string) => ngESDecorator; + + /** + * Register controller + * + * @param {string} name - controller name + * + * @returns {ngESDecorator} - decorated class + */ + var Controller: (name: string) => ngESDecorator; + + /** + * Register decorator + * + * @param {string} name - provider name to decorate + * + * @returns {ngESDecorator} - decorated class + */ + var Decorator: (name: string) => ngESDecorator; + + /** + * Register directive + * + * @param {string} name - directive selector, can be in hyphen-case + * + * @returns {ngESDecorator} - decorated class + */ + var Directive: (name: string) => ngESDecorator; + + /** + * Register factory + * + * @param {string} name - factory name + * + * @returns {ngESDecorator} - decorated class + */ + var Factory: (name: string) => ngESDecorator; + + /** + * Register filter + * + * @param {string} name - filter name + * + * @returns {ngESDecorator} - decorated class + */ + var Filter: (name: string) => ngESDecorator; + + /** + * Add $inject property to target + * + * @param {Array} dependencies - dependencies to inject + * + * @returns {ngESDecorator} - decorated class + */ + var Inject: (...dependencies: Array) => ngESDecorator; + + /** + * Inject dependencies as properties to target + * + * @param {Array} dependencies - dependencies to inject + * + * @returns {ngESDecorator} - decorated class + */ + var InjectAsProperty: (...dependencies: Array) => ngESDecorator; + + /** + * Attach target to the specified module + * + * @param {string} name - module name + * + * @returns {ngESDecorator} - decorated class + */ + var Module: (name: string) => ngESDecorator; + + /** + * Register provider + * + * @param {string} name - provider name + * + * @returns {ngESDecorator} - decorated class + */ + var Provider: (name: string) => ngESDecorator; + + /** + * Register run block + * + * @returns {ngESDecorator} - decorated class + */ + var Run: () => ngESDecorator; + + /** + * Register service + * + * @param {string} name - service name + * + * @returns {ngESDecorator} - decorated class + */ + var Service: (name: string) => ngESDecorator; + + /** + * Register value + * + * @param {string} name - value name + * + * @returns {ngESDecorator} - decorated class + */ + var Value: (name: string) => ngESDecorator; + + export { + Component, + Config, + Constant, + Controller, + Decorator, + Directive, + Factory, + Filter, + Inject, + InjectAsProperty, + Module, + Provider, + Run, + Service, + Value, + } +} diff --git a/angular-gettext/angular-gettext.d.ts b/angular-gettext/angular-gettext.d.ts index 48734d4433..84721d8dc0 100644 --- a/angular-gettext/angular-gettext.d.ts +++ b/angular-gettext/angular-gettext.d.ts @@ -51,12 +51,12 @@ declare namespace angular.gettext { /** Get the correct pluralized (but untranslated) string for the value of n. */ getStringForm(string: string, n: number): string; - /** Translate a string with the given context. Uses Angular.JS interpolation, so something like this will do what you expect: + /** Translate a string with the given scope. Uses Angular.JS interpolation, so something like this will do what you expect: * var hello = gettextCatalog.getString("Hello {{name}}!", { name: "Ruben" }); * // var hello will be "Hallo Ruben!" in Dutch. - * The context parameter is optional: pass null (or don't pass anything) if you're not using it: this skips interpolation and is a lot faster. + * The scope parameter is optional: pass null (or don't pass anything) if you're not using it: this skips interpolation and is a lot faster. */ - getString(string: string, context?: any): string; + getString(string: string, scope?: any, context?: string): string; /** Translate a plural string with the given context. */ getPlural(n: number, string: string, stringPlural: string, context?: any): string; diff --git a/angular-ui-notification/angular-ui-notification-tests.ts b/angular-ui-notification/angular-ui-notification-tests.ts new file mode 100644 index 0000000000..3039a74c9e --- /dev/null +++ b/angular-ui-notification/angular-ui-notification-tests.ts @@ -0,0 +1,30 @@ +/// + +function TestNotifications(NotificationProvider: angular.uiNotification.INotificationProvider, Notification: angular.uiNotification.INotificationService) { + NotificationProvider.setOptions({ + delay: 10000, + startTop: 20, + startRight: 10, + verticalSpacing: 20, + horizontalSpacing: 20, + positionX: 'left', + positionY: 'bottom' + }); + + Notification.primary('Primary notification'); + Notification('Primary notification'); + + Notification.success('Success notification'); + + Notification({message: 'Warning notification'}, 'warning'); + + Notification({message: 'Primary notification', title: 'Primary notification'}); + + Notification.error({message: 'Error notification 1s', delay: 1000}); + + Notification.success({message: 'Success notification
Some other content
This is a link
', title: 'Html content'}); + + Notification.error({message: 'Error Bottom Right', positionY: 'bottom', positionX: 'right'}); + + Notification.error({message: 'Error notification 1s', replaceMessage: true}); +} \ No newline at end of file diff --git a/angular-ui-notification/angular-ui-notification.d.ts b/angular-ui-notification/angular-ui-notification.d.ts new file mode 100644 index 0000000000..48215e6d42 --- /dev/null +++ b/angular-ui-notification/angular-ui-notification.d.ts @@ -0,0 +1,82 @@ +// Type definitions for angular-ui-notification +// Project: https://github.com/alexcrack/angular-ui-notification +// Definitions by: Kamil Rojewski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace angular.uiNotification { + // Taken from angular to avoid dependency + interface IPromise { + /** + * Regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected. + * The successCallBack may return IPromise for when a $q.reject() needs to be returned + * This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method. + */ + then(successCallback: (promiseValue: T) => IPromise|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; + + /** + * Shorthand for promise.then(null, errorCallback) + */ + catch(onRejected: (reason: any) => IPromise|TResult): IPromise; + + /** + * Allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information. + * + * Because finally is a reserved word in JavaScript and reserved keywords are not supported as property names by ES3, you'll need to invoke the method like promise['finally'](callback) to make your code IE8 and Android 2.x compatible. + */ + finally(finallyCallback: () => any): IPromise; + } + + type XPosition = 'right'|'left'|'center'; + type YPosition = 'top'|'bottom'; + + type MessageType = 'primary'|'info'|'success'|'warning'|'error'; + + interface IGlobalMessageOptions { + delay?: number; + startTop?: number; + startRight?: number; + verticalSpacing?: number; + horizontalSpacing?: number; + positionX?: XPosition; + positionY?: YPosition; + replaceMessage?: boolean; + templateUrl?: string; + onClose?: (element: any) => any; + closeOnClick?: boolean; + maxCount?: number; + } + + interface IMessageOptions { + title?: string; + message?: string; + templateUrl?: string; + delay?: number; + type?: MessageType; + positionX?: XPosition; + positionY?: YPosition; + replaceMessage?: boolean; + closeOnClick?: boolean; + } + + interface INotificationScope { + kill(isHard: boolean): void; + } + + interface INotificationProvider { + setOptions(options: IGlobalMessageOptions): void; + } + + type Message = string|IMessageOptions; + + interface INotificationService { + primary(message: Message): IPromise; + info(message: Message): IPromise; + success(message: Message): IPromise; + warning(message: Message): IPromise; + error(message: Message): IPromise; + + clearAll(): void; + + (message: Message, type?: MessageType): IPromise; + } +} diff --git a/angularjs/angular-component-router.d.ts b/angularjs/angular-component-router.d.ts index 3b037b58b1..94d7dd7359 100644 --- a/angularjs/angular-component-router.d.ts +++ b/angularjs/angular-component-router.d.ts @@ -476,7 +476,7 @@ declare namespace angular { // Supplement IComponentOptions from angular.d.ts with router-specific // fields. interface IComponentOptions { - $canActivate?: () => boolean; + $canActivate?: (...args: any[]) => boolean | angular.IPromise; $routeConfig?: RouteDefinition[]; } } diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index e64496604f..111ba86cce 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -238,6 +238,7 @@ declare namespace angular { * @param directiveFactory An injectable directive factory function. */ directive(name: string, inlineAnnotatedFunction: any[]): IModule; + directive(name: string, injectionFunction: Function): IModule; directive(object: Object): IModule; /** * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider. @@ -1745,12 +1746,12 @@ declare namespace angular { */ $onInit?(): void; /** - * Called whenever one-way bindings are updated. The changesObj is a hash whose keys are the names of the bound - * properties that have changed, and the values are an {@link IChangesObject} object of the form + * Called whenever one-way bindings are updated. The onChangesObj is a hash whose keys are the names of the bound + * properties that have changed, and the values are an {@link IChangesObject} object of the form * { currentValue, previousValue, isFirstChange() }. Use this hook to trigger updates within a component such as * cloning the bound value to prevent accidental mutation of the outer value. */ - $onChanges?(changesObj: {[property:string]: IChangesObject}): void; + $onChanges?(onChangesObj: IOnChangesObject): void; /** * Called on a controller when its containing scope is destroyed. Use this hook for releasing external resources, * watches and event handlers. @@ -1766,6 +1767,10 @@ declare namespace angular { */ $postLink?(): void; } + + interface IOnChangesObject { + [property: string]: IChangesObject; + } interface IChangesObject { currentValue: any; @@ -1825,7 +1830,7 @@ declare namespace angular { bindToController?: boolean | Object; link?: IDirectiveLinkFn | IDirectivePrePost; multiElement?: boolean; - name?: string; + directiveName?: string; priority?: number; /** * @deprecated diff --git a/anydb-sql-migrations/anydb-sql-migrations.d.ts b/anydb-sql-migrations/anydb-sql-migrations.d.ts index 9ab421c3ac..98961266a9 100644 --- a/anydb-sql-migrations/anydb-sql-migrations.d.ts +++ b/anydb-sql-migrations/anydb-sql-migrations.d.ts @@ -3,7 +3,7 @@ // Definitions by: Gorgi Kosev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /// declare module "anydb-sql-migrations" { @@ -31,4 +31,4 @@ declare module "anydb-sql-migrations" { items: MigrationTask[]; }) => any) => Promise; }; -} \ No newline at end of file +} diff --git a/asana/asana.d.ts b/asana/asana.d.ts index 61cb54d26f..8b618b81a3 100644 --- a/asana/asana.d.ts +++ b/asana/asana.d.ts @@ -3,7 +3,7 @@ // Definitions by: Qubo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /// declare module "asana" { diff --git a/auth0-js/auth0-js-tests.ts b/auth0-js/auth0-js-tests.ts new file mode 100644 index 0000000000..c92251db91 --- /dev/null +++ b/auth0-js/auth0-js-tests.ts @@ -0,0 +1,23 @@ +/// + +var auth0 = new Auth0({ + domain: 'mine.auth0.com', + clientID: 'dsa7d77dsa7d7', + callbackURL: 'http://my-app.com/callback', + callbackOnLocationHash: true +}); + +auth0.login({ + connection: 'google-oauth2', + popup: true, + popupOptions: { + width: 450, + height: 800 + } +}, (err, profile, idToken, accessToken, state) => { + if (err) { + alert("something went wrong: " + err.message); + return; + } + alert('hello ' + profile.name); + }); diff --git a/auth0-js/auth0-js.d.ts b/auth0-js/auth0-js.d.ts new file mode 100644 index 0000000000..250c7a850e --- /dev/null +++ b/auth0-js/auth0-js.d.ts @@ -0,0 +1,133 @@ +// Type definitions for Auth0.js +// Project: https://github.com/auth0/auth0.js +// Definitions by: Robert McLaws +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** Extensions to the browser Window object. */ +interface Window { + /** Allows you to pass the id_token to other APIs, as specified in https://docs.auth0.com/apps-apis */ + token: string; +} + +/** This is the interface for the main Auth0 client. */ +interface Auth0Static { + + new(options: Auth0ClientOptions): Auth0Static; + changePassword(options: any, callback?: Function): void; + decodeJwt(jwt: string): any; + login(options: any, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + loginWithPopup(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + loginWithResourceOwner(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: any) => any): void; + loginWithUsernamePassword(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + logout(query: string): void; + getConnections(callback?: Function): void; + refreshToken(refreshToken: string, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; + getDelegationToken(targetClientId: string, id_token: string, options: any, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; + getProfile(id_token: string, callback?: Function): Auth0UserProfile; + getSSOData(withActiveDirectories: any, callback?: Function): void; + parseHash(hash: string): Auth0DecodedHash; + signup(options: Auth0SignupOptions, callback: Function): void; + validateUser(options: any, callback: (error?: Auth0Error, valid?: any) => any): void; +} + +/** Represents constructor options for the Auth0 client. */ +interface Auth0ClientOptions { + clientID: string; + callbackURL: string; + callbackOnLocationHash?: boolean; + domain: string; + forceJSONP?: boolean; +} + +/** Represents a normalized UserProfile. */ +interface Auth0UserProfile { + email: string; + email_verified: boolean; + family_name: string; + gender: string; + given_name: string; + locale: string; + name: string; + nickname: string; + picture: string; + user_id: string; + /** Represents one or more Identities that may be associated with the User. */ + identities: Auth0Identity[]; + user_metadata?: any; + app_metadata?: any; +} + +/** Represents an Auth0UserProfile that has a Microsoft Account as the primary identity. */ +interface MicrosoftUserProfile extends Auth0UserProfile { + emails: string[]; +} + +/** Represents an Auth0UserProfile that has an Office365 account as the primary identity. */ +interface Office365UserProfile extends Auth0UserProfile { + tenantid: string; + upn: string; +} + +/** Represents an Auth0UserProfile that has an Active Directory account as the primary identity. */ +interface AdfsUserProfile extends Auth0UserProfile { + issuer: string; +} + +/** Represents multiple identities assigned to a user. */ +interface Auth0Identity { + access_token: string; + connection: string; + isSocial: boolean; + provider: string; + user_id: string; +} + +interface Auth0DecodedHash { + access_token: string; + id_token: string; + profile: Auth0UserProfile; + state: any; +} + +interface Auth0PopupOptions { + width: number; + height: number; +} + +interface Auth0LoginOptions { + auto_login?: boolean; + connection?: string; + email?: string; + username?: string; + password?: string; + popup?: boolean; + popupOptions?: Auth0PopupOptions; +} + +interface Auth0SignupOptions extends Auth0LoginOptions { + auto_login: boolean; +} + +interface Auth0Error { + code: any; + details: any; + name: string; + message: string; + status: any; +} + +/** Represents the response from an API Token Delegation request. */ +interface Auth0DelegationToken { + /** The length of time in seconds the token is valid for. */ + expires_in: string; + /** The JWT for delegated access. */ + id_token: string; + /** The type of token being returned. Possible values: "Bearer" */ + token_type: string; +} + +declare var Auth0: Auth0Static; + +declare module "auth0-js" { + export = Auth0 +} diff --git a/auth0.lock/auth0.lock-tests.ts b/auth0.lock/auth0.lock-tests.ts index 07a7cf8323..d466cf5937 100644 --- a/auth0.lock/auth0.lock-tests.ts +++ b/auth0.lock/auth0.lock-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// const CLIENT_ID = "YOUR_AUTH0_APP_CLIENTID"; diff --git a/auth0.lock/auth0.lock.d.ts b/auth0.lock/auth0.lock.d.ts index 7a459afd97..43d842aecc 100644 --- a/auth0.lock/auth0.lock.d.ts +++ b/auth0.lock/auth0.lock.d.ts @@ -3,7 +3,7 @@ // Definitions by: Brian Caruso // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface Auth0LockAdditionalSignUpFieldOption { value: string; diff --git a/auth0.widget/auth0.widget-tests.ts b/auth0.widget/auth0.widget-tests.ts index 012e9b9769..f44601986e 100644 --- a/auth0.widget/auth0.widget-tests.ts +++ b/auth0.widget/auth0.widget-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// var widget: Auth0WidgetStatic = new Auth0Widget({ diff --git a/auth0.widget/auth0.widget.d.ts b/auth0.widget/auth0.widget.d.ts index 20694526c3..e36a7f868a 100644 --- a/auth0.widget/auth0.widget.d.ts +++ b/auth0.widget/auth0.widget.d.ts @@ -3,7 +3,7 @@ // Definitions by: Robert McLaws // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface Auth0WidgetStatic { diff --git a/auth0/auth0-tests.ts b/auth0/auth0-tests.ts index 9cd903b306..a1357246f3 100644 --- a/auth0/auth0-tests.ts +++ b/auth0/auth0-tests.ts @@ -1,23 +1,51 @@ -/// +/// -var auth0 = new Auth0({ - domain: 'mine.auth0.com', - clientID: 'dsa7d77dsa7d7', - callbackURL: 'http://my-app.com/callback', - callbackOnLocationHash: true +import * as auth0 from 'auth0'; + +const management = new auth0.ManagementClient({ + token: '{YOUR_API_V2_TOKEN}', + domain: '{YOUR_ACCOUNT}.auth0.com' }); -auth0.login({ - connection: 'google-oauth2', - popup: true, - popupOptions: { - width: 450, - height: 800 - } -}, (err, profile, idToken, accessToken, state) => { - if (err) { - alert("something went wrong: " + err.message); - return; - } - alert('hello ' + profile.name); - }); +const auth = new auth0.AuthenticationClient({ + domain: '{YOUR_ACCOUNT}.auth0.com', + clientId: '{OPTIONAL_CLIENT_ID}' +}); + +// Using a callback. +management.getUsers((err: Error, users: auth0.User[]) => { + if (err) { + // Handle error. + } + console.log(users); +}); + +// Using a Promise. +management + .getUsers() + .then((users) => { + console.log(users); + }) + .catch((err) => { + // Handle the error. + }); + +management + .createUser({ + connection: 'My-Connection', + email: 'hi@me.co', + }).then((user) => { + console.log(user); + }).catch((err) => { + // Handle the error. + }); + +auth + .requestChangePasswordEmail({ + connection: 'My-Connection', + email: 'hi@me.co', + }).then((response) => { + console.log(response); + }).catch((err) => { + // Handle the error. + }); diff --git a/auth0/auth0.d.ts b/auth0/auth0.d.ts index 0608674ae7..e367d30411 100644 --- a/auth0/auth0.d.ts +++ b/auth0/auth0.d.ts @@ -1,131 +1,95 @@ -// Type definitions for Auth0.js -// Project: http://auth0.com -// Definitions by: Robert McLaws +// Type definitions for auth0 v2.3.1 +// Project: https://github.com/auth0/node-auth0 +// Definitions by: Seth Westphal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/** Extensions to the browser Window object. */ -interface Window { - /** Allows you to pass the id_token to other APIs, as specified in https://docs.auth0.com/apps-apis */ +/// + +declare module "auth0" { + + import * as Promise from 'bluebird'; + + export interface ManagementClientOptions { token: string; -} + domain?: string; + } -/** This is the interface for the main Auth0 client. */ -interface Auth0Static { - - new(options: Auth0ClientOptions): Auth0Static; - changePassword(options: any, callback?: Function): void; - decodeJwt(jwt: string): any; - login(options: any, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; - loginWithPopup(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; - loginWithResourceOwner(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: any) => any): void; - loginWithUsernamePassword(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; - logout(query: string): void; - getConnections(callback?: Function): void; - getDelegationToken(targetClientId: string, id_token: string, options: any, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; - getProfile(id_token: string, callback?: Function): Auth0UserProfile; - getSSOData(withActiveDirectories: any, callback?: Function): void; - parseHash(hash: string): Auth0DecodedHash; - signup(options: Auth0SignupOptions, callback: Function): void; - validateUser(options: any, callback: (error?: Auth0Error, valid?: any) => any): void; -} - -/** Represents constructor options for the Auth0 client. */ -interface Auth0ClientOptions { - clientID: string; - callbackURL: string; - callbackOnLocationHash?: boolean; - domain: string; - forceJSONP?: boolean; -} - -/** Represents a normalized UserProfile. */ -interface Auth0UserProfile { - email: string; - family_name: string; - gender: string; - given_name: string; - locale: string; - name: string; - nickname: string; - picture: string; - user_id: string; - /** Represents one or more Identities that may be associated with the User. */ - identities: Auth0Identity[]; - user_metadata?: any; - app_metadata?: any; -} - -/** Represents an Auth0UserProfile that has a Microsoft Account as the primary identity. */ -interface MicrosoftUserProfile extends Auth0UserProfile { - emails: string[]; -} - -/** Represents an Auth0UserProfile that has an Office365 account as the primary identity. */ -interface Office365UserProfile extends Auth0UserProfile { - tenantid: string; - upn: string; -} - -/** Represents an Auth0UserProfile that has an Active Directory account as the primary identity. */ -interface AdfsUserProfile extends Auth0UserProfile { - issuer: string; -} - -/** Represents multiple identities assigned to a user. */ -interface Auth0Identity { - access_token: string; + export interface UserData { connection: string; - isSocial: boolean; - provider: string; - user_id: string; -} - -interface Auth0DecodedHash { - access_token: string; - id_token: string; - profile: Auth0UserProfile; - state: any; -} - -interface Auth0PopupOptions { - width: number; - height: number; -} - -interface Auth0LoginOptions { - auto_login?: boolean; - connection?: string; email?: string; username?: string; password?: string; - popup?: boolean; - popupOptions?: Auth0PopupOptions; -} + phone_number?: string; + user_metadata?: {}; + email_verified?: boolean; + app_metadata?: {}; + } -interface Auth0SignupOptions extends Auth0LoginOptions { - auto_login: boolean; -} + export interface GetUsersData { + per_page?: number; + page?: number; + include_totals?: boolean; + sort?: string; + connection?: string; + fields?: string; + include_fields?: boolean; + q?: string; + search_engine?: string; + } -interface Auth0Error { - code: any; - details: any; - name: string; - message: string; - status: any; -} + export interface User { + email?: string; + email_verified?: boolean; + username?: string; + phone_number?: string; + phone_verified?: boolean; + user_id?: string; + created_at?: string; + updated_at?: string; + identities?: Identity[]; + app_metadata?: {}; + user_metadata?: {}; + picture?: string; + name?: string; + nickname?: string; + multifactor?: string[]; + last_ip?: string; + last_login?: string; + logins_count?: number; + blocked?: boolean; + } -/** Represents the response from an API Token Delegation request. */ -interface Auth0DelegationToken { - /** The length of time in seconds the token is valid for. */ - expires_in: string; - /** The JWT for delegated access. */ - id_token: string; - /** The type of token being returned. Possible values: "Bearer" */ - token_type: string; -} + export interface Identity { + connection: string; + user_id: string; + provider: string; + isSocial: boolean; + } -declare var Auth0: Auth0Static; + export class ManagementClient { + constructor(options: ManagementClientOptions); + + getUsers(params?: GetUsersData): Promise; + getUsers(params?: GetUsersData, cb?: (err: Error, users: User[]) => void): void; + createUser(data: UserData): Promise; + createUser(data: UserData, cb: (err: Error, data: User) => void): void; + } + + export interface AuthenticationClientOptions { + clientId?: string; + domain: string; + } + + export interface RequestChangePasswordEmailData { + connection: string; + email: string; + } + + export class AuthenticationClient { + constructor(options: AuthenticationClientOptions); + + requestChangePasswordEmail(data: RequestChangePasswordEmailData): Promise; + requestChangePasswordEmail(data: RequestChangePasswordEmailData, cb: (err: Error, message: string) => void): void; + } -declare module "auth0" { - export = Auth0 } diff --git a/aws-lambda/aws-lambda-tests.ts b/aws-lambda/aws-lambda-tests.ts index fd289dcb7f..8b9f53a8ab 100644 --- a/aws-lambda/aws-lambda-tests.ts +++ b/aws-lambda/aws-lambda-tests.ts @@ -9,6 +9,8 @@ var kinesis: lambda.Kinesis; var recordsList: lambda.Record[]; var anyObj: any; var num: number; +var identity: lambda.Identity; +var error: Error; /* Records */ var records: lambda.Records; @@ -46,4 +48,19 @@ context.succeed(str); context.succeed(anyObj); context.succeed(str, anyObj); str = context.awsRequestId; -num = context.getRemainingTimeInMillis(); \ No newline at end of file +num = context.getRemainingTimeInMillis(); +identity = context.identity; + +/* Identity */ +var identity: lambda.Identity; + +str = identity.cognitoIdentityId; +str = identity.cognitoIdentityPoolId; + +/* Callback */ +function callback(cb: lambda.Callback) { + cb(); + cb(null); + cb(error); + cb(null, anyObj); +} \ No newline at end of file diff --git a/aws-lambda/aws-lambda.d.ts b/aws-lambda/aws-lambda.d.ts index cdd8e2f506..081c6e0e3e 100644 --- a/aws-lambda/aws-lambda.d.ts +++ b/aws-lambda/aws-lambda.d.ts @@ -36,8 +36,20 @@ declare module "aws-lambda" { succeed(message: string, object: any): void; awsRequestId: string; getRemainingTimeInMillis(): number; + /** Information about the Amazon Cognito identity provider when invoked through the AWS Mobile SDK. It can be null. */ + identity?: Identity; } + interface Identity { + cognitoIdentityId: string; + cognitoIdentityPoolId: string; + } - export type Callback = (error?: Error, message?: string) => void; + /** + * Optional callback parameter. + * + * @param error – an optional parameter that you can use to provide results of the failed Lambda function execution. + * @param result – an optional parameter that you can use to provide the result of a successful function execution. The result provided must be JSON.stringify compatible. + */ + export type Callback = (error?: Error, result?: any) => void; } \ No newline at end of file diff --git a/base64url/base64url.d.ts b/base64url/base64url.d.ts new file mode 100644 index 0000000000..42dbe4cca5 --- /dev/null +++ b/base64url/base64url.d.ts @@ -0,0 +1,74 @@ +// Type definitions for base64url v2.0.0 +// Project: https://github.com/brianloveswords/base64url +// Definitions by: Stepan Miroshin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/** + * For encoding and decoding base64url! + * v2.0.0 + */ + +/** + * Encoding type + */ +declare type Encoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "utf16le" | "base64" | "binary" | "hex" + +interface IBase64Url { + /** + * Encode input to base64url + * @param {string} input Incoming input + * @param {Encoding} encoding Default 'utf8' + * @return {string} + */ + (input: string, encoding?: Encoding): string; + /** + * Encode input to base64url + * @param {Buffer} input Incoming value + */ + (inout: Buffer): string; + /** + * Encode input to base64url + * + * @param {string} input Incoming input + * @param {Encoding} encoding Default 'utf8' + * @returns {string} + */ + encode(input: string, encoding?: Encoding): string; + /** + * Encode input to base64url + * @param {Buffer} input Incoming value + */ + encode(input: Buffer): string; + /** + * Convert a base64url encoded string into a raw string. + * @param {string} base64url base64url encoded string + * @param {Encoding} encoding Encoding defaults to 'utf8' + * @returns {string} + */ + decode(base64url: string, encoding?: string): string; + /** + * Convert a base64url encoded string to a base64 encoded string + * @param {string | Buffer} base64url base64url encoded value + * @returns {string} + */ + toBase64(base64url: string | Buffer): string; + /** + * Convert a base64 encoded string to a base64url encoded string + * @param {string} base64 encoded string + * @returns {string} + */ + fromBase64(base64: string): string; + /** + * Convert a base64url encoded string to a Buffer + * @param {string} base64url encoded string + * @returns {Buffer} + */ + toBuffer(base64url: string): Buffer; +} + +declare module "base64url" { + const base64url: IBase64Url; + export = base64url; +} diff --git a/base64url/base64url.test.ts b/base64url/base64url.test.ts new file mode 100644 index 0000000000..01b3934bc9 --- /dev/null +++ b/base64url/base64url.test.ts @@ -0,0 +1,26 @@ +/// + +import * as base64url from "base64url"; + +// default +let str = base64url("some value"); +str = base64url("some value", "hex"); +str = base64url(new Buffer("some value")); + +// encode +str = base64url.encode("some value"); +str = base64url.encode("some value", "hex"); +str = base64url.encode(new Buffer("some value")); + +// decode +str = base64url.decode("ADA="); +str = base64url.decode("ADA=", "binary"); + +// toBase64 +str = base64url.toBase64("ADA="); +str = base64url.toBase64(new Buffer("ADA=", "base64")); + +// fromBase64 +str = base64url.fromBase64("ADA="); + +let buf = base64url.toBase64("ADA="); \ No newline at end of file diff --git a/big.js/big.js-tests.ts b/big.js/big.js-tests.ts index 0067a0b4f5..5a12cab011 100644 --- a/big.js/big.js-tests.ts +++ b/big.js/big.js-tests.ts @@ -12,6 +12,7 @@ */ +import BigJS = BigJsLibrary.BigJS; function constructorTests() { var x = new Big(9) // '9' var y = new Big(x) // '9' @@ -247,4 +248,19 @@ function testMultipleConstructors() { x.div(3) // 1.667 y.div(3) // 1.6666666667 -} \ No newline at end of file +} + +function multipleTypesAccepted(n: number | BigJS | string) { + var y = Big(n) + .minus(n) + .mod(n) + .plus(n) + .times(n); + y.cmp(n); + y.eq(n); + y.gt(n); + y.gte(n); + y.lt(n); + y.lte(n); + y.div(n) +} diff --git a/big.js/big.js.d.ts b/big.js/big.js.d.ts index 52a653ba83..e08ee7bc57 100644 --- a/big.js/big.js.d.ts +++ b/big.js/big.js.d.ts @@ -25,23 +25,11 @@ declare namespace BigJsLibrary { RM: RoundingMode; } + type BigNumberInputType = number | string | BigJS; + interface BigJS_Constructors { - /** A decimal value. */ - new (value: number): BigJS; - /** A decimal value. - String values may be in exponential, as well as normal (non-exponential) notation. There is no limit to the number of digits of a string value (other than that of Javascript's maximum array size), but the largest recommended exponent magnitude is 1e+6. Infinity, NaN and hexadecimal literal strings, e.g. '0xff', are not valid. - String values in octal literal form will be interpreted as decimals, e.g. '011' is 11, not 9. */ - new (value: string): BigJS; - /** A decimal value. */ - new (value: BigJS): BigJS; - /** A decimal value. */ - (value: number): BigJS; - /** A decimal value. - String values may be in exponential, as well as normal (non-exponential) notation. There is no limit to the number of digits of a string value (other than that of Javascript's maximum array size), but the largest recommended exponent magnitude is 1e+6. Infinity, NaN and hexadecimal literal strings, e.g. '0xff', are not valid. - String values in octal literal form will be interpreted as decimals, e.g. '011' is 11, not 9. */ - (value: string): BigJS; - /** A decimal value. */ - (value: BigJS): BigJS; + new (value: BigNumberInputType): BigJS; + (value: BigNumberInputType): BigJS; /** A decimal value. */ (): BigJS; @@ -57,85 +45,35 @@ declare namespace BigJsLibrary { 1 = If the value of this Big number is greater than the value of n -1 = If the value of this Big number is less than the value of n 0 = If this Big number and n have the same value */ - cmp(n: number): number; - /** Compare - @returns {Number} - 1 = If the value of this Big number is greater than the value of n - -1 = If the value of this Big number is less than the value of n - 0 = If this Big number and n have the same value */ - cmp(n: string): number; - /** Compare - @returns {Number} - 1 = If the value of this Big number is greater than the value of n - -1 = If the value of this Big number is less than the value of n - 0 = If this Big number and n have the same value */ - cmp(n: BigJS): number; + cmp(n: BigNumberInputType): number; /** Returns a Big number whose value is the value of this Big number divided by n. */ - div(n: number): BigJS; - /** Returns a Big number whose value is the value of this Big number divided by n. */ - div(n: string): BigJS; - /** Returns a Big number whose value is the value of this Big number divided by n. */ - div(n: BigJS): BigJS; + div(n: BigNumberInputType): BigJS; /** Returns true if the value of this Big equals the value of n, otherwise returns false. */ - eq(n: number): boolean; - /** Returns true if the value of this Big equals the value of n, otherwise returns false. */ - eq(n: string): boolean; - /** Returns true if the value of this Big equals the value of n, otherwise returns false. */ - eq(n: BigJS): boolean; + eq(n: BigNumberInputType): boolean; /** Returns true if the value of this Big is greater than the value of n, otherwise returns false. */ - gt(n: number): boolean; - /** Returns true if the value of this Big is greater than the value of n, otherwise returns false. */ - gt(n: string): boolean; - /** Returns true if the value of this Big is greater than the value of n, otherwise returns false. */ - gt(n: BigJS): boolean; + gt(n: BigNumberInputType): boolean; /** Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false. */ - gte(n: number): boolean; - /** Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false. */ - gte(n: string): boolean; - /** Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false. */ - gte(n: BigJS): boolean; + gte(n: BigNumberInputType): boolean; /** Returns true if the value of this Big is less than the value of n, otherwise returns false. */ - lt(n: number): boolean; - /** Returns true if the value of this Big is less than the value of n, otherwise returns false. */ - lt(n: string): boolean; - /** Returns true if the value of this Big is less than the value of n, otherwise returns false. */ - lt(n: BigJS): boolean; + lt(n: BigNumberInputType): boolean; /** Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false. */ - lte(n: number): boolean; - /** Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false. */ - lte(n: string): boolean; - /** Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false. */ - lte(n: BigJS): boolean; + lte(n: BigNumberInputType): boolean; /** Returns a Big number whose value is the value of this Big number minus n. */ - minus(n: number): BigJS; - /** Returns a Big number whose value is the value of this Big number minus n. */ - minus(n: string): BigJS; - /** Returns a Big number whose value is the value of this Big number minus n. */ - minus(n: BigJS): BigJS; + minus(n: BigNumberInputType): BigJS; /** Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n. - The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */ - mod(n: number): BigJS; - /** Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n. - The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */ - mod(n: string): BigJS; - /** Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n. - The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */ - mod(n: BigJS): BigJS; + The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */ + mod(n: BigNumberInputType): BigJS; /** Returns a Big number whose value is the value of this Big number plus n. */ - plus(n: number): BigJS; - /** Returns a Big number whose value is the value of this Big number plus n. */ - plus(n: string): BigJS; - /** Returns a Big number whose value is the value of this Big number plus n. */ - plus(n: BigJS): BigJS; + plus(n: BigNumberInputType): BigJS; /** Returns a Big number whose value is the value of this Big number raised to the power exp. If exp is negative and the result has more fraction digits than is specified by Big.DP, it will be rounded to Big.DP decimal places using rounding mode Big.RM. @@ -156,11 +94,7 @@ declare namespace BigJsLibrary { sqrt(): BigJS; /** Returns a Big number whose value is the value of this Big number times n. */ - times(n: number): BigJS; - /** Returns a Big number whose value is the value of this Big number times n. */ - times(n: string): BigJS; - /** Returns a Big number whose value is the value of this Big number times n. */ - times(n: BigJS): BigJS; + times(n: BigNumberInputType): BigJS; /** Returns a string representing the value of this Big number in exponential notation to a fixed number of decimal places dp. */ toExponential(): string; diff --git a/blessed/blessed-tests.ts b/blessed/blessed-tests.ts new file mode 100644 index 0000000000..4e7f7002e6 --- /dev/null +++ b/blessed/blessed-tests.ts @@ -0,0 +1,773 @@ +/// + +import * as blessed from 'blessed'; + +let screen: blessed.Widgets.Screen = null; + +// https://github.com/chjj/blessed/blob/master/test/widget-autopad.js + +screen = blessed.screen({ + dump: __dirname + '/logs/autopad.log', + smartCSR: true, + autoPadding: true, + warnings: true +}); + +var box1 = blessed.box({ + parent: screen, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line' +}); + +var box2 = blessed.box({ + parent: box1, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line' +}); + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-bigtext.js + +screen = blessed.screen({ + dump: __dirname + '/logs/bigtext.log', + smartCSR: true, + warnings: true +}); + +var box = blessed.bigtext({ + parent: screen, + content: 'Hello', + shrink: true, + width: '80%', + // height: '80%', + height: 'shrink', + // width: 'shrink', + border: 'line', + fch: ' ', + ch: '\u2592', + style: { + fg: 'red', + bg: 'blue', + bold: false + } +}); + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-csr.js + +screen = blessed.screen({ + dump: __dirname + '/logs/csr.log', + smartCSR: true, + warnings: true +}); + +var lorem = require('fs').readFileSync(__dirname + '/git.diff', 'utf8'); + +var cleanSides = screen.cleanSides; +function expectClean(value: any) { + screen.cleanSides = function(el: blessed.widget.Element) { + var ret = cleanSides.apply(this, arguments); + if (ret !== value) { + throw new Error('Failed. Expected ' + + value + ' from cleanSides. Got ' + + ret + '.'); + } + return ret; + }; +} +var btext = blessed.box({ + parent: screen, + left: 'center', + top: 'center', + width: '80%', + height: '80%', + style: { + bg: 'green' + }, + border: 'line', + content: 'CSR should still work.' +}); +let _oscroll = btext.scroll; +btext.scroll = function(offset, always) { + expectClean(true); + return _oscroll(offset, always); +}; + +var text = blessed.scrollabletext({ + parent: screen, + content: lorem, + border: 'line', + left: 'center', + top: 'center', + draggable: true, + width: '50%', + height: '50%', + mouse: true, + keys: true, + vi: true +}); + +_oscroll = text.scroll; +text.scroll = function(offset, always) { + var el = this; + var value = true; + if (el.left < 0) value = true; + if (el.top < 0) value = false; + if (el.left + el.width > screen.width) value = true; + if (el.top + el.height > screen.height) value = false; + expectClean(value); + return _oscroll(offset, always); +}; + +text.focus(); + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-dock-noborder.js + +screen = blessed.screen({ + dump: __dirname + '/logs/dock.log', + smartCSR: true, + dockBorders: true, + warnings: true +}); + +blessed.box({ + parent: screen, + left: -1, + top: -1, + width: '50%+1', + height: '50%+1', + border: 'line', + content: 'Foo' +}); + +blessed.box({ + parent: screen, + left: '50%-1', + top: -1, + width: '50%+3', + height: '50%+1', + content: 'Bar', + border: 'line' +}); + +blessed.box({ + parent: screen, + left: -1, + top: '50%-1', + width: '50%+1', + height: '50%+3', + border: 'line', + content: 'Foo' +}); + +blessed.listtable({ + parent: screen, + left: '50%-1', + top: '50%-1', + width: '50%+3', + height: '50%+3', + border: 'line', + align: 'center', + tags: true, + keys: true, + vi: true, + mouse: true, + style: { + header: { + fg: 'blue', + bold: true + }, + cell: { + fg: 'magenta', + selected: { + bg: 'blue' + } + } + }, + data: [ + [ 'Animals', 'Foods', 'Times', 'Numbers' ], + [ 'Elephant', 'Apple', '1:00am', 'One' ], + [ 'Bird', 'Orange', '2:15pm', 'Two' ], + [ 'T-Rex', 'Taco', '8:45am', 'Three' ], + [ 'Mouse', 'Cheese', '9:05am', 'Four' ] + ] +}).focus(); + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://raw.githubusercontent.com/chjj/blessed/master/example/simple-form.js + +var form = blessed.form({ + parent: screen, + keys: true, + left: 0, + top: 0, + width: 30, + height: 4, + bg: 'green', + content: 'Submit or cancel?' +}); + +var submit = blessed.button({ + parent: form, + mouse: true, + keys: true, + padding: { + left: 1, + right: 1 + }, + left: 10, + top: 2, + shrink: true, + name: 'submit', + content: 'submit', + style: { + bg: 'blue', + focus: { + bg: 'red' + }, + hover: { + bg: 'red' + } + } +}); + +var cancel = blessed.button({ + parent: form, + mouse: true, + keys: true, + padding: { + left: 1, + right: 1 + }, + left: 20, + top: 2, + shrink: true, + name: 'cancel', + content: 'cancel', + style: { + bg: 'blue', + focus: { + bg: 'red' + }, + hover: { + bg: 'red' + } + } +}); + +// https://github.com/chjj/blessed/blob/master/test/widget-layout.js + +screen = blessed.screen({ + dump: __dirname + '/logs/layout.log', + smartCSR: true, + autoPadding: true, + warnings: true +}); + +var layout = blessed.layout({ + parent: screen, + top: 'center', + left: 'center', + width: '50%', + height: '50%', + border: 'line', + layout: process.argv[2] === 'grid' ? 'grid' : 'inline', + style: { + bg: 'red', + border: { + fg: 'blue' + } + } +}); + +var box1 = blessed.box({ + parent: layout, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line', + content: '1' +}); + +var box2 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '2' +}); + +var box3 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '3' +}); + +var box4 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '4' +}); + +var box5 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '5' +}); + +var box6 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '6' +}); + +var box7 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '7' +}); + +var box8 = blessed.box({ + parent: layout, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line', + content: '8' +}); + +var box9 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '9' +}); + +var box10 = blessed.box({ + parent: layout, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line', + content: '10' +}); + +var box11 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '11' +}); + +var box12 = blessed.box({ + parent: layout, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line', + content: '12' +}); + +if (process.argv[2] !== 'grid') { + for (var i = 0; i < 10; i++) { + blessed.box({ + parent: layout, + // width: i % 2 === 0 ? 10 : 20, + // height: i % 2 === 0 ? 5 : 10, + width: Math.random() > 0.5 ? 10 : 20, + height: Math.random() > 0.5 ? 5 : 10, + border: 'line', + content: (i + 1 + 12) + '' + }); + } +} + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-form.js + +screen = blessed.screen({ + dump: __dirname + '/logs/form.log', + warnings: true +}); + +type FormData = { + radio1: boolean; + radio2: boolean; + text: string; + check: boolean; +}; + +var form2 = blessed.form({ + parent: screen, + mouse: true, + keys: true, + vi: true, + left: 0, + top: 0, + width: '100%', + //height: 12, + style: { + bg: 'green', + border: { + inverse: true + }, + scrollbar: { + inverse: true + } + }, + content: 'foobar', + scrollable: true, + scrollbar: { + ch: ' ' + } + //alwaysScroll: true +}); + +form2.on('submit', (data) => { + output.setContent(JSON.stringify(data, null, 2)); + screen.render(); +}); + +form2.key('d', function() { + form2.scroll(1, true); + screen.render(); +}); + +form2.key('u', function() { + form2.scroll(-1, true); + screen.render(); +}); + +var set = blessed.radioset({ + parent: form2, + left: 1, + top: 1, + shrink: true, + //padding: 1, + //content: 'f', + style: { + bg: 'magenta' + } +}); + +var radio1 = blessed.radiobutton({ + parent: set, + mouse: true, + keys: true, + shrink: true, + style: { + bg: 'magenta' + }, + height: 1, + left: 0, + top: 0, + name: 'radio1', + content: 'radio1' +}); + +var radio2 = blessed.radiobutton({ + parent: set, + mouse: true, + keys: true, + shrink: true, + style: { + bg: 'magenta' + }, + height: 1, + left: 15, + top: 0, + name: 'radio2', + content: 'radio2' +}); + +var text2 = blessed.textbox({ + parent: form2, + mouse: true, + keys: true, + style: { + bg: 'blue' + }, + height: 1, + width: 20, + left: 1, + top: 3, + name: 'text' +}); + +text2.on('focus', function() { + text2.readInput(); +}); + +var check = blessed.checkbox({ + parent: form2, + mouse: true, + keys: true, + shrink: true, + style: { + bg: 'magenta' + }, + height: 1, + left: 28, + top: 1, + name: 'check', + content: 'check' +}); + +var check2 = blessed.checkbox({ + parent: form2, + mouse: true, + keys: true, + shrink: true, + style: { + bg: 'magenta' + }, + height: 1, + left: 28, + top: 14, + name: 'foooooooo2', + content: 'foooooooo2' +}); + +var submit = blessed.button({ + parent: form2, + mouse: true, + keys: true, + shrink: true, + padding: { + left: 1, + right: 1 + }, + left: 29, + top: 3, + name: 'submit', + content: 'submit', + style: { + bg: 'blue', + focus: { + bg: 'red' + } + } +}); + +submit.on('press', function() { + form2.submit(); +}); + +var box1 = blessed.box({ + parent: form2, + left: 1, + top: 10, + height: 10, + width: 10, + content: 'one', + style: { + bg: 'cyan' + } +}); + +var box2 = blessed.box({ + parent: box1, + left: 1, + top: 2, + height: 8, + width: 9, + content: 'two', + style: { + bg: 'magenta' + } +}); + +var box3 = blessed.box({ + parent: box2, + left: 1, + top: 2, + height: 6, + width: 8, + content: 'three', + style: { + bg: 'yellow' + } +}); + +var box4 = blessed.box({ + parent: box3, + left: 1, + top: 2, + height: 4, + width: 7, + content: 'four', + style: { + bg: 'blue' + } +}); + +var output = blessed.scrollabletext({ + parent: form2, + mouse: true, + keys: true, + left: 0, + top: 20, + height: 5, + right: 0, + style: { + bg: 'red' + }, + content: 'foobar' +}); + +var bottom = blessed.line({ + parent: form2, + type: 'line', + orientation: 'horizontal', + left: 0, + right: 0, + top: 50, + style: { + fg: 'blue' + } +}); + +screen.key('q', function() { + return screen.destroy(); +}); + +form2.focus(); + +form2.submit(); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-table.js + +screen = blessed.screen({ + dump: __dirname + '/logs/table.log', + autoPadding: false, + fullUnicode: true, + warnings: true +}); + +var DU = '杜'; +var JUAN = '鹃'; + +var table = blessed.table({ + //parent: screen, + top: 'center', + left: 'center', + data: null, + border: 'line', + align: 'center', + tags: true, + //width: '80%', + width: 'shrink', + style: { + border: { + fg: 'red' + }, + header: { + fg: 'blue', + bold: true + }, + cell: { + fg: 'magenta' + } + } +}); + +var data1 = [ + [ 'Animals', 'Foods', 'Times' ], + [ 'Elephant', 'Apple', '1:00am' ], + [ 'Bird', 'Orange', '2:15pm' ], + [ 'T-Rex', 'Taco', '8:45am' ], + [ 'Mouse', 'Cheese', '9:05am' ] +]; + +data1[1][0] = '{red-fg}' + data1[1][0] + '{/red-fg}'; +data1[2][0] += ' (' + DU + JUAN + ')'; + +var data2 = [ + [ 'Animals', 'Foods', 'Times', 'Numbers' ], + [ 'Elephant', 'Apple', '1:00am', 'One' ], + [ 'Bird', 'Orange', '2:15pm', 'Two' ], + [ 'T-Rex', 'Taco', '8:45am', 'Three' ], + [ 'Mouse', 'Cheese', '9:05am', 'Four' ] +]; + +data2[1][0] = '{red-fg}' + data2[1][0] + '{/red-fg}'; +data2[2][0] += ' (' + DU + JUAN + ')'; + +screen.key('q', function() { + return screen.destroy(); +}); + +table.setData(data2); +screen.append(table); +screen.render(); + +setTimeout(function() { + table.setData(data1); + screen.render(); +}, 3000); diff --git a/blessed/blessed.d.ts b/blessed/blessed.d.ts index 6746afe5f5..cb9bd393ed 100644 --- a/blessed/blessed.d.ts +++ b/blessed/blessed.d.ts @@ -1,1256 +1,155 @@ -// Type definitions for blessed 0.1.5 +// Type definitions for blessed 0.1.81 // Project: https://github.com/chjj/blessed -// Definitions by: bryn austin bellomy +// Definitions by: bryn austin bellomy , Diullei Gomes // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// -declare module "blessed" -{ - import events = require('events'); - import buffer = require('buffer'); - import child_process = require('child_process'); +declare module "blessed" { + import {EventEmitter} from 'events'; + import * as stream from "stream" + import * as child_process from "child_process"; - module Blessed - { - export var colors: Colors; + export class BlessedProgram { + hideCursor: () => void; + move: any; + showCursor: any; + } - export interface GenericCallback { - (...args:any[]): void; + export module Widgets { + + export module Types { + + export type TTopLeft = string | number | "center"; + + export type TPosition = string | number; + + export type TMouseAction = "mousedown" | "mouseup" | "mousemove"; + + export type TStyle = { + type?: string; + bg?: string; + fg?: string; + ch?: string; + bold?: boolean; + underline?: boolean; + blink?: boolean; + inverse?: boolean; + invisible?: boolean; + transparent?: boolean; + border?: "line" | "bg" | TBorder; + hover?: boolean; + focus?: boolean; + label?: string; + track?: {bg?: string; fg?: string;}; + scrollbar?: {bg?: string; fg?: string;}; + } + + export type TBorder = { + /** + * Type of border (line or bg). bg by default. + */ + type?: "line" | "bg"; + /** + * Character to use if bg type, default is space. + */ + ch?: string; + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg?: number; + fg?: number; + /** + * Border attributes. + */ + bold?: string; + underline?: string; + } + + export type TCursor = { + /** + * Have blessed draw a custom cursor and hide the terminal cursor (experimental). + */ + artificial: boolean; + /** + * Shape of the cursor. Can be: block, underline, or line. + */ + shape: boolean; + /** + * Whether the cursor blinks. + */ + blink: boolean; + /** + * Color of the color. Accepts any valid color value (null is default). + */ + color: string; + } + + export type TAlign = "left" | "center" | "right"; + + export type ListbarCommand = { + key: string; + callback: () => void; + }; + + export type TImage = { + /** + * Pixel width. + */ + width: number; + /** + * Pixel height. + */ + height: number; + /** + * Image bitmap. + * */ + bmp: any; + /** + * Image cellmap (bitmap scaled down to cell size). + */ + cellmap: any; + }; + + export type Cursor = { + /** + * Have blessed draw a custom cursor and hide the terminal cursor (experimental). + */ + artificial: boolean; + /** + * Shape of the cursor. Can be: block, underline, or line. + */ + shape: boolean; + /** + * Whether the cursor blinks. + */ + blink: boolean; + /** + * Color of the color. Accepts any valid color value (null is default). + */ + color: string; + } } - export interface ColorPair { - /** background, must be number (-1 for default). */ - bg?: number; - /** foreground, must be number (-1 for default). */ - fg?: number; - } - - export interface Style extends ColorPair { - bold?: boolean; - underline?: boolean; - border: Border; - hover: ColorPair; - } - - export interface Border extends ColorPair { - /** type of border ('line' or 'bg'). */ - type?: string; //'line'|'bg'; - /** character to use if bg type, default is space. */ - ch?: string; - } - - export interface Padding { - top?:number; - right?:number; - bottom?:number; - left?:number; - } - - export interface Position { - /** offsets of the element relative to its parent. can be a number, percentage (0-100%), or keyword (center). right and bottom do not accept keywords. */ - top?:number|string; - /** offsets of the element relative to its parent. can be a number, percentage (0-100%), or keyword (center). right and bottom do not accept keywords. */ - right?:number|string; - /** offsets of the element relative to its parent. can be a number, percentage (0-100%), or keyword (center). right and bottom do not accept keywords. */ - bottom?:number|string; - /** offsets of the element relative to its parent. can be a number, percentage (0-100%), or keyword (center). right and bottom do not accept keywords. */ - left?:number|string; - /** width of the element, can be a number, percentage (0-100%), or keyword (half or shrink). */ - width?:number|string; - /** height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). */ - height?:number|string; - } - - export interface KeyCode { - name: string; - ctrl: boolean; - meta: boolean; - shift: boolean; - sequence: string; - full: string; - } - - export class Program - { - /** - Wrap the given text in terminal formatting codes corresponding to the given attribute - name. The `attr` string can be of the form `red fg` or `52 bg` where `52` is a 0-255 - integer color number. - */ - text (text:string, attr:string): string; - } - - export interface Colors { - /** Either pass a hex string, an array of 3 numbers, or three separate numbers representing an RGB value. This returns the 0-255 color number for that color. */ - match (r:string|number[]|number, g?:number, b?:number): number; - - /** An array of the 255 colors as hex strings. */ - colors: string[]; - } - - export interface NodeOptions - { - screen?: Screen; - parent?: Node; - children?: Node[]; - } - - export class Node extends events.EventEmitter - { - constructor(options?:NodeOptions); - - type : string; - options : NodeOptions; - parent : Node; - screen : Screen; - children : Node[]; - data : any; - _ : any; - $ : any; - index : number; - - // on(event:string, callback:() => void); - // on(event:'adopt', callback:() => void); - // on(event:'remove', callback:() => void); - // on(event:'reparent', callback:() => void); - // on(event:'attach', callback:() => void); - // on(event:'detach', callback:() => void); - - prepend(node:Node): void; - append(node:Node): void; - remove(node:Node): void; - insert(node:Node, index:number): void; - insertBefore(node:Node, refNode:Node): void; - insertAfter(node:Node, refNode:Node): void; - detach(): void; - // emitDescendants(): void; - // get(key:string): any; - // get(key:string, default:any): any; - // set(key:string, value:any): void; - } - - export interface ScreenOptions extends NodeOptions - { - /** the blessed Program to be associated with. will be automatically instantiated if none is provided. */ - program?: any; - /** attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with uniform cells to their sides). this is known to cause flickering with elements that are not full-width, however, it is more optimal for terminal rendering. */ - smartCSR?: boolean; - /** do CSR on any element within 20 cols of the screen edge on either side. faster than smartCSR, but may cause flickering depending on what is on each side of the element. */ - fastCSR?: boolean; - /** attempt to perform back_color_erase optimizations for terminals that support it. it will also work with terminals that don't support it, but only on lines with the default background color. as it stands with the current implementation, it's uncertain how much terminal performance this adds at the cost of overhead within node. */ - useBCE?: boolean; - /** amount of time (in ms) to redraw the screen after the terminal is resized (default: 300). */ - resizeTimeout?: number; - /** the width of tabs within an element's content. */ - tabSize?: number; - /** automatically position child elements with border and padding in mind. */ - autoPadding?: boolean; - /** the name of the logfile to use. if specified but the file does not exist, it will be created. see log method. */ - log?: string; - /** dump all output and input to desired file. can be used together with log option if set as a boolean. */ - dump?: any; - /** debug mode. enables usage of the `debug` method. also creates a debug console which will display when pressing F12. it will display all log and debug messages. */ - debug?: boolean; - /** Array of keys in their full format (e.g. C-c) to ignore when keys are locked. Useful for creating a key that will always exit no matter whether the keys are locked. */ - ignoreLocked?: string[]; - - /** Do not clear the screen, only scroll down enough to make room for the elements on the screen. do not use the alternate screenbuffer. useful for writing a CLI tool or some kind of prompt (experimental - see test/widget-noalt.js) */ - noAlt?: boolean; - - /** Options for the cursor. */ - cursor?: CursorOptions; - } - - export interface CursorOptions { - /** have blessed draw a custom cursor and hide the terminal cursor (experimental). */ - artificial?: boolean; - /** shape of the artificial cursor. can be: block, underline, or line. */ - shape?: string; //'block'|'underline'|'line'; - /** whether the artificial cursor blinks. */ - blink?: boolean; - /** color of the artificial cursor. accepts any valid color value (null is default). */ - color?: string; - } - - export interface ScreenEventCallback { - (character:string, keyCode:KeyCode): void; - } - - export class Screen extends Node - { - constructor(options?:ScreenOptions); - - /** the blessed Program object. */ - program: any; - /** the blessed Tput object (only available if you passed tput: true to the Program constructor.) */ - tput: any; - /** top of the focus history stack. */ - focused: any; - /** width of the screen (same as program.cols). */ - width: number; - /** height of the screen (same as program.rows). */ - height: number; - /** same as screen.width. */ - cols: number; - /** same as screen.height. */ - rows: number; - - /** calculated relative left offset. */ - left: number; - /** calculated relative right offset. */ - right: number; - /** calculated relative top offset. */ - top: number; - /** calculated relative bottom offset. */ - bottom: number; - /** calculated absolute left offset. */ - aleft: number; - /** calculated absolute right offset. */ - aright: number; - /** calculated absolute top offset. */ - atop: number; - /** calculated absolute bottom offset. */ - abottom: number; - - - /** whether the focused element grabs all keypresses. */ - grabKeys: boolean; - /** prevent keypresses from being received by any element. */ - lockKeys: boolean; - /** the currently hovered element. only set if mouse events are bound. */ - hover: Element; - /** set or get window title. */ - title: string; - - /** write string to the log file if one was created. */ - log(...msg:any[]): void; - /** same as the log method, but only gets called if the debug option was set. */ - debug(...msg:string[]): void; - /** allocate a new pending screen buffer and a new output screen buffer. */ - alloc(): void; - /** draw the screen based on the contents of the screen buffer. */ - draw(start:number, end:number): void; - /** render all child elements, writing all data to the screen buffer and drawing the screen. */ - render(): void; - /** clear any region on the screen. */ - clearRegion(x1:number, x2:number, y1:number, y2:number): void; - /** fill any region with a character of a certain attribute. */ - fillRegion(attr:number, ch:string, x1:number, x2:number, y1:number, y2:number): void; - /** focus element by offset of focusable elements. */ - focusOffset(offset:number): void; - /** focus previous element in the index. */ - focusPrevious(): void; - /** focus next element in the index. */ - focusNext(): void; - /** push element on the focus stack (equivalent to screen.focused = el). */ - focusPush(element:Element): void; - /** pop element off the focus stack. */ - focusPop(): void; - /** save the focused element. */ - saveFocus(): void; - /** restore the saved focused element. */ - restoreFocus(): void; - /** "rewind" focus to the last visible and attached element. */ - rewindFocus(): void; - /** bind a keypress listener for a specific key. */ - key(keyEvents:string|string[], callback:ScreenEventCallback): void; - /** bind a keypress listener for a specific key once. */ - onceKey(keyEvents:string|string[], callback:ScreenEventCallback): void; - /** remove a keypress listener for a specific key. */ - unkey(name:string, listener:ScreenEventCallback): void; - /** spawn a process in the foreground, return to blessed app after exit. */ - spawn(file:string, args:string[], options:NodeChildProcessExecOptions): child_process.ChildProcess; - /** spawn a process in the foreground, return to blessed app after exit. executes callback on error or exit. */ - exec(file:string, args:string[], options:NodeChildProcessExecOptions, callback:GenericCallback): child_process.ChildProcess; - /** read data from text editor. */ - readEditor(options:{}, callback:GenericCallback): void; - /** set effects based on two events and attributes. */ - setEffects(el:Element, fel:Element, over:string, out:string, effects:Style, temp?:string): void; - /** insert a line into the screen (using csr: this bypasses the output buffer). */ - insertLine(n:number, y:number, top:number, bottom:number): void; - /** delete a line from the screen (using csr: this bypasses the output buffer). */ - deleteLine(n:number, y:number, top:number, bottom:number): void; - /** insert a line at the bottom of the screen. */ - insertBottom(top:number, bottom:number): void; - /** insert a line at the top of the screen. */ - insertTop(top:number, bottom:number): void; - /** delete a line at the bottom of the screen. */ - deleteBottom(top:number, bottom:number): void; - /** delete a line at the top of the screen. */ - deleteTop(top:number, bottom:number): void; - - /** enable mouse events for the screen and optionally an element (automatically called when a form of on('mouse') is bound). */ - enableMouse(el?:Element): void; - /** enable keypress events for the screen and optionally an element (automatically called when a form of on('keypress') is bound). */ - enableKeys(el?:Element): void; - /** enable key and mouse events. calls bot enableMouse and enableKeys. */ - enableInput(el?:Element): void; - - /** attempt to copy text to clipboard using iTerm2's propriety sequence. returns true if successful. */ - copyToClipboard(text:string): boolean; - /** attempt to change cursor shape. will not work in all terminals (see artificial cursors for a solution to this). returns true if successful. */ - cursorShape(shape:string, blink:boolean): boolean; - /** attempt to change cursor color. returns true if successful. */ - cursorColor(color: string): boolean; - /** attempt to reset cursor. returns true if successful. */ - cursorReset(): boolean; - - } - - export interface ElementOptions extends NodeOptions - { - fg?: string; - bg?: string; - scrollbar?: ColorPair; - focus?: Style; - hover?: Style; - - /** border object, see below. */ - border?: Border; - /** positioning options. */ - position?: Position; - /** amount of padding on the inside of the element. can be a number or an object containing the properties: left, right, top, and bottom. */ - padding?: number|Padding; - /** element's text content. */ - content?: string; - /** element is clickable. */ - clickable?: boolean; - /** element is focusable and can receive key input. */ - input?: boolean; - /** element is focused. */ - focused?: boolean; - /** whether the element is hidden. */ - hidden?: boolean; - /** a simple text label for the element. */ - label?: string; - /** a floating text label for the element which appears on mouseover. */ - hoverText?: string; - /** text alignment: left, center, or right. */ - align?: string; - /** vertical text alignment: top, middle, or bottom. */ - valign?: string; - /** shrink/flex/grow to content and child elements. width/height during render. */ - shrink?: any; - /** width of the element, can be a number, percentage (0-100%), or keyword (half or shrink). */ - width?: number|string; - /** height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). */ - height?: number|string; - /** whether the element is scrollable or not. */ - scrollable?: boolean; - /** background character (default is whitespace ). */ - ch?: string; - /** allow the element to be dragged with the mouse. */ - draggable?: boolean; - } - - export class Element extends Node - { - constructor(options?:ElementOptions); - - /** name of the element. useful for form submission. */ - name: string; - /** border object. */ - border: Border; - /** contains attributes (e.g. fg/bg/underline). see above. */ - style: Style; - /** raw width, height, and offsets. */ - position: Position; - /** type of border (line or bg). bg by default. */ - type: string; //'line'|'bg'; - /** character to use if bg type, default is space. */ - ch: string; - /** raw text content. */ - content: string; - /** whether the element is hidden or not. */ - hidden: boolean; - /** whether the element is visible or not. */ - visible: boolean; - /** whether the element is attached to a screen in its ancestry somewhere. */ - detached: boolean; - /** calculated width. */ - width: number; - /** calculated height. */ - height: number; - /** whether the element is draggable. set to true to allow dragging. */ - draggable: boolean; - - - - /** calculated relative left offset. */ - left: number; - /** calculated relative right offset. */ - right: number; - /** calculated relative top offset. */ - top: number; - /** calculated relative bottom offset. */ - bottom: number; - /** calculated absolute left offset. */ - aleft: number; - /** calculated absolute right offset. */ - aright: number; - /** calculated absolute top offset. */ - atop: number; - /** calculated absolute bottom offset. */ - abottom: number; - - - /** write content and children to the screen buffer. */ - render(): void; - /** hide element. */ - hide(): void; - /** show element. */ - show(): void; - /** toggle hidden/shown. */ - toggle(): void; - /** focus element. */ - focus(): void; - /** bind a keypress listener for a specific key. */ - key(name:string|string[], listener:(character?:any, keyCode?:any) => void): void; - /** bind a keypress listener for a specific key once. */ - onceKey(name:string, listener:() => void): void; - /** remove a keypress listener for a specific key. */ - unkey(name:string, listener:() => void): void; - /** same as el.on('screen', ...) except this will automatically cleanup listeners after the element is detached. */ - onScreenEvent(event:string, listener:(...args:any[]) => void): void; - /** set the z-index of the element (changes rendering order). */ - setIndex(z:number): void; - /** put the element in front of its siblings. */ - setFront(): void; - /** put the element in back of its siblings. */ - setBack(): void; - /** set the label text for the top-left corner. example options: {text:'foo',side:'left'} */ - setLabel(textOrOptions:string|{}): void; - /** remove the label completely. */ - removeLabel(): void; - /** set the hover text for the bottom-right corner. example options: {text:'foo'} */ - setHover(textOrOptions:string|{}): void; - /** remove the hover label completely. */ - removeHover(): void; - /** set the content. note: when text is input, it will be stripped of all non-SGR escape codes, tabs will be replaced with 8 spaces, and tags will be replaced with SGR codes (if enabled). */ - setContent(text:string): void; - /** return content, slightly different from el.content. assume the above formatting. */ - getContent(): void; - /** similar to setContent, but ignore tags and remove escape codes. */ - setText(text:string): void; - /** similar to getContent, but return content with tags and escape codes removed. */ - getText(): void; - /** insert a line into the box's content. */ - insertLine(index:number, lines:string|string[]): void; - /** delete a line from the box's content. */ - deleteLine(index:number, numLines:number): void; - /** get a line from the box's content. */ - getLine(index:number): void; - /** get a line from the box's content from the visible top. */ - getBaseLine(index:number): void; - /** set a line in the box's content. */ - setLine(index:number, line:string): void; - /** set a line in the box's content from the visible top. */ - setBaseLine(index:number, line:string): void; - /** clear a line from the box's content. */ - clearLine(index:number): void; - /** clear a line from the box's content from the visible top. */ - clearBaseLine(index:number): void; - /** insert a line at the top of the box. */ - insertTop(lines:string|string[]): void; - /** insert a line at the bottom of the box. */ - insertBottom(lines:string|string[]): void; - /** delete a line at the top of the box. */ - deleteTop(): void; - /** delete a line at the bottom of the box. */ - deleteBottom(): void; - /** unshift a line onto the top of the content. */ - unshiftLine(lines:string|string[]): void; - /** shift a line off the top of the content. */ - shiftLine(index:number): void; - /** push a line onto the bottom of the content. */ - pushLine(lines:string|string[]): void; - /** pop a line off the bottom of the content. */ - popLine(index:number): void; - /** an array containing the content lines. */ - getLines(): void; - /** an array containing the lines as they are displayed on the screen. */ - getScreenLines(): void; - /** get a string's real length, taking into account tags. */ - textLength(text:string): number; - - /** enable dragging of the element. */ - enableDrag(): void; - /** disable dragging of the element. */ - disableDrag(): void; - } - - - // - // Box - // - - export interface BoxOptions extends ElementOptions { - // intentionally empty - } - - export class Box extends Element { - constructor(options?:BoxOptions); - // intentionally empty - } - - - // - // ScrollableBox - // - - export interface ScrollableBoxOptions extends BoxOptions { - /** a limit to the childBase. default is `Infinity`. */ - baseLimit: number; - /** a option which causes the ignoring of `childOffset`. this in turn causes the childBase to change every time the element is scrolled. */ - alwaysScroll: boolean; - /** object enabling a scrollbar. */ - scrollbar: ScrollBar; - } - - /** A box with scrollable content. */ - export class ScrollableBox extends Box { - constructor(options?:ScrollableBoxOptions); - - /** the offset of the top of the scroll content. */ - childBase: number; - /** the offset of the chosen item/line. */ - childOffset: number; - /** scroll the content by a relative offset. */ - scroll(offset:number): void; - /** scroll the content to an absolute index. */ - scrollTo(index:number): void; - /** same as `scrollTo`. */ - setScroll(index:number): void; - /** set the current scroll index in percentage (0-100). */ - setScrollPerc(perc:number): void; - /** get the current scroll index in lines. */ - getScroll(): number; - /** get the actual height of the scrolling area. */ - getScrollHeight(): number; - /** get the current scroll index in percentage. */ - getScrollPerc(): number; - /** reset the scroll index to its initial state. */ - resetScroll(): void; - - } - - export interface ScrollBar { - /** style of the scrollbar. */ - style: Style; - /** style of the scrollbar track if present (takes regular style options). */ - track: Style; - } - - - // - // ScrollableText - // - - export interface ScrollableTextOptions extends ScrollableBoxOptions { - /** whether to enable automatic mouse support for this element. */ - mouse: boolean; - /** use predefined keys for navigating the text. */ - keys: boolean; - /** use vi keys with the `keys` option. */ - vi: boolean; - } - - /** __DEPRECATED__ - Use Box with the `scrollable` and `alwaysScroll` options instead. A scrollable text box which can display and scroll text, as well as handle pre-existing newlines and escape codes. */ - export class ScrollableText extends ScrollableBox { - constructor(options?:ScrollableTextOptions); - } - - - - // - // Text - // - - export interface TextOptions extends ElementOptions { - align?: string; //'left'|'center'|'right'; - } - - export class Text extends Element { - constructor(options?:TextOptions); - // intentionally empty - } - - - // - // Line - // - - export interface LineOptions extends BoxOptions { - orientation?: string; //'vertical'|'horizontal'; - style?: Style; - } - - export class Line extends Box { - constructor(options?:LineOptions); - // intentionally empty - } - - - // - // List - // - - export interface ListStyle extends Style { - selected?: Style; - item?: Style; - } - - export interface ListOptions extends BoxOptions - { - style?: ListStyle; - - /** whether to automatically enable mouse support for this list (allows clicking items). */ - mouse?: boolean; - /** use predefined keys for navigating the list. */ - keys?: any; - /** use vi keys with the keys option. */ - vi?: boolean; - /** an array of strings which become the list's items. */ - items?: string[]; - /** a function that is called when vi mode is enabled and the key / is pressed. This function accepts a callback function which should be called with the search string. The search string is then used to jump to an item that is found in items. */ - search?: (callback:(searchString:string) => void) => void; - /** whether the list is interactive and can have items selected (default: true). */ - interactive?: boolean; - } - - export class List extends Box - { - constructor(options?:ListOptions); - - /** The text of the currently selected item. */ - value:string; - /** The items in the list. */ - items:string[]; - /** The items in the list. */ - ritems:string[]; - /** The index of the current selection. */ - selected:number; - - /** add an item based on a string. */ - addItem(text:string): void; - /** returns the item index from the list. child can be an element, index, or string. */ - getItemIndex(child:Element|number|string): void; - /** returns the item element. child can be an element, index, or string. */ - getItem(child:Element|number|string): void; - /** removes an item from the list. child can be an element, index, or string. */ - removeItem(child:Element|number|string): void; - /** clears all items from the list. */ - clearItems(): void; - /** sets the list items to multiple strings. */ - setItems(items:string[]): void; - /** Sets the current selection by absolute index. */ - select(index:number): void; - /** Changes the current selection based on current offset. */ - move(offset:number): void; - /** select item above selected. */ - up(amount:number): void; - /** select item below selected. */ - down(amount:number): void; - /** show/focus list and pick an item. the callback is executed with the result. */ - pick(cwd:string, callback:(err:any, file:string) => void): void; - - /** show/focus list and pick an item. the callback is executed with the result. */ - pick(callback:(err:any, file:string) => void): void; - } - - // - // Input - // - - export interface InputOptions extends BoxOptions { - // intentionally empty - } - - export class Input extends Box { - constructor(options?:InputOptions); - // intentionally empty - } - - export interface InputOptions extends BoxOptions { - // intentionally empty - } - - // - // Textarea - // - - export interface TextareaOptions extends InputOptions - { - /** use pre-defined keys (`i` or `enter` for insert, `e` for editor, `C-e` for editor while inserting). */ - keys?: boolean; - /** use pre-defined mouse events (right-click for editor). */ - mouse?: boolean; - /** call `readInput()` when the element is focused. automatically unfocus. */ - inputOnFocus?: boolean; - } - - /** A box which allows multiline text input. */ - export class Textarea extends Input - { - constructor(options?:TextareaOptions); - - /** the input text. __read-only__. */ - value: string; - - /** submit the textarea (emits `submit`). */ - submit(): void; - /** cancel the textarea (emits `cancel`). */ - cancel(): void; - /** grab key events and start reading text from the keyboard. takes a callback which receives the final value. */ - readInput(callback:GenericCallback): void; - /** open text editor in `$EDITOR`, read the output from the resulting file. takes a callback which receives the final value. */ - readEditor(callback:GenericCallback): void; - /** the same as `this.value`, for now. */ - getValue(): string; - /** clear input. */ - clearValue(): void; - /** set value. */ - setValue(text:string): void; - } - - - // - // Textbox - // - - export interface TextboxOptions extends TextareaOptions { - /** completely hide text. */ - secret?: boolean; - /** replace text with asterisks (`*`). */ - censor?: boolean; - } - - /** A box which allows text input. */ - export class Textbox extends Textarea { - constructor(options?:TextboxOptions); - - /** completely hide text. */ - secret: boolean; - /** replace text with asterisks (`*`). */ - censor: boolean; - } - - - // - // Button - // - - export interface ButtonOptions extends InputOptions { - } - - /** A button which can be focused and allows key and mouse input. */ - export class Button extends Input { - constructor(options?:ButtonOptions); - - // on(event:string, callback:() => void): void; - // on(event:'press', callback:() => void); - - /** press button. emits 'press'. */ - press(): void; - } - - - // - // ProgressBar - // - - export interface ProgressBarOptions extends InputOptions { - /** can be `horizontal` or `vertical`. */ - orientation: string; - /** the character to fill the bar with (default is space). */ - pch: string; - /** the amount filled (0 - 100). */ - filled: number; - /** same as `filled`. */ - value: number; - /** enable key support. */ - keys: boolean; - /** enable mouse support. */ - mouse: boolean; - - /** contains the extra key 'bar', which defines the style of the bar contents itself. */ - style: ProgressBarStyle; - } - - export interface ProgressBarStyle extends Style { - /** style of the bar contents itself. */ - bar: Style; - } - - - export class ProgressBar extends Input { - constructor(options?:ProgressBarOptions); - - /** progress the bar by a fill amount. */ - progress(amount:number): void; - /** set progress to specific amount. */ - setProgress(amount:number): void; - /** reset the bar. */ - reset(): void; - } - - // - // Checkbox - // - - export interface CheckboxOptions extends InputOptions { - /** whether the element is checked or not. */ - checked: boolean; - /** enable mouse support. */ - mouse: boolean; + export module Events { + + export interface IMouseEventArg { + x: number; + y: number; + action: Types.TMouseAction; + } + + export interface IKeyEventArg { + full: string; + name: string; + shift: boolean; + ctrl: boolean; + meta: boolean; + sequence: string; + } } - - /** A checkbox which can be used in a form element. */ - export class Checkbox extends Input - { - constructor(options?:CheckboxOptions); - - /** the text next to the checkbox (do not use setcontent, use `check.text = ''`). */ - text: string; - /** whether the element is checked or not. */ - checked: boolean; - /** same as `checked`. */ - value: boolean; - - /** check the element. */ - check(): void; - /** uncheck the element. */ - uncheck(): void; - /** toggle checked state. */ - toggle(): void; - } - - - // - // RadioSet - // - - export interface RadioSetOptions extends BoxOptions { - } - - - export class RadioSet extends Box { - constructor(options?:RadioSetOptions); - } - - - // - // RadioButton - // - - export interface RadioButtonOptions extends CheckboxOptions { - } - - - /** A radio button which can be used in a form element. */ - export class RadioButton extends Checkbox { - constructor(options?:RadioButtonOptions); - } - - - - // - // Prompt - // - - export interface PromptOptions extends BoxOptions { - } - - - /** A prompt box containing a text input, okay, and cancel buttons (automatically hidden). */ - export class Prompt extends Box - { - constructor(options?:PromptOptions); - - /** show the prompt and wait for the result of the textbox. set text and initial value */ - input(text:string, value:any, callback:(val:any) => void): void; - /** show the prompt and wait for the result of the textbox. set text and initial value */ - setInput(text:string, value:any, callback:(val:any) => void): void; - /** show the prompt and wait for the result of the textbox. set text and initial value */ - readInput(text:string, value:any, callback:(val:any) => void): void; - } - - - // - // Question - // - - export interface QuestionOptions extends BoxOptions { - } - - - /** A question box containing okay and cancel buttons (automatically hidden). */ - export class Question extends Box - { - constructor(options?:QuestionOptions); - - /** ask a `question`. `callback` will yield the result. */ - ask(question:string, callback:(result:any) => void): void; - } - - - // - // Message - // - - export interface MessageOptions extends BoxOptions { - } - - - /** A box containing a message to be displayed (automatically hidden). */ - export class Message extends Box - { - constructor(options?:MessageOptions); - - /** display a message for a time (default is 3 seconds). set time to 0 for a perpetual message that is dismissed on keypress. */ - log(text:string, timeOrCallback:number|MessageCallback, callback?:MessageCallback): void; - /** display a message for a time (default is 3 seconds). set time to 0 for a perpetual message that is dismissed on keypress. */ - display(text:string, timeOrCallback:number|MessageCallback, callback?:MessageCallback): void; - /** display an error in the same way. */ - error(text:string, timeOrCallback:number|MessageCallback, callback?:MessageCallback): void; - } - - export interface MessageCallback { - (): void; - } - - - // - // Loading - // - - export interface LoadingOptions extends BoxOptions { - } - - /** A box with a spinning line to denote loading (automatically hidden). */ - export class Loading extends Box - { - constructor(options?:LoadingOptions); - - /** display the loading box with a message. will lock keys until `stop` is called. */ - load(text:string): void; - /** hide loading box. unlock keys. */ - stop(): void; - } - - - // - // Listbar - // - - export interface ListbarOptions extends BoxOptions - { - /** Listbar's `style` object includes sub-styles for `selected` and `item`. */ - style?: ListbarStyle; - - /** set buttons using an object with keys as titles of buttons, containing of objects containing keys of `keys` and `callback`. */ - items?: ListbarItemSet; - /** set buttons using an object with keys as titles of buttons, containing of objects containing keys of `keys` and `callback`. */ - commands?: ListbarItemSet; - /** automatically bind list buttons to keys 0-9. */ - autoCommandKeys?: boolean; - } - - export interface ListbarItemSet { - [name: string]: ListbarItem; - } - - export interface ListbarItem { - keys: string[]; - callback: GenericCallback; - } - - export interface ListbarStyle extends Style - { - /** style for a selected item. */ - selected: Style; - /** style for an unselected item. */ - item: Style; - } - - /** A horizontal list. Useful for a main menu bar. */ - export class Listbar extends Box - { - constructor(options?:ListbarOptions); - - /** append an item to the bar. */ - add(item:ListbarItem, callback:GenericCallback): void; - /** append an item to the bar. */ - addItem(item:ListbarItem, callback:GenericCallback): void; - /** append an item to the bar. */ - appendItem(item:ListbarItem, callback:GenericCallback): void; - - /** select button and execute its callback. */ - selectTab(index: number): void; - - /** set commands (see `commands` option above). */ - setItems(commands: ListbarItemSet): void; - /** select an item on the bar. */ - select(offset: number): void; - /** remove item from the bar. */ - removeItem(child:ListbarItem): void; - /** move focus relatively across the bar. */ - move(offset: number): void; - /** move focus left relatively across the bar. */ - moveLeft(offset: number): void; - /** move focus right relatively across the bar. */ - moveRight(offset: number): void; - } - - - // - // Log - // - - export interface LogOptions extends ScrollableTextOptions { - /** amount of scrollback allowed. default: Infinity. */ - scrollback?: number; - /** scroll to bottom on input even if the user has scrolled up. default: false. */ - scrollOnInput?: boolean; - } - - - /** A log permanently scrolled to the bottom. */ - export class Log extends ScrollableText - { - constructor(options?:LogOptions); - - /** amount of scrollback allowed. default: Infinity. */ - scrollback: number; - /** scroll to bottom on input even if the user has scrolled up. default: false. */ - scrollOnInput: boolean; - - /** add a log line. */ - log(text:string): void; - /** add a log line. */ - add(text:string): void; - } - - - // - // Table - // - - export interface TableOptions extends BoxOptions - { - /** array of array of strings representing rows (same as `data`). */ - rows?: string[][]; - /** array of array of strings representing rows (same as `rows`). */ - data?: string[][]; - /** spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). */ - pad?: number; - /** do not draw inner cells. */ - noCellBorders?: boolean; - /** fill cell borders with the adjacent background color. */ - fillCellBorders?: boolean; - - /** includes `header` and `cell` substyles. */ - style?: TableStyle; - } - - export interface TableStyle extends Style { - /** header style. */ - header: Style; - /** cell style. */ - cell: Style; - } - - /** A stylized table of text elements. */ - export class Table extends Box - { - /** includes `header` and `cell` substyles. */ - style: TableStyle; - - /** set rows in table. array of arrays of strings. */ - setData(rows: string[][]): void; - /** set rows in table. array of arrays of strings. */ - setRows(rows: string[][]): void; - } - - - // - // ListTable - // - - export interface ListTableOptions extends ListOptions - { - /** array of array of strings representing rows (same as `data`). */ - rows?: string[][]; - /** array of array of strings representing rows (same as `rows`). */ - data?: string[][]; - /** spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). */ - pad?: number; - - /** do not draw inner cells. */ - noCellBorders?: boolean; - - /** includes `header` and `cell` substyles. */ - style?: TableStyle; - } - - export interface ListTableStyle extends TableStyle { - } - - - /** A stylized table of text elements with a list. */ - export class ListTable extends List - { - constructor(options?:ListTableOptions); - - /** set rows in table. array of arrays of strings. */ - setData(rows: string[][]): void; - /** set rows in table. array of arrays of strings. */ - setRows(rows: string[][]): void; - } - - // - // Image - // - - export interface ImageOptions extends BoxOptions { - /** path to image. */ - file: string; - /** path to w3mimgdisplay. if a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. */ - w3m: string; - } - - - /** Display an image in the terminal (jpeg, png, gif) using w3mimgdisplay. Requires w3m to be installed. X11 required: works in xterm, urxvt, and possibly other terminals. */ - export class Image extends Box - { - constructor(options?:ImageOptions); - - /** set the image in the box to a new path. */ - setImage (img:string, callback:GenericCallback): void; - /** clear the current image. */ - clearImage (callback:GenericCallback): void; - /** get the size of an image file in pixels. */ - imageSize (img:string, callback:GenericCallback): void; - /** get the size of the terminal in pixels. */ - termSize (callback:GenericCallback): void; - /** get the pixel to cell ratio for the terminal. */ - getPixelRatio (callback:GenericCallback): void; - } - - - // - // Form - // - - export interface FormOptions extends BoxOptions { - /** allow default keys (tab, vi keys, enter). */ - keys?:boolean; - /** allow vi keys. */ - vi?:boolean; - } - - export class Form extends Box - { - constructor(options?:FormOptions); - - /** last submitted data. */ - submission: any; - - // on(event:string, callback:() => void): void; - // on(event:'submit', callback:(data) => void): void; - // on(event:'cancel', callback:() => void): void; - // on(event:'reset', callback:() => void): void; - - next(): void; - previous(): void; - - resetSelected(): void; - /** focus first form element. */ - focusFirst(): void; - /** focus last form element. */ - focusLast(): void; - /** focus next form element. */ - focusNext(): void; - /** focus previous form element. */ - focusPrevious(): void; - /** submit the form. */ - submit(): void; - /** discard the form. */ - cancel(): void; - /** clear the form. */ - reset(): void; - } - - - // - // FileManager - // - - export interface FileManagerOptions extends ListOptions { - cwd?: string; - } - - export interface DirectoryEntry { - name: string; - text: string; - dir: boolean; - symlink: boolean; - } - - export class FileManager extends List - { - constructor(options?:FileManagerOptions); - - cwd: string; - - useFormatter (formatterFn:(entry:DirectoryEntry) => DirectoryEntry): void; - - /** refresh the file list (perform a readdir on cwd and update the list items). */ - refresh (cwd?:string, callback?:() => void): void; - - /** refresh the file list. */ - refresh (callback?:() => void): void; - - /** reset back to original cwd. */ - reset (cwd?:string, callback?:() => void): void; - } - - - // - // Terminal - // - - export interface TerminalOptions extends BoxOptions - { - /** handler for input data. */ - handler?: (userInput:Buffer) => void; - /** name of shell. $SHELL by default. */ - shell?:string; - /** args for shell. */ - args?:any; - /** can be line, underline, and block. */ - cursor?:string; //'line'|'underline'|'block'; - } - - export class Terminal extends Box - { - /** reference to the headless term.js terminal. */ - term: any; - /** reference to the pty.js pseudo terminal. */ - pty: any; - - /** write data to the terminal. */ - write(data:string): void; - - /** nearly identical to `element.screenshot`, however, the specified region includes the terminal's _entire_ scrollback, rather than just what is visible on the screen. */ - screenshot(xi?:number, xl?:number, yi?:number, yl?:number): string; - } - - - export interface NodeChildProcessExecOptions - { + export interface NodeChildProcessExecOptions { cwd?: string; stdio?: any; customFds?: any; @@ -1260,10 +159,2676 @@ declare module "blessed" maxBuffer?: number; killSignal?: string; } + + export interface IDestroyable { + destroy(): void; + } + + export interface IOptions { + } + + export interface IHasOptions { + options: T; + } + + export interface TputsOptions extends IOptions { + terminal?: string; + extended?: boolean; + debug?: boolean; + termcap?: string; + terminfoFile?: string; + terminfoPrefix?: string; + termcapFile?: string; + } + + export class Tput implements IHasOptions { + constructor(opts: TputsOptions); + + // ** properties ** // + + /** + * Original options object. + */ + options: TputsOptions; + + debug: boolean; + padding: boolean; + extended: boolean; + printf: boolean; + termcap: string; + terminfoPrefix: string; + terminfoFile: string; + termcapFile: string; + error: Error; + terminal: string; + + setup(): void; + term(is: any): boolean; + readTerminfo(term: string): string; + parseTerminfo(data: any, file: string): { + header: { + dataSize: number; + headerSize: number; + magicNumber: boolean; + namesSize: number; + boolCount: number; + numCount: number; + strCount: number; + strTableSize: number; + extended: { + dataSize: number; + headerSize: number; + boolCount: number; + numCount: number; + strCount: number; + strTableSize: number; + lastStrTableOffset: number; + } + } + name: string; + names: string[]; + desc: string; + bools: Object; + numbers: Object; + strings: Object; + }; + } + + export interface IDestroyable { + destroy(): void; + } + + export interface INodeOptions extends IOptions { + name?: string; + screen?: Screen; + parent?: Node; + children?: Node[]; + focusable?: boolean; + } + + export abstract class Node extends EventEmitter implements IHasOptions, IDestroyable { + constructor(options: INodeOptions); + + // ** properties ** // + + focusable: boolean; + + /** + * Original options object. + */ + options: INodeOptions; + + /** + * An object for any miscellanous user data. + */ + data: {[index: string]: any;}; + /** + * An object for any miscellanous user data. + */ + _: {[index: string]: any;}; + /** + * An object for any miscellanous user data. + */ + $: {[index: string]: any;}; + /** + * Type of the node (e.g. box). + */ + type: string; + /** + * Render index (document order index) of the last render call. + */ + index: number; + /** + * Parent screen. + */ + screen: Screen; + /** + * Parent node. + */ + parent: Node; + /** + * Array of node's children. + */ + children: Node[]; + + // ** methods ** // + + /** + * Prepend a node to this node's children. + */ + prepend(node: Node): void; + /** + * Append a node to this node's children. + */ + append(node: Node): void; + /** + * Remove child node from node. + */ + remove(node: Node): void; + /** + * Insert a node to this node's children at index i. + */ + insert(node: Node, index: number): void; + /** + * Insert a node to this node's children before the reference node. + */ + insertBefore(node: Node, refNode: Node): void; + /** + * Insert a node from node after the reference node. + */ + insertAfter(node: Node, refNode: Node): void; + /** + * Remove node from its parent. + */ + detach(): void; + /** + * Remove node from its parent. + */ + free(): void; + /** + * Remove node from its parent. + */ + forDescendants(iter: Function, s: any): void; + /** + * Remove node from its parent. + */ + forAncestors(iter: Function, s: any): void; + /** + * Remove node from its parent. + */ + collectDescendants(s: any): void; + /** + * Remove node from its parent. + */ + collectAncestors(s: any): void; + /** + * Remove node from its parent. + */ + emitDescendants(): void; + /** + * Remove node from its parent. + */ + emitAncestors(): void; + /** + * Remove node from its parent. + */ + hasDescendant(target: Node): void; + /** + * Remove node from its parent. + */ + hasAncestor(target: Node): boolean; + /** + * Remove node from its parent. + */ + destroy(): void; + /** + * Emit event for element, and recursively emit same event for all descendants. + */ + emitDescendants(type: string, ...args: any[]): void; + /** + * Get user property with a potential default value. + */ + get(name: string, def: T): T; + /** + * Set user property to value. + */ + set(name: string, value: T): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Received when node is added to a parent. + */ + on(event: "adopt", callback: (arg: Node) => void): this; + /** + * Received when node is removed from it's current parent. + */ + on(event: "remove", callback: (arg: Node) => void): this; + /** + * Received when node gains a new parent. + */ + on(event: "reparent", callback: (arg: Node) => void): this; + /** + * Received when node is attached to the screen directly or somewhere in its ancestry. + */ + on(event: "attach", callback: (arg: Node) => void): this; + /** + * Received when node is detached from the screen directly or somewhere in its ancestry. + */ + on(event: "detach", callback: (arg: Node) => void): this; + } + + export class NodeWithEvents extends Node { + // ** methods ** // + + /** + * Bind a keypress listener for a specific key. + */ + key(name: string | string[], listener: Function): void; + /** + * Bind a keypress listener for a specific key once. + */ + onceKey(name: string, listener: Function): void; + /** + * Remove a keypress listener for a specific key. + */ + unkey(name: string, listener: Function): void; + removeKey(name: string, listener: Function): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Received on screen resize. + */ + on(event: "resize", callback: () => void): this; + /** + * Received on mouse events. + */ + on(event: "mouse", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mouseout", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mouseover", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mousedown", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mouseup", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mousewheel", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "wheeldown", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "wheelup", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mousemove", callback: (arg: Events.IMouseEventArg) => void): this; + /** + * Received on key events. + */ + on(event: "keypress", callback: (ch: string, key: Events.IKeyEventArg) => void): this; + /** + * Global events received for all elements. + */ + on(event: "element click", callback: (arg: Screen) => void): this; + on(event: "element mouseover", callback: (arg: Screen) => void): this; + on(event: "element mouseout", callback: (arg: Screen) => void): this; + on(event: "element mouseup", callback: (arg: Screen) => void): this; + /** + * Received on key event for [name]. + */ + //on(event: "key", callback: (arg: BlessedScreen) => void): this; + /** + * Received when the terminal window focuses/blurs. Requires a terminal supporting the + * focus protocol and focus needs to be passed to program.enableMouse(). + */ + on(event: "focus", callback: (arg: Screen) => void): this; + /** + * Received when the terminal window focuses/blurs. Requires a terminal supporting the + * focus protocol and focus needs to be passed to program.enableMouse(). + */ + on(event: "blur", callback: (arg: Screen) => void): this; + /** + * Received before render. + */ + on(event: "prerender", callback: () => void): this; + /** + * Received on render. + */ + on(event: "render", callback: () => void): this; + /** + * Received when blessed notices something untoward (output is not a tty, terminfo not found, etc). + */ + on(event: "warning", callback: (text: string) => void): this; + /** + * Received when the screen is destroyed (only useful when using multiple screens). + */ + on(event: "destroy", callback: () => void): this; + /** + * Received when the element is moved. + */ + on(event: "move", callback: () => void): this; + /** + * Element was clicked (slightly smarter than mouseup). + */ + on(event: "click", callback: (arg: Screen) => void): this; + /** + * Received when element is shown. + */ + on(event: "show", callback: () => void): this; + /** + * Received when element becomes hidden. + */ + on(event: "hide", callback: () => void): this; + + on(event: "set content", callback: () => void): this; + on(event: "parsed content", callback: () => void): this; + } + + export interface IScreenOptions extends INodeOptions { + /** + * The blessed Program to be associated with. Will be automatically instantiated if none is provided. + */ + program?: BlessedProgram; + /** + * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with + * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, + * however, it is more optimal for terminal rendering. + */ + smartCSR?: boolean; + /** + * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, + * but may cause flickering depending on what is on each side of the element. + */ + fastCSR?: boolean; + /** + * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work + * with terminals that don't support it, but only on lines with the default background color. As it + * stands with the current implementation, it's uncertain how much terminal performance this adds at + * the cost of overhead within node. + */ + useBCE?: boolean; + /** + * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). + */ + resizeTimeout?: number; + /** + * The width of tabs within an element's content. + */ + tabSize?: number; + /** + * Automatically position child elements with border and padding in mind (NOTE: this is a recommended + * option. It may become default in the future). + */ + autoPadding?: boolean; + + cursor?: Types.TCursor; + + /** + * Create a log file. See log method. + */ + log?: (...msg: any[]) => void; + /** + * Dump all output and input to desired file. Can be used together with log option if set as a boolean. + */ + dump?: string; + /** + * Debug mode. Enables usage of the debug method. Also creates a debug console which will display when + * pressing F12. It will display all log and debug messages. + */ + debug?: (...msg: string[]) => void; + /** + * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful + * for creating a key that will always exit no matter whether the keys are locked. + */ + ignoreLocked?: boolean; + /** + * Automatically "dock" borders with other elements instead of overlapping, depending on position + * (experimental). For example: These border-overlapped elements: + */ + dockBorders?: boolean; + /** + * Normally, dockable borders will not dock if the colors or attributes are different. This option + * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. + */ + ignoreDockContrast?: boolean; + /** + * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode + * combining characters. This allows you to display text above the basic multilingual plane. This + * is behind an option because it may affect performance slightly negatively. Without this option + * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', + * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply + * removes them from an element's content if iTerm2 is detected). + */ + fullUnicode?: boolean; + /** + * Send focus events after mouse is enabled. + */ + sendFocus?: boolean; + /** + * Display warnings (such as the output not being a TTY, similar to ncurses). + */ + warnings?: boolean; + /** + * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. + * If value is true unicode is forced. If value is false non-unicode is forced (default: null). + */ + forceUnicode?: boolean; + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + * */ + input?: stream.Writable; + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + * */ + output?: stream.Readable; + /** + * The blessed Tput object (only available if you passed tput: true to the Program constructor.) + */ + tput?: Tput; + /** + * Top of the focus history stack. + */ + focused?: BlessedElement; + /** + * Width of the screen (same as program.cols). + */ + width?: Types.TPosition; + /** + * Height of the screen (same as program.rows). + */ + height?: Types.TPosition; + /** + * Same as screen.width. + */ + cols?: number; + /** + * Same as screen.height. + */ + rows?: number; + /** + * Relative top offset, always zero. + */ + top?: Types.TTopLeft; + /** + * Relative left offset, always zero. + */ + left?: Types.TTopLeft; + /** + * Relative right offset, always zero. + */ + right?: Types.TPosition; + /** + * Relative bottom offset, always zero. + */ + bottom?: Types.TPosition; + /** + * Absolute top offset, always zero. + */ + atop?: Types.TTopLeft; + /** + * Absolute left offset, always zero. + */ + aleft?: Types.TTopLeft; + /** + * Absolute right offset, always zero. + */ + aright?: Types.TPosition; + /** + * Absolute bottom offset, always zero. + */ + abottom?: Types.TPosition; + /** + * Whether the focused element grabs all keypresses. + */ + grabKeys?: any; + /** + * Prevent keypresses from being received by any element. + */ + lockKeys?: boolean; + /** + * The currently hovered element. Only set if mouse events are bound. + */ + hover?: any; + /** + * Set or get terminal name. Set calls screen.setTerminal() internally. + */ + terminal?: string; + /** + * Set or get window title. + */ + title?: string; + } + + export class Screen extends NodeWithEvents implements IHasOptions { + constructor(opts: IScreenOptions); + + // ** properties ** // + cleanSides: any; + + /** + * Original options object. + */ + options: IScreenOptions; + + /** + * The blessed Program to be associated with. Will be automatically instantiated if none is provided. + */ + program: BlessedProgram; + /** + * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with + * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, + * however, it is more optimal for terminal rendering. + */ + smartCSR: boolean; + /** + * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, + * but may cause flickering depending on what is on each side of the element. + */ + fastCSR: boolean; + /** + * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work + * with terminals that don't support it, but only on lines with the default background color. As it + * stands with the current implementation, it's uncertain how much terminal performance this adds at + * the cost of overhead within node. + */ + useBCE: boolean; + /** + * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). + */ + resizeTimeout: number; + /** + * The width of tabs within an element's content. + */ + tabSize: number; + /** + * Automatically position child elements with border and padding in mind (NOTE: this is a recommended + * option. It may become default in the future). + */ + autoPadding: boolean; + + cursor: Types.TCursor; + + /** + * Dump all output and input to desired file. Can be used together with log option if set as a boolean. + */ + dump: string; + /** + * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful + * for creating a key that will always exit no matter whether the keys are locked. + */ + ignoreLocked: boolean; + /** + * Automatically "dock" borders with other elements instead of overlapping, depending on position + * (experimental). For example: These border-overlapped elements: + */ + dockBorders: boolean; + /** + * Normally, dockable borders will not dock if the colors or attributes are different. This option + * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. + */ + ignoreDockContrast: boolean; + /** + * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode + * combining characters. This allows you to display text above the basic multilingual plane. This + * is behind an option because it may affect performance slightly negatively. Without this option + * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', + * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply + * removes them from an element's content if iTerm2 is detected). + */ + fullUnicode: boolean; + /** + * Send focus events after mouse is enabled. + */ + sendFocus: boolean; + /** + * Display warnings (such as the output not being a TTY, similar to ncurses). + */ + warnings: boolean; + /** + * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. + * If value is true unicode is forced. If value is false non-unicode is forced (default: null). + */ + forceUnicode: boolean; + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + * */ + input: stream.Writable; + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + * */ + output: stream.Readable; + /** + * The blessed Tput object (only available if you passed tput: true to the Program constructor.) + */ + tput: Tput; + /** + * Top of the focus history stack. + */ + focused: BlessedElement; + /** + * Width of the screen (same as program.cols). + */ + width: Types.TPosition; + /** + * Height of the screen (same as program.rows). + */ + height: Types.TPosition; + /** + * Same as screen.width. + */ + cols: number; + /** + * Same as screen.height. + */ + rows: number; + /** + * Relative top offset, always zero. + */ + top: Types.TTopLeft; + /** + * Relative left offset, always zero. + */ + left: Types.TTopLeft; + /** + * Relative right offset, always zero. + */ + right: Types.TPosition; + /** + * Relative bottom offset, always zero. + */ + bottom: Types.TPosition; + /** + * Absolute top offset, always zero. + */ + atop: Types.TTopLeft; + /** + * Absolute left offset, always zero. + */ + aleft: Types.TTopLeft; + /** + * Absolute right offset, always zero. + */ + aright: Types.TPosition; + /** + * Absolute bottom offset, always zero. + */ + abottom: Types.TPosition; + /** + * Whether the focused element grabs all keypresses. + */ + grabKeys: any; + /** + * Prevent keypresses from being received by any element. + */ + lockKeys: boolean; + /** + * The currently hovered element. Only set if mouse events are bound. + */ + hover: any; + /** + * Set or get terminal name. Set calls screen.setTerminal() internally. + */ + terminal: string; + /** + * Set or get window title. + */ + title: string; + + // ** methods ** // + + /** + * Write string to the log file if one was created. + */ + log(...msg: any[]): void; + /** + * Same as the log method, but only gets called if the debug option was set. + */ + debug(...msg: string[]): void; + /** + * Allocate a new pending screen buffer and a new output screen buffer. + */ + alloc(): void; + /** + * Reallocate the screen buffers and clear the screen. + */ + realloc(): void; + /** + * Draw the screen based on the contents of the screen buffer. + */ + draw(start: number, end: number): void; + /** + * Render all child elements, writing all data to the screen buffer and drawing the screen. + */ + render(): void; + /** + * Clear any region on the screen. + */ + clearRegion(x1: number, x2: number, y1: number, y2: number): void; + /** + * Fill any region with a character of a certain attribute. + */ + fillRegion(attr: string, ch: string, x1: number, x2: number, y1: number, y2: number): void; + /** + * Focus element by offset of focusable elements. + */ + focusOffset(offset: number): any; + /** + * Focus previous element in the index. + */ + focusPrevious(): void; + /** + * Focus next element in the index. + */ + focusNext(): void; + /** + * Push element on the focus stack (equivalent to screen.focused = el). + */ + focusPush(element: BlessedElement): void; + /** + * Pop element off the focus stack. + */ + focusPop(): BlessedElement; + /** + * Save the focused element. + */ + saveFocus(): BlessedElement; + /** + * Restore the saved focused element. + */ + restoreFocus(): BlessedElement; + /** + * "Rewind" focus to the last visible and attached element. + */ + rewindFocus(): BlessedElement; + /** + * Spawn a process in the foreground, return to blessed app after exit. + */ + spawn(file: string, args: string[], options: NodeChildProcessExecOptions): child_process.ChildProcess; + /** + * Spawn a process in the foreground, return to blessed app after exit. Executes callback on error or exit. + */ + exec(file: string, args: string[], options: NodeChildProcessExecOptions, callback: Function): child_process.ChildProcess; + /** + * Read data from text editor. + */ + readEditor(options: any, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + readEditor(callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + /** + * Set effects based on two events and attributes. + */ + setEffects(el: BlessedElement, fel: BlessedElement, over: any, out: any, effects: any, temp: any): void; + /** + * Insert a line into the screen (using csr: this bypasses the output buffer). + */ + insertLine(n: number, y: number, top: number, bottom: number): void; + /** + * Delete a line from the screen (using csr: this bypasses the output buffer). + */ + deleteLine(n: number, y: number, top: number, bottom: number): void; + /** + * Insert a line at the bottom of the screen. + */ + insertBottom(top: number, bottom: number): void; + /** + * Insert a line at the top of the screen. + */ + insertTop(top: number, bottom: number): void; + /** + * Delete a line at the bottom of the screen. + */ + deleteBottom(top: number, bottom: number): void; + /** + * Delete a line at the top of the screen. + */ + deleteTop(top: number, bottom: number): void; + /** + * Enable mouse events for the screen and optionally an element (automatically called when a form of + * on('mouse') is bound). + */ + enableMouse(el: BlessedElement): void; + enableMouse(): void; + /** + * Enable keypress events for the screen and optionally an element (automatically called when a form of + * on('keypress') is bound). + */ + enableKeys(el: BlessedElement): void; + enableKeys(): void; + /** + * Enable key and mouse events. Calls bot enableMouse and enableKeys. + */ + enableInput(el: BlessedElement): void; + enableInput(): void; + /** + * Attempt to copy text to clipboard using iTerm2's proprietary sequence. Returns true if successful. + */ + copyToClipboard(text: string): void; + /** + * Attempt to change cursor shape. Will not work in all terminals (see artificial cursors for a solution + * to this). Returns true if successful. + */ + cursorShape(shape: boolean, blink: boolean): any; + /** + * Attempt to change cursor color. Returns true if successful. + */ + cursorColor(color: string): void; + /** + * Attempt to reset cursor. Returns true if successful. + */ + cursorReset(): void; + /** + * Take an SGR screenshot of the screen within the region. Returns a string containing only + * characters and SGR codes. Can be displayed by simply echoing it in a terminal. + */ + screenshot(xi: number, xl: number, yi: number, yl: number): string; + screenshot(): void; + /** + * Destroy the screen object and remove it from the global list. Also remove all global events relevant + * to the screen object. If all screen objects are destroyed, the node process is essentially reset + * to its initial state. + */ + destroy(): void; + /** + * Reset the terminal to term. Reloads terminfo. + */ + setTerminal(term: string): void; + } + + export interface Padding { + left?: number; + right?: number; + top?: number; + bottom?: number; + } + + export class PositionCoords { + xi: number; + xl: number; + yi: number; + yl: number; + } + + export interface Position { + left: number | string; + right: number | string; + top: number | string; + bottom: number | string; + } + + export interface Border { + /** + * Type of border (line or bg). bg by default. + */ + type?: "line" | "bg"; + /** + * Character to use if bg type, default is space. + */ + ch?: string; + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg?: number; + fg?: number; + /** + * Border attributes. + */ + bold?: string; + underline?: string; + } + + export interface ElementOptions extends INodeOptions { + tags?: boolean; + + fg?: string; + bg?: string; + bold?: string; + underline?: string; + + style?: any; + /** + * Border object, see below. + */ + border?: Border | "line" | "bg"; + /** + * Element's text content. + */ + content?: string; + /** + * Element is clickable. + */ + clickable?: boolean; + /** + * Element is focusable and can receive key input. + */ + input?: boolean; + keyable?: boolean; + /** + * Element is focused. + */ + focused?: BlessedElement; + /** + * Whether the element is hidden. + */ + hidden?: boolean; + /** + * A simple text label for the element. + */ + label?: string; + /** + * A floating text label for the element which appears on mouseover. + */ + hoverText?: string; + /** + * Text alignment: left, center, or right. + */ + align?: "left" | "center" | "right"; + /** + * Vertical text alignment: top, middle, or bottom. + */ + valign?: "top" | "middle" | "bottom"; + /** + * Shrink/flex/grow to content and child elements. Width/height during render. + */ + shrink?: boolean; + /** + * Amount of padding on the inside of the element. Can be a number or an object containing + * the properties: left, right, top, and bottom. + */ + padding?: number | Padding; + + top?: Types.TTopLeft; + left?: Types.TTopLeft; + right?: Types.TPosition; + bottom?: Types.TPosition; + + /** + * Width/height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). + * Percentages can also have offsets (50%+1, 50%-1). + */ + width?: number | string; + /** + * Offsets of the element relative to its parent. Can be a number, percentage (0-100%), or + * keyword (center). right and bottom do not accept keywords. Percentages can also have + * offsets (50%+1, 50%-1). + */ + height?: number | string; + /** + * Can contain the above options. + */ + position?: Position; + /** + * Whether the element is scrollable or not. + */ + scrollable?: boolean; + /** + * Background character (default is whitespace ). + */ + ch?: string; + /** + * Allow the element to be dragged with the mouse. + */ + draggable?: boolean; + /** + * Draw a translucent offset shadow behind the element. + */ + shadow?: boolean; + } + + export interface Coords { + xl: number; + xi: number; + yl: number; + yi: number; + base: number; + _contentEnd: {x: number; y: number;}; + notop: Types.TTopLeft; + noleft: Types.TTopLeft; + noright: Types.TPosition; + nobot: Types.TPosition; + } + + export interface LabelOptions { + text: string; + side: Types.TAlign; + } + + // TODO: scrollable - Note: If the scrollable option is enabled, Element inherits all methods from ScrollableBox. + export abstract class BlessedElement extends NodeWithEvents implements IHasOptions { + constructor(opts: ElementOptions); + + // ** properties ** // + + /** + * Original options object. + */ + options: ElementOptions; + /** + * Name of the element. Useful for form submission. + */ + name: string; + /** + * Border object. + */ + border: Border; + + style: any; + position: Position; + content: string; + hidden: boolean; + visible: boolean; + detached: boolean; + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg: number; + fg: number; + /** + * Border attributes. + */ + bold: string; + underline: string; + /** + * Calculated width. + */ + width: number | string; + /** + * Calculated height. + */ + height: number | string; + /** + * Calculated relative top offset.*/ + top: Types.TTopLeft; + /** + * Calculated relative left offset. + */ + left: Types.TTopLeft; + /** + * Calculated relative right offset. + */ + right: Types.TPosition; + /** + * Calculated relative bottom offset. + */ + bottom: Types.TPosition; + /** + * Calculated absolute top offset. + */ + atop: Types.TTopLeft; + /** + * Calculated absolute left offset. + */ + aleft: Types.TTopLeft; + /** + * Calculated absolute right offset. + */ + aright: Types.TPosition; + /** + * Calculated absolute bottom offset. + */ + abottom: Types.TPosition; + + /** + * Whether the element is draggable. Set to true to allow dragging. + */ + draggable: boolean; + + itop: Types.TTopLeft; + ileft: Types.TTopLeft; + iheight: Types.TPosition; + iwidth: Types.TPosition; + + /** + * Calculated relative top offset. + */ + rtop: Types.TTopLeft; + /** + * Calculated relative left offset. + */ + rleft: Types.TTopLeft; + /** + * Calculated relative right offset. + */ + rright: Types.TPosition; + /** + * Calculated relative bottom offset. + */ + rbottom: Types.TPosition; + + lpos: PositionCoords; + + // ** methods ** // + + /** + * Write content and children to the screen buffer. + */ + render(): Coords; + /** + * Hide element.*/ + hide(): void; + /** + * Show element. + */ + show(): void; + /** + * Toggle hidden/shown. + */ + toggle(): void; + /** + * Focus element. + */ + focus(): void; + /** + * Same asel.on('screen', ...) except this will automatically keep track of which listeners + * are bound to the screen object. For use with removeScreenEvent(), free(), and destroy(). + */ + onScreenEvent(type: string, handler: Function): void; + /** + * Same asel.removeListener('screen', ...) except this will automatically keep track of which + * listeners are bound to the screen object. For use with onScreenEvent(), free(), and destroy(). + */ + removeScreenEvent(type: string, handler: Function): void; + /** + * Free up the element. Automatically unbind all events that may have been bound to the screen + * object. This prevents memory leaks. For use with onScreenEvent(), removeScreenEvent(), + * and destroy(). + */ + free(): void; + /** + * Same as the detach() method, except this will automatically call free() and unbind any screen + * events to prevent memory leaks. for use with onScreenEvent(), removeScreenEvent(), and free(). + */ + destroy(): void; + /** + * Set the z-index of the element (changes rendering order). + */ + setIndex(z: number): void; + /** + * Put the element in front of its siblings.*/ + setFront(): void; + /** + * Put the element in back of its siblings. + */ + setBack(): void; + /** + * text/options - Set the label text for the top-left corner. Example options: {text:'foo',side:'left'} + */ + setLabel(arg: string | LabelOptions): void; + /** + * Remove the label completely. + */ + removeLabel(): any; + /** + * text/options - Set a hover text box to follow the cursor. Similar to the "title" DOM attribute + * in the browser. Example options: {text:'foo'} + */ + setHover(arg: string | LabelOptions): void; + /** + * Remove the hover label completely. + */ + removeHover(): void; + /** + * Enable mouse events for the element (automatically called when a form of on('mouse') is bound). + */ + enableMouse(): void; + /** + * Enable keypress events for the element (automatically called when a form of on('keypress') is bound). + */ + enableKeys(): void; + /** + * Enable key and mouse events. Calls bot enableMouse and enableKeys. + */ + enableInput(): void; + /** + * Enable dragging of the element. + */ + enableDrag(): void; + /** + * Disable dragging of the element. + */ + disableDrag(): void; + /** + * Take an SGR screenshot of the screen within the region. Returns a string containing only + * characters and SGR codes. Can be displayed by simply echoing it in a terminal. + */ + screenshot(xi: number, xl: number, yi: number, yl: number): string; + screenshot(): void; + + /* + Content Methods + + Methods for dealing with text content, line by line. Useful for writing a text editor, + irc client, etc. + + Note: All of these methods deal with pre-aligned, pre-wrapped text. If you use deleteTop() + on a box with a wrapped line at the top, it may remove 3-4 "real" lines (rows) depending + on how long the original line was. + + The lines parameter can be a string or an array of strings. The line parameter must + be a string. + */ + + /** + * Set the content. Note: When text is input, it will be stripped of all non-SGR + * escape codes, tabs will be replaced with 8 spaces, and tags will be replaced + * with SGR codes (if enabled). + */ + setContent(text: string): void; + /** + * Return content, slightly different from el.content. Assume the above formatting. + */ + getContent(): string; + /** + * Similar to setContent, but ignore tags and remove escape codes. + */ + setText(text: string): void; + /** + * Similar to getContent, but return content with tags and escape codes removed. + */ + getText(): string; + /** + * Insert a line into the box's content. + */ + insertLine(i: number, lines: string | string[]): void; + /** + * Delete a line from the box's content. + */ + deleteLine(i: number): void; + /** + * Get a line from the box's content. + */ + getLine(i: number): string; + /** + * Get a line from the box's content from the visible top. + */ + getBaseLine(i: number): string; + /** + * Set a line in the box's content. + */ + setLine(i: number, line: string | string[]): void; + /** + * Set a line in the box's content from the visible top. + */ + setBaseLine(i: number, line: string | string[]): void; + /** + * Clear a line from the box's content. + */ + clearLine(i: number): void; + /** + * Clear a line from the box's content from the visible top. + */ + clearBaseLine(i: number): void; + /** + * Insert a line at the top of the box. + */ + insertTop(lines: string | string[]): void; + /** + * Insert a line at the bottom of the box. + */ + insertBottom(lines: string | string[]): void; + /** + * Delete a line at the top of the box. + */ + deleteTop(): void; + /** + * Delete a line at the bottom of the box. + */ + deleteBottom(): void; + /** + * Unshift a line onto the top of the content. + */ + unshiftLine(lines: string | string[]): void; + /** + * Shift a line off the top of the content. + */ + shiftLine(i: number): void; + /** + * Push a line onto the bottom of the content. + */ + pushLine(lines: string | string[]): void; + /** + * Pop a line off the bottom of the content. + */ + popLine(i: number): string; + /** + * An array containing the content lines. + */ + getLines(): string[]; + /** + * An array containing the lines as they are displayed on the screen. + */ + getScreenLines(): string[]; + /** + * Get a string's displayed width, taking into account double-width, surrogate pairs, + * combining characters, tags, and SGR escape codes. + */ + strWidth(text: string): string; + + // ** events ** // + } + + export interface ScrollableBoxOptions extends ElementOptions { + /** + * A limit to the childBase. Default is Infinity. + */ + baseLimit?: number; + /** + * A option which causes the ignoring of childOffset. This in turn causes the + * childBase to change every time the element is scrolled. + */ + alwaysScroll?: boolean; + /** + * Object enabling a scrollbar. + * Style of the scrollbar track if present (takes regular style options). + */ + scrollbar?: { style?: any; track?: any; ch?: string; } + } + + export interface ScrollableTextOptions extends ScrollableBoxOptions { + /** + * Whether to enable automatic mouse support for this element. + * Use pre-defined mouse events (right-click for editor). + */ + mouse?: boolean | (() => void); + /** + * Use pre-defined keys (i or enter for insert, e for editor, C-e for editor while inserting). + */ + keys?: string | string[] | boolean; + /** + * Use vi keys with the keys option. + */ + vi?: boolean; + } + + export interface BoxOptions extends ScrollableTextOptions { + bindings?: any; + } + + /** + * DEPRECATED - Use Box with the scrollable option instead. A box with scrollable content. + */ + export class ScrollableBoxElement extends BlessedElement { + /** + * The offset of the top of the scroll content. + */ + childBase: number; + /** + * The offset of the chosen item/line. + */ + childOffset: number; + + /** + * Scroll the content by a relative offset. + */ + scroll(offset: number, always?: boolean): void; + /** + * Scroll the content to an absolute index. + */ + scrollTo(index: number): void; + /** + * Same as scrollTo. + */ + setScroll(index: number): void; + /** + * Set the current scroll index in percentage (0-100). + */ + setScrollPerc(perc: number): void; + /** + * Get the current scroll index in lines. + */ + getScroll(): void; + /** + * Get the actual height of the scrolling area. + */ + getScrollHeight(): void; + /** + * Get the current scroll index in percentage. + */ + getScrollPerc(): void; + /** + * Reset the scroll index to its initial state. + */ + resetScroll(): void; + + on(event: string, listener: Function): this; + /** + * Received when the element is scrolled. + */ + on(event: "scroll", callback: () => void): this; + } + + /** + * DEPRECATED - Use Box with the scrollable and alwaysScroll options instead. + * A scrollable text box which can display and scroll text, as well as handle + * pre-existing newlines and escape codes. + */ + export class ScrollableTextElement extends ScrollableBoxElement { + } + + /** + * A box element which draws a simple box containing content or other elements. + */ + export class BoxElement extends ScrollableTextElement implements IHasOptions { + constructor(opts: BoxOptions); + + /** + * Original options object. + */ + options: BoxOptions; + } + + export interface TextOptions extends ElementOptions { + /** + * Fill the entire line with chosen bg until parent bg ends, even if there + * is not enough text to fill the entire width. + */ + fill?: boolean; + /** + * Text alignment: left, center, or right. + */ + align?: Types.TAlign; + } + + /** + * An element similar to Box, but geared towards rendering simple text elements. + */ + export class TextElement extends BlessedElement implements IHasOptions { + constructor(opts: TextOptions); + + /** + * Original options object. + */ + options: TextOptions; + } + + /** + * A simple line which can be line or bg styled. + */ + export interface LineOptions extends BoxOptions { + /** + * Can be vertical or horizontal. + */ + orientation?: "vertical" | "horizontal"; + /** + * Treated the same as a border object. (attributes can be contained in style). + */ + type?: string; + bg?: string; + fg?: string; + ch?: string; + } + + /** + * A simple line which can be line or bg styled. + */ + export class LineElement extends BoxElement implements IHasOptions { + constructor(opts: LineOptions); + + /** + * Original options object. + */ + options: LineOptions; + } + + export interface BigTextOptions extends BoxOptions { + /** + * bdf->json font file to use (see ttystudio for instructions on compiling BDFs to JSON). + */ + font?: string; + /** + * bdf->json bold font file to use (see ttystudio for instructions on compiling BDFs to JSON). + */ + fontBold?: string; + /** + * foreground character. (default: ' ') + */ + fch?: string; + } + + /** + * A box which can render content drawn as 8x14 cell characters using the terminus font. + */ + export class BigTextElement extends BoxElement implements IHasOptions { + constructor(opts: BigTextOptions); + + /** + * Original options object. + */ + options: BigTextOptions; + } + + export interface ListElementStyle { + selected?: any; + item?: any; + } + + export interface ListOptions extends BoxOptions { + /** + * Style for a selected item. Style for an unselected item. + */ + style?: TStyle; + /** + * An array of strings which become the list's items. + */ + items?: string[]; + /** + * A function that is called when vi mode is enabled and the key / is pressed. This function accepts a + * callback function which should be called with the search string. The search string is then used to + * jump to an item that is found in items. + */ + search?: () => void; + /** + * Whether the list is interactive and can have items selected (Default: true). + */ + interactive?: boolean; + /** + * Whether to automatically override tags and invert fg of item when selected (Default: true). + */ + invertSelected?: boolean; + } + + export class ListElement extends BoxElement implements IHasOptions> { + constructor(opts: ListOptions); + + /** + * Original options object. + */ + options: ListOptions; + + /** + * Add an item based on a string. + */ + add(text: string): void; + /** + * Add an item based on a string. + */ + addItem(text: string): void; + /** + * Removes an item from the list. Child can be an element, index, or string. + */ + removeItem(child: BlessedElement): BlessedElement; + /** + * Push an item onto the list. + * */ + pushItem(child: BlessedElement): number; + /** + * Pop an item off the list. + * */ + popItem(): BlessedElement; + /** + * Unshift an item onto the list. + */ + unshiftItem(child: BlessedElement): number; + /** + * Shift an item off the list. + * */ + shiftItem(): BlessedElement; + /** + * Inserts an item to the list. Child can be an element, index, or string. + */ + insertItem(i: number, child: BlessedElement): void; + /** + * Returns the item element. Child can be an element, index, or string. + */ + getItem(child: BlessedElement): BlessedElement; + /** + * Set item to content. + */ + setItem(child: BlessedElement, content: BlessedElement | string): void; + /** + * Remove and insert items to the list. + * */ + spliceItem(i: number, n: number, ...items: BlessedElement[]): void; + /** + * Clears all items from the list. + * */ + clearItems(): void; + /** + * Sets the list items to multiple strings. + */ + setItems(items: BlessedElement[]): void; + /** + * Returns the item index from the list. Child can be an element, index, or string. + */ + getItemIndex(child: BlessedElement): number; + /** + * Select an index of an item. + * */ + select(index: number): void; + /** + * Select item based on current offset. + * */ + move(offset: number): void; + /** + * Select item above selected. + * */ + up(amount: number): void; + /** + * Select item below selected. + */ + down(amount: number): void; + /** + * Show/focus list and pick an item. The callback is executed with the result. + */ + pick(callback: () => void): void; + /** + * Find an item based on its text content. + */ + fuzzyFind(arg: string | RegExp | (() => void)): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Received when an item is selected. + */ + on(event: "select", callback: (item: BoxElement, index: number) => void): this; + /** + * List was canceled (when esc is pressed with the keys option). + */ + on(event: "cancel", callback: () => void): this; + /** + * Either a select or a cancel event was received. + */ + on(event: "action", callback: () => void): this; + + on(event: "create item", callback: () => void): this; + on(event: "add item", callback: () => void): this; + on(event: "remove item", callback: () => void): this; + on(event: "insert item", callback: () => void): this; + on(event: "set items", callback: () => void): this; + on(event: "select item", callback: (item: BlessedElement, index: number) => void): this; + } + + export interface FileManagerOptions extends ListOptions { + /** + * Current working directory. + */ + cwd?: string; + } + + export class FileManagerElement extends ListElement implements IHasOptions { + constructor(opts: FileManagerOptions); + + /** + * Original options object. + */ + options: FileManagerOptions; + /** + * Current working directory. + */ + cwd: string; + + /** + * Refresh the file list (perform a readdir on cwd and update the list items). + */ + refresh(cwd:string, callback: () => void): void; + refresh(callback: () => void): void; + refresh(): void; + /** + * Pick a single file and return the path in the callback. + */ + pick(cwd:string, callback: () => void): void; + pick(callback: () => void): void; + /** + * Reset back to original cwd. + */ + reset(cwd:string, callback: () => void): void; + reset(callback: () => void): void; + reset(): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Received when an item is selected. + */ + on(event: "cd", callback: (file: string, cwd: string) => void): this; + /** + * Received when an item is selected. + */ + on(event: "file", callback: (file: string) => void): this; + + on(event: "error", callback: (err: any, file: string) => void): this; + on(event: "refresh", callback: () => void): this; + } + + export interface StyleListTable extends ListElementStyle { + /** + * Header style. + */ + header?: any; + /** + * Cell style. + */ + cell?: any; + } + + export interface ListTableOptions extends ListOptions { + /** + * Array of array of strings representing rows. + */ + rows?: string[]; + data?: string[][]; + /** + * Spaces to attempt to pad on the sides of each cell. 2 by default: one space on each side + * (only useful if the width is shrunken). + */ + pad?: number; + /** + * Do not draw inner cells. + */ + noCellBorders?: boolean; + + style?: StyleListTable; + } + + export class ListTableElement extends ListElement implements IHasOptions { + constructor(opts: ListTableOptions); + + /** + * Original options object. + */ + options: ListTableOptions; + + /** + * Set rows in table. Array of arrays of strings. + * @example: + * + * table.setData([ + [ 'Animals', 'Foods' ], + [ 'Elephant', 'Apple' ], + [ 'Bird', 'Orange' ] + ]); + */ + setRows(rows: string[][]): void; + /** + * Set rows in table. Array of arrays of strings. + * @example: + * + * table.setData([ + [ 'Animals', 'Foods' ], + [ 'Elephant', 'Apple' ], + [ 'Bird', 'Orange' ] + ]); + */ + setData(rows: string[][]): void; + } + + export interface ListbarOptions extends BoxOptions { + style?: ListElementStyle; + /** + * Set buttons using an object with keys as titles of buttons, containing of objects + * containing keys of keys and callback. + */ + commands: Types.ListbarCommand[]; + items: Types.ListbarCommand[]; + /** + * Automatically bind list buttons to keys 0-9. + */ + autoCommandKeys: boolean; + } + + export class ListbarElement extends BoxElement implements IHasOptions { + constructor(opts: ListbarOptions); + + /** + * Original options object. + */ + options: ListbarOptions; + + /** + * Set commands (see commands option above). + */ + setItems(commands: Types.ListbarCommand[]): void; + /** + * Append an item to the bar. + */ + add(item: Types.ListbarCommand, callback: () => void): void; + /** + * Append an item to the bar. + */ + addItem(item: Types.ListbarCommand, callback: () => void): void; + /** + * Append an item to the bar. + */ + appendItem(item: Types.ListbarCommand, callback: () => void): void; + /** + * Select an item on the bar. + */ + select(offset: number): void; + /** + * Remove item from the bar. + */ + removeItem(child: BlessedElement): void; + /** + * Move relatively across the bar. + */ + move(offset: number): void; + /** + * Move left relatively across the bar. + */ + moveLeft(offset: number): void; + /** + * Move right relatively across the bar. + */ + moveRight(offset: number): void; + /** + * Select button and execute its callback. + */ + selectTab(index: number): void; + + // ** events ** // + + on(event: string, listener: Function): this; + + on(event: "set items", callback: () => void): this; + on(event: "remove item", callback: () => void): this; + on(event: "select tab", callback: () => void): this; + } + + export interface FormOptions extends BoxOptions { + /** + * Allow default keys (tab, vi keys, enter). + */ + keys?: any; + /** + * Allow vi keys. + */ + vi?: boolean; + } + + export class FormElement extends BoxElement implements IHasOptions { + constructor(opts: FormOptions); + + /** + * Original options object. + */ + options: FormOptions; + /** + * Last submitted data. + */ + submission: TFormData; + + /** + * Focus next form element. + */ + focusNext(): void; + /** + * Focus previous form element. + */ + focusPrevious(): void; + /** + * Submit the form. + */ + submit(): void; + /** + * Discard the form. + */ + cancel(): void; + /** + * Clear the form. + */ + reset(): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Form is submitted. Receives a data object. + */ + on(event: "submit", callback: (out: TFormData) => void): this; + /** + * Form is discarded. + */ + on(event: "cancel", callback: () => void): this; + /** + * Form is cleared. + */ + on(event: "reset", callback: () => void): this; + } + + export interface InputOptions extends BoxOptions { } + + export abstract class InputElement extends BoxElement { + constructor(opts: InputOptions); + } + + /** + * A box which allows multiline text input. + */ + export interface TextareaOptions extends InputOptions { + /** + * Call readInput() when the element is focused. Automatically unfocus. + */ + inputOnFocus?: boolean; + } + + export class TextareaElement extends InputElement implements IHasOptions { + constructor(opts: TextareaOptions); + + /** + * Original options object. + */ + options: TextareaOptions; + + /** + * The input text. read-only. + */ + value: string; + + /** + * Submit the textarea (emits submit). + */ + submit(): void; + /** + * Cancel the textarea (emits cancel). + */ + cancel(): void; + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + readInput(callback?: (err: any, value?: string) => void): void; + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + input(callback: (err: any, value?: string) => void): void; + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + setInput(callback: (err: any, value?: string) => void): void; + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + readEditor(callback: (err: any, value?: string) => void): void; + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + editor(callback: (err: any, value?: string) => void): void; + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + setEditor(callback: (err: any, value?: string) => void): void; + /** + * The same as this.value, for now. + */ + getValue(): string; + /** + * Clear input. + */ + clearValue(): void; + /** + * Set value. + */ + setValue(text: string): void; + + // ** events ** // + + on(event: string, listener: Function): this; + + on(event: "error", callback: (err: any) => void): this; + + /** + * Value is submitted (enter). + */ + on(event: "submit", callback: (value: any) => void): this; + /** + * Value is discared (escape). + */ + on(event: "cancel", callback: (value: any) => void): this; + /** + * Either submit or cancel. + */ + on(event: "action", callback: (value: any) => void): this; + } + + export interface TextboxOptions extends TextareaOptions { + /** + * Completely hide text. + */ + secret?: boolean; + /** + * Replace text with asterisks (*). + */ + censor?: boolean; + } + + export class TextboxElement extends TextareaElement implements IHasOptions { + constructor(opts: TextboxOptions); + + /** + * Original options object. + */ + options: TextboxOptions; + + /** + * Completely hide text. + */ + secret: boolean; + /** + * Replace text with asterisks (*). + */ + censor: boolean; + } + + export interface ButtonOptions extends BoxOptions { } + + export class ButtonElement extends InputElement implements IHasOptions { + constructor(opts: ButtonOptions); + + /** + * Original options object. + */ + options: ButtonOptions; + + /** + * Press button. Emits press. + */ + press(): void; + + on(event: string, listener: Function): this; + + on(event: "press", callback: () => void): this; + } + + export interface CheckboxOptions extends BoxOptions { + /** + * whether the element is checked or not. + * */ + checked?: boolean; + /** + * enable mouse support. + * */ + mouse?: boolean; + } + + /** + * A checkbox which can be used in a form element. + * */ + export class CheckboxElement extends InputElement implements IHasOptions { + constructor(options?: CheckboxOptions); + + /** + * Original options object. + */ + options: CheckboxOptions; + + /** + * the text next to the checkbox (do not use setcontent, use `check.text = ''`). + * */ + text: string; + /** + * whether the element is checked or not. + * */ + checked: boolean; + /** + * same as `checked`. + * */ + value: boolean; + + /** + * check the element. + * */ + check(): void; + /** + * uncheck the element. + * */ + uncheck(): void; + /** + * toggle checked state. + * */ + toggle(): void; + } + + export interface RadioSetOptions extends BoxOptions { } + + /** + * An element wrapping RadioButtons. RadioButtons within this element will be mutually exclusive + * with each other. + * */ + export abstract class RadioSetElement extends BoxElement { + constructor(opts: RadioSetOptions); + } + + export interface RadioButtonOptions extends BoxOptions { } + + /** + * A radio button which can be used in a form element. + */ + export abstract class RadioButtonElement extends CheckboxElement { + constructor(opts: RadioButtonOptions); + } + + export interface PromptOptions extends BoxOptions { } + + /** + * A prompt box containing a text input, okay, and cancel buttons (automatically hidden). + */ + export class PromptElement extends BoxElement implements IHasOptions { + constructor(opts: PromptOptions); + + options: PromptOptions; + + /** + * Show the prompt and wait for the result of the textbox. Set text and initial value. + */ + input(text: string, value: string, callback: (err: any, value: string) => void): void; + setInput(text: string, value: string, callback: (err: any, value: string) => void): void; + readInput(text: string, value: string, callback: (err: any, value: string) => void): void; + } + + export interface QuestionOptions extends BoxOptions { } + + /** + * A question box containing okay and cancel buttons (automatically hidden). + */ + export class QuestionElement extends BoxElement implements IHasOptions { + constructor(opts: QuestionOptions); + + options: QuestionOptions; + + /** + * Ask a question. callback will yield the result. + */ + ask(question: string, callback: (err: any, value: string) => void): void; + } + + export interface MessageOptions extends BoxOptions { } + + /** + * A box containing a message to be displayed (automatically hidden). + */ + export class MessageElement extends BoxElement implements IHasOptions { + constructor(opts: MessageOptions); + + options: MessageOptions; + + /** + * Display a message for a time (default is 3 seconds). Set time to 0 for a perpetual message that is dismissed on keypress. + */ + log(text: string, time: number, callback: (err: any) => void): void; + log(text: string, callback: (err: any) => void): void; + display(text: string, time: number, callback: (err: any) => void): void; + display(text: string, callback: (err: any) => void): void; + + /** + * Display an error in the same way. + */ + error(text: string, time: number, callback: () => void): void; + error(text: string, callback: () => void): void; + } + + export interface LoadingOptions extends BoxOptions { } + + /** + * A box with a spinning line to denote loading (automatically hidden). + */ + export class LoadingElement extends BoxElement implements IHasOptions { + constructor(opts: LoadingOptions); + + options: LoadingOptions; + + /** + * Display the loading box with a message. Will lock keys until stop is called. + */ + load(text: string): void; + /** + * Hide loading box. Unlock keys. + */ + stop(): void; + } + + export interface ProgressBarOptions extends BoxOptions { + /** + * can be `horizontal` or `vertical`. + * */ + orientation: string; + /** + * the character to fill the bar with (default is space). + * */ + pch: string; + /** + * the amount filled (0 - 100). + * */ + filled: number; + /** + * same as `filled`. + * */ + value: number; + /** + * enable key support. + * */ + keys: boolean; + /** + * enable mouse support. + * */ + mouse: boolean; + } + + /** + * A progress bar allowing various styles. This can also be used as a form input. + */ + export class ProgressBarElement extends InputElement implements IHasOptions { + constructor(options?: ProgressBarOptions); + + options: ProgressBarOptions; + + /** + * progress the bar by a fill amount. + * */ + progress(amount:number): void; + /** + * set progress to specific amount. + * */ + setProgress(amount:number): void; + /** + * reset the bar. + * */ + reset(): void; + + on(event: string, listener: Function): this; + /** + * Bar was reset. + */ + on(event: "reset", callback: () => void): this; + /** + * Bar has completely filled. + */ + on(event: "complete", callback: () => void): this; + } + + export interface LogOptions extends ScrollableTextOptions { + /** + * amount of scrollback allowed. default: Infinity. + * */ + scrollback?: number; + /** + * scroll to bottom on input even if the user has scrolled up. default: false. + * */ + scrollOnInput?: boolean; + } + + /** + * A log permanently scrolled to the bottom. + * */ + export class Log extends ScrollableTextElement implements IHasOptions { + constructor(options?: LogOptions); + + options: LogOptions; + + /** + * amount of scrollback allowed. default: Infinity. + * */ + scrollback: number; + /** + * scroll to bottom on input even if the user has scrolled up. default: false. + * */ + scrollOnInput: boolean; + + /** + * add a log line. + * */ + log(text:string): void; + /** + * add a log line. + * */ + add(text:string): void; + } + + export interface TableOptions extends BoxOptions { + /** + * array of array of strings representing rows (same as `data`). + * */ + rows?: string[][]; + /** + * array of array of strings representing rows (same as `rows`). + * */ + data?: string[][]; + /** + * spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). + * */ + pad?: number; + /** + * do not draw inner cells. + * */ + noCellBorders?: boolean; + /** + * fill cell borders with the adjacent background color. + * */ + fillCellBorders?: boolean; + } + + /** + * A stylized table of text elements. + * */ + export class TableElement extends BoxElement implements IHasOptions { + constructor(opts: TableOptions); + + options: TableOptions; + + /** + * set rows in table. array of arrays of strings. + * */ + setData(rows: string[][]): void; + /** + * set rows in table. array of arrays of strings. + * */ + setRows(rows: string[][]): void; + } + + export interface TerminalOptions extends BoxOptions { + /** + * handler for input data. + * */ + handler?: (userInput:Buffer) => void; + /** + * name of shell. $SHELL by default. + * */ + shell?:string; + /** + * args for shell. + * */ + args?:any; + /** + * can be line, underline, and block. + * */ + cursor?: 'line'|'underline'|'block'; + + terminal?: string; + + /** + * Object for process env. + */ + env?: any; + } + + export class TerminalElement extends BoxElement implements IHasOptions { + constructor(opts: TerminalOptions); + + options: TerminalOptions; + + /** + * reference to the headless term.js terminal. + * */ + term: any; + /** + * reference to the pty.js pseudo terminal. + * */ + pty: any; + + /** + * write data to the terminal. + * */ + write(data:string): void; + + /** + * nearly identical to `element.screenshot`, however, the specified region includes the terminal's _entire_ scrollback, rather than just what is visible on the screen. + * */ + screenshot(xi?:number, xl?:number, yi?:number, yl?:number): string; + } + + export interface ImageOptions extends BoxOptions { + /** + * path to image. + * */ + file: string; + /** + * path to w3mimgdisplay. if a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. + * */ + type: "ansi" | "overlay" | "w3m"; + } + + /** + * Display an image in the terminal (jpeg, png, gif) using w3mimgdisplay. Requires w3m to be installed. X11 required: works in xterm, urxvt, and possibly other terminals. + * */ + export class ImageElement extends BoxElement implements IHasOptions { + constructor(options?: ImageOptions); + + options: ImageOptions; + } + + export interface ANSIImageOptions extends BoxOptions { + /** + * URL or path to PNG/GIF file. Can also be a buffer. + * */ + file: string; + /** + * Scale cellmap down (0-1.0) from its original pixel width/height (Default: 1.0). + * */ + scale: number; + + /** + * This differs from other element's width or height in that only one of them is needed: blessed will maintain the aspect ratio of the image as it scales down to the proper number of cells. NOTE: PNG/GIF's are always automatically shrunken to size (based on scale) if a width or height is not given. + * */ + width: number | string; + height: number | string; + + /** + * Add various "density" ASCII characters over the rendering to give the image more detail, similar to libcaca/libcucul (the library mplayer uses to display videos in the terminal). + */ + ascii: string; + + /** + * Whether to animate if the image is an APNG/animating GIF. If false, only display the first frame or IDAT (Default: true). + */ + animate: boolean; + + /** + * Set the speed of animation. Slower: 0.0-1.0. Faster: 1-1000. It cannot go faster than 1 frame per millisecond, so 1000 is the fastest. (Default: 1.0) + */ + speed: number; + + /** + * mem or cpu. If optimizing for memory, animation frames will be rendered to bitmaps as the animation plays, using less memory. Optimizing for cpu will precompile all bitmaps beforehand, which may be faster, but might also OOM the process on large images. (Default: mem). + */ + optimization: "mem" | "cpu"; + } + + /** + * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. + * */ + export class ANSIImageElement extends BoxElement implements IHasOptions { + constructor(options?:ANSIImageOptions); + + options: ANSIImageOptions; + + /** + * Image object from the png reader. + */ + img: Types.TImage; + + /** + * set the image in the box to a new path. + * */ + setImage(img: string, callback: () => void): void; + /** + * clear the current image. + * */ + clearImage(callback: () => void): void; + /** + * Play animation if it has been paused or stopped. + */ + play(): void; + /** + * Pause animation. + */ + pause(): void; + /** + * Stop animation. + */ + stop(): void; + } + + export interface OverlayImageOptions extends BoxOptions { + /** + * Path to image. + */ + file: string; + /** + * Render the file as ANSI art instead of using w3m to overlay Internally uses the ANSIImage element. See the ANSIImage element for more information/options. (Default: true). + */ + ansi: boolean; + /** + * Path to w3mimgdisplay. If a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. + */ + w3m: string; + /** + * Whether to search /usr, /bin, and /lib for w3mimgdisplay (Default: true). + */ + search: string; + } + + /** + * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. + * */ + export class OverlayImageElement extends BoxElement implements IHasOptions { + constructor(options?: OverlayImageOptions); + + options: OverlayImageOptions; + + /** + * set the image in the box to a new path. + * */ + setImage(img: string, callback: () => void): void; + /** + * clear the current image. + * */ + clearImage(callback: () => void): void; + /** + * get the size of an image file in pixels. + * */ + imageSize(img:string, callback: () => void): void; + /** + * get the size of the terminal in pixels. + * */ + termSize(callback: () => void): void; + /** + * get the pixel to cell ratio for the terminal. + * */ + getPixelRatio(callback: () => void): void; + } + + export interface VideoOptions extends BoxOptions { + /** + * Video to play. + */ + file: string; + /** + * Start time in seconds. + */ + start: number; + } + + export class VideoElement extends BoxElement implements IHasOptions { + constructor(options?: VideoOptions); + + options: VideoOptions; + + /** + * The terminal element running mplayer or mpv. + */ + tty: any; + } + + export interface LayoutOptions extends ElementOptions { + /** + * A callback which is called right before the children are iterated over to be rendered. Should return an + * iterator callback which is called on each child element: iterator(el, i). + */ + renderer?: () => void; + + /** + * Using the default renderer, it provides two layouts: inline, and grid. inline is the default and will render + * akin to inline-block. grid will create an automatic grid based on element dimensions. The grid cells' + * width and height are always determined by the largest children in the layout. + */ + layout: "inline" | "inline-block" | "grid"; + } + + export class LayoutElement extends BlessedElement implements IHasOptions { + constructor(options?: LayoutOptions); + + options: LayoutOptions; + + /** + * A callback which is called right before the children are iterated over to be rendered. Should return an + * iterator callback which is called on each child element: iterator(el, i). + */ + renderer(coords: PositionCoords): void; + /** + * Check to see if a previous child element has been rendered and is visible on screen. This is only useful + * for checking child elements that have already been attempted to be rendered! see the example below. + */ + isRendered(el: BlessedElement): boolean; + /** + * Get the last rendered and visible child element based on an index. This is useful for basing the position + * of the current child element on the position of the last child element. + */ + getLast(i: number): Element; + /** + * Get the last rendered and visible child element coords based on an index. This is useful for basing the position + * of the current child element on the position of the last child element. See the example below. + */ + getLastCoords(i: number): PositionCoords; + } + + export class Program { + /** + Wrap the given text in terminal formatting codes corresponding to the given attribute + name. The `attr` string can be of the form `red fg` or `52 bg` where `52` is a 0-255 + integer color number. + */ + text (text:string, attr:string): string; + } } - export = Blessed; + export module widget { + export class Element extends Widgets.BlessedElement { } + export class Node extends Widgets.Node { } + export class Screen extends Widgets.Screen { } + + export class Box extends Widgets.BoxElement { } + export class ScrollableBox extends Widgets.ScrollableBoxElement { } + export class ScrollableText extends Widgets.ScrollableTextElement { } + export class Text extends Widgets.BoxElement { } + export class Line extends Widgets.LineElement { } + export class BigText extends Widgets.BigTextElement { } + export class List extends Widgets.ListElement { } + export class FileManager extends Widgets.FileManagerElement { } + export class ListTable extends Widgets.ListTableElement { } + export class ListBar extends Widgets.ListbarElement { } + export class Form extends Widgets.FormElement { } + export class Textarea extends Widgets.TextareaElement { } + export class Button extends Widgets.ButtonElement { } + export class Checkbox extends Widgets.CheckboxElement { } + export class RadioSet extends Widgets.RadioSetElement { } + export class RadioButton extends Widgets.RadioButtonElement { } + + export class Prompt extends Widgets.PromptElement { } + export class question extends Widgets.QuestionElement { } + export class Message extends Widgets.MessageElement { } + export class Loading extends Widgets.LoadingElement { } + + export class ProgressBar extends Widgets.ProgressBarElement { } + export class Terminal extends Widgets.TerminalElement { } + } + + export function screen(options?: Widgets.IScreenOptions): Widgets.Screen; + + export function box(options?: Widgets.BoxOptions): Widgets.BoxElement; + export function text(options?: Widgets.TextOptions): Widgets.TextElement; + export function line(options?: Widgets.LineOptions): Widgets.LineElement; + export function scrollablebox(options?: Widgets.BoxOptions): Widgets.BoxElement; + export function scrollabletext(options?: Widgets.BoxOptions): Widgets.BoxElement; + export function bigtext(options?: Widgets.BigTextOptions): Widgets.BigTextElement; + export function list(options?: Widgets.ListOptions): Widgets.ListElement; + export function filemanager(options?: Widgets.FileManagerOptions): Widgets.FileManagerElement; + export function listtable(options?: Widgets.ListTableOptions): Widgets.ListTableElement; + export function listbar(options?: Widgets.ListbarOptions): Widgets.ListbarElement; + export function form(options?: Widgets.FormOptions): Widgets.FormElement; + export function input(options?: Widgets.InputOptions): Widgets.InputElement; + export function textarea(options?: Widgets.TextareaOptions): Widgets.TextareaElement; + export function textbox(options?: Widgets.TextboxOptions): Widgets.TextboxElement; + export function button(options?: Widgets.ButtonOptions): Widgets.ButtonElement; + export function checkbox(options?: Widgets.CheckboxOptions): Widgets.CheckboxElement; + export function radioset(options?: Widgets.RadioSetOptions): Widgets.RadioSetElement; + export function radiobutton(options?: Widgets.RadioButtonOptions): Widgets.RadioButtonElement; + + export function table(options?: Widgets.TableOptions): Widgets.TableElement; + + export function prompt(options?: Widgets.PromptOptions): Widgets.PromptElement; + export function question(options?: Widgets.QuestionOptions): Widgets.QuestionElement; + export function message(options?: Widgets.MessageOptions): Widgets.MessageElement; + export function loading(options?: Widgets.LoadingOptions): Widgets.LoadingElement; + + export function progressbar(options?: Widgets.ProgressBarOptions): Widgets.ProgressBarElement; + export function terminal(options?: Widgets.TerminalOptions): Widgets.TerminalElement; + + export function layout(options?: Widgets.LayoutOptions): Widgets.LayoutElement; + + export function escape(item: any): any; + export const colors: { + match: (hexColor: string) => string + } } - - - diff --git a/blue-tape/blue-tape-tests.ts b/blue-tape/blue-tape-tests.ts index a01675a1c5..fc931aeed5 100644 --- a/blue-tape/blue-tape-tests.ts +++ b/blue-tape/blue-tape-tests.ts @@ -1,5 +1,5 @@ /// -/// +/// /// import tape = require('blue-tape'); diff --git a/bluebird-retry/bluebird-retry-tests.ts b/bluebird-retry/bluebird-retry-tests.ts index 5d8c32dfcb..e42b5457df 100644 --- a/bluebird-retry/bluebird-retry-tests.ts +++ b/bluebird-retry/bluebird-retry-tests.ts @@ -1,5 +1,5 @@ /// -/// +/// import Promise = require('bluebird'); import retry = require('bluebird-retry'); @@ -32,4 +32,4 @@ var options:retry.Options = { interval: 500 }; -retry(logFail, options); \ No newline at end of file +retry(logFail, options); diff --git a/bluebird-retry/bluebird-retry.d.ts b/bluebird-retry/bluebird-retry.d.ts index 1210bf3b53..b63a3cf131 100644 --- a/bluebird-retry/bluebird-retry.d.ts +++ b/bluebird-retry/bluebird-retry.d.ts @@ -3,7 +3,7 @@ // Definitions by: Pascal Vomhoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "bluebird-retry" { import Promise = require('bluebird'); diff --git a/bluebird/bluebird-2.0-tests.ts b/bluebird/bluebird-2.0-tests.ts new file mode 100644 index 0000000000..3a8ddaa383 --- /dev/null +++ b/bluebird/bluebird-2.0-tests.ts @@ -0,0 +1,1404 @@ +/// + +// Tests by: Bart van der Schoor + +// Note: replicate changes to all overloads in both definition and test file +// Note: keep both static and instance members inline (so similar) + +// Note: try to maintain the ordering and separators, and keep to the pattern + +var obj: Object; +var bool: boolean; +var num: number; +var str: string; +var err: Error; +var x: any; +var f: Function; +var func: Function; +var arr: any[]; +var exp: RegExp; +var anyArr: any[]; +var strArr: string[]; +var numArr: number[]; +var voidVar: void; + +// - - - - - - - - - - - - - - - - - + +var value: any; +var reason: any; +var insanity: any; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +interface Foo { + foo(): string; +} +interface Bar { + bar(): string; +} +interface Baz { + baz(): string; +} + +// - - - - - - - - - - - - - - - - - + +interface StrFooMap { + [key:string]:Foo; +} + +interface StrBarMap { + [key:string]:Bar; +} + +// - - - - - - - - - - - - - - - - - + +interface StrFooArrMap { + [key:string]:Foo[]; +} + +interface StrBarArrMap { + [key:string]:Bar[]; +} + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +var foo: Foo; +var bar: Bar; +var baz: Baz; + +var fooArr: Foo[]; +var barArr: Bar[]; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +var numProm: Promise; +var strProm: Promise; +var anyProm: Promise; +var boolProm: Promise; +var objProm: Promise; +var voidProm: Promise; + +var fooProm: Promise; +var barProm: Promise; +var fooOrBarProm: Promise; +var bazProm: Promise; + +// - - - - - - - - - - - - - - - - - + +var numThen: PromiseLike; +var strThen: PromiseLike; +var anyThen: PromiseLike; +var boolThen: PromiseLike; +var objThen: PromiseLike; +var voidThen: PromiseLike; + +var fooThen: PromiseLike; +var barThen: PromiseLike; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +var numArrProm: Promise; +var strArrProm: Promise; +var anyArrProm: Promise; + +var fooArrProm: Promise; +var barArrProm: Promise; + +// - - - - - - - - - - - - - - - - - + +var numArrThen: PromiseLike; +var strArrThen: PromiseLike; +var anyArrThen: PromiseLike; + +var fooArrThen: PromiseLike; +var barArrThen: PromiseLike; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +var numPromArr: Promise[]; +var strPromArr: Promise[]; +var anyPromArr: Promise[]; + +var fooPromArr: Promise[]; +var barPromArr: Promise[]; + +// - - - - - - - - - - - - - - - - - + +var numThenArr: PromiseLike[]; +var strThenArr: PromiseLike[]; +var anyThenArr: PromiseLike[]; + +var fooThenArr: PromiseLike[]; +var barThenArr: PromiseLike[]; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// booya! +var fooThenArrThen: PromiseLike[]>; +var barThenArrThen: PromiseLike[]>; + +var fooResolver: Promise.Resolver; +var barResolver: Promise.Resolver; + +var fooInspection: Promise.Inspection; +var barInspection: Promise.Inspection; + +var fooInspectionArrProm: Promise[]>; +var barInspectionArrProm: Promise[]>; + +var BlueBird: typeof Promise; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +var nodeCallbackFunc = (callback: (err: any, result: string) => void) => {} +var nodeCallbackFuncErrorOnly = (callback: (err: any) => void) => {} + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooThen = fooProm; +barThen = barProm; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = new Promise((resolve: (value: Foo) => void, reject: (reason: any) => void) => { + if (bool) { + resolve(foo); + } + else { + reject(new Error(str)); + } +}); +fooProm = new Promise((resolve: (value: Foo) => void) => { + if (bool) { + resolve(foo); + } +}); + +// - - - - - - - - - - - - - - - - - - - - - - - + +// needs a hint when used untyped? +fooProm = new Promise((resolve, reject) => { + if (bool) { + resolve(fooThen); + } + else { + reject(new Error(str)); + } +}); +fooProm = new Promise((resolve) => { + resolve(fooThen); +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooResolver.resolve(foo); + +fooResolver.reject(err); + +fooResolver.progress(bar); + +fooResolver.callback = (err: any, value: Foo) => { + +}; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +bool = fooInspection.isFulfilled(); + +bool = fooInspection.isRejected(); + +bool = fooInspection.isPending(); + +foo = fooInspection.value(); + +x = fooInspection.reason(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooProm.then((value: Foo) => { + return bar; +}, (reason: any) => { + return bar; +}, (note: any) => { + return bar; +}); +barProm = fooProm.then((value: Foo) => { + return bar; +}, (reason: any) => { + return bar; +}); +barProm = fooProm.then((value: Foo) => { + return bar; +}, (reason: any) => { + return barProm; +}); +barProm = fooProm.then((value: Foo) => { + return bar; +}, (reason: any) => { + return; +}); +barProm = fooProm.then((value: Foo) => { + return bar; +}, (reason: any) => { + return voidProm; +}); +barProm = fooProm.then((value: Foo) => { + return bar; +}); +barProm = barProm.then((value: Bar) => { + if (value) return value; + var b:Bar; + return Promise.resolve(b); +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.catch((reason: any) => { + return; +}); + +fooProm = fooProm.caught((reason: any) => { + return; +}); +fooProm = fooProm.catch((error: any) => { + return true; +}, (reason: any) => { + return; +}); +fooProm = fooProm.caught((error: any) => { + return true; +}, (reason: any) => { + return; +}); + +fooProm = fooProm.catch((reason: any) => { + return voidProm; +}); + +fooProm = fooProm.caught((reason: any) => { + return voidProm; +}); +fooProm = fooProm.catch((error: any) => { + return true; +}, (reason: any) => { + return voidProm; +}); +fooProm = fooProm.caught((error: any) => { + return true; +}, (reason: any) => { + return voidProm; +}); + +fooProm = fooProm.catch((reason: any) => { + //handle multiple valid return types simultaneously + if (foo === null) { + return; + } else if (!reason) { + return voidProm; + } else if (foo) { + return foo; + } +}); + +fooOrBarProm = fooProm.catch((reason: any) => { + return bar; +}); +fooOrBarProm = fooProm.caught((reason: any) => { + return bar; +}); + +fooOrBarProm = fooProm.catch((error: any) => { + return true; +}, (reason: any) => { + return bar; +}); +fooOrBarProm = fooProm.caught((error: any) => { + return true; +}, (reason: any) => { + return bar; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.catch(Error, (reason: any) => { + return; +}); +fooProm = fooProm.catch(Promise.CancellationError, (reason: any) => { + return; +}); +fooProm = fooProm.caught(Error, (reason: any) => { + return; +}); +fooProm = fooProm.caught(Promise.CancellationError, (reason: any) => { + return; +}); + +fooOrBarProm = fooProm.catch(Error, (reason: any) => { + return bar; +}); +fooOrBarProm = fooProm.catch(Promise.CancellationError, (reason: any) => { + return bar; +}); +fooOrBarProm = fooProm.caught(Error, (reason: any) => { + return bar; +}); +fooOrBarProm = fooProm.caught(Promise.CancellationError, (reason: any) => { + return bar; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooProm.error((reason: any) => { + return bar; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.finally(() => { + // non-Thenable return is ignored + return "foo"; +}); +fooProm = fooProm.finally(() => { + return fooThen; +}); +fooProm = fooProm.finally(() => { + // non-Thenable return is ignored +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.lastly(() => { + // non-Thenable return is ignored + return "foo"; +}); +fooProm = fooProm.lastly(() => { + return fooThen; +}); +fooProm = fooProm.lastly(() => { + // non-Thenable return is ignored +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.bind(obj); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +voidVar = fooProm.done((value: Foo) => { + return bar; +}, (reason: any) => { + return bar; +}, (note: any) => { + +}); +voidVar = fooProm.done((value: Foo) => { + return bar; +}, (reason: any) => { + return bar; +}); +voidVar = fooProm.done((value: Foo) => { + return bar; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +voidVar = fooProm.done((value: Foo) => { + return barThen; +}, (reason: any) => { + return barThen; +}, (note: any) => { + +}); +voidVar = fooProm.done((value: Foo) => { + return barThen; +}, (reason: any) => { + return barThen; +}); +voidVar = fooProm.done((value: Foo) => { + return barThen; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.tap((value: Foo) => { + // non-Thenable return is ignored + return "foo"; +}); +fooProm = fooProm.tap((value: Foo) => { + return fooThen; +}); +fooProm = fooProm.tap((value: Foo) => { + return voidThen; +}); +fooProm = fooProm.tap(() => { + // non-Thenable return is ignored +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.progressed((note: any) => { + return foo; +}); +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.delay(num); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.timeout(num); +fooProm = fooProm.timeout(num, str); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm.nodeify(); +fooProm = fooProm.nodeify((err: any) => { }); +fooProm = fooProm.nodeify((err: any, foo?: Foo) => { }); + +fooProm.nodeify({ spread: true }); +fooProm = fooProm.nodeify((err: any) => { }, { spread: true }); +fooProm = fooProm.nodeify((err: any, foo?: Foo) => { }, { spread: true }); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooProm.fork((value: Foo) => { + return bar; +}, (reason: any) => { + return bar; +}, (note: any) => { + +}); +barProm = fooProm.fork((value: Foo) => { + return bar; +}, (reason: any) => { + return bar; +}); +barProm = fooProm.fork((value: Foo) => { + return bar; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooProm.fork((value: Foo) => { + return barThen; +}, (reason: any) => { + return barThen; +}, (note: any) => { + +}); +barProm = fooProm.fork((value: Foo) => { + return barThen; +}, (reason: any) => { + return barThen; +}); +barProm = fooProm.fork((value: Foo) => { + return barThen; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooProm.cancel(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.cancellable(); +fooProm = fooProm.uncancellable(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +bool = fooProm.isCancellable(); +bool = fooProm.isFulfilled(); +bool = fooProm.isRejected(); +bool = fooProm.isPending(); +bool = fooProm.isResolved(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooInspection = fooProm.inspect(); + +anyProm = fooProm.call(str); +anyProm = fooProm.call(str, 1, 2, 3); + +//TODO enable get() test when implemented +// barProm = fooProm.get(str); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooProm.return(bar); +barProm = fooProm.thenReturn(bar); + +voidProm = fooProm.return(); +voidProm = fooProm.thenReturn(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooProm +fooProm = fooProm.throw(err); +fooProm = fooProm.thenThrow(err); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +str = fooProm.toString(); + +obj = fooProm.toJSON(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooArrProm.spread((one: Foo, two: Bar) => { + return bar; +}, (reason: any) => { + return bar; +}); +barProm = fooArrProm.spread((one: Foo, two: Bar, twotwo: Foo) => { + return bar; +}); + +// - - - - - - - - - - - - - - - - - + +barProm = fooArrProm.spread((one: Foo, two: Bar) => { + return barThen; +}, (reason: any) => { + return barThen; +}); +barProm = fooArrProm.spread((one: Foo, two: Bar, twotwo: Foo) => { + return barThen; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +//TODO fix collection inference + +barArrProm = fooProm.all(); + +objProm = fooProm.props(); + +barInspectionArrProm = fooProm.settle(); + +barProm = fooProm.any(); + +barArrProm = fooProm.some(num); + +barProm = fooProm.race(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +Promise.all([fooProm, barProm]).then(result => { + result[0].foo(); + result[1].bar(); +}); + +Promise.all([fooProm, fooProm]).then(result => { + result[0].foo(); + result[1].foo(); +}); + +Promise.all([fooProm, barProm, bazProm]).then(result => { + result[0].foo(); + result[1].bar(); + result[2].baz(); +}); + +Promise.all([fooProm, barProm, fooProm]).then(result => { + result[0].foo(); + result[1].bar(); + result[2].foo(); +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +//TODO fix collection inference + +barArrProm = fooArrProm.map((item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = fooArrProm.map((item: Foo) => { + return bar; +}); + +barArrProm = fooArrProm.map((item: Foo, index: number, arrayLength: number) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = fooArrProm.map((item: Foo) => { + return bar; +}, { + concurrency: 1 +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barArrProm = fooArrProm.mapSeries((item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = fooArrProm.mapSeries((item: Foo) => { + return bar; +}); + + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooArrProm.reduce((memo: Bar, item: Foo, index: number, arrayLength: number) => { + return memo; +}); +barProm = fooArrProm.reduce((memo: Bar, item: Foo) => { + return memo; +}, bar); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooArrProm = fooArrProm.filter((item: Foo, index: number, arrayLength: number) => { + return bool; +}); +fooArrProm = fooArrProm.filter((item: Foo) => { + return bool; +}); + +fooArrProm = fooArrProm.filter((item: Foo, index: number, arrayLength: number) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = fooArrProm.filter((item: Foo) => { + return bool; +}, { + concurrency: 1 +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooArrProm = fooArrProm.each((item: Foo): Bar => bar); +fooArrProm = fooArrProm.each((item: Foo, index: number): Bar => index ? bar : null); +fooArrProm = fooArrProm.each((item: Foo, index: number, arrayLength: number): Bar => bar); +fooArrProm = fooArrProm.each((item: Foo, index: number, arrayLength: number): Promise => barProm); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +function getMaybePromise(): Foo|Promise { + return foo; +} + +fooProm = Promise.try(() => { + return getMaybePromise(); +}); +fooProm = Promise.try(() => { + return getMaybePromise(); +}); +fooProm = Promise.try(() => { + return foo; +}); +fooProm = Promise.try(() => { + return foo; +}, arr); +fooProm = Promise.try(() => { + return foo; +}, arr, x); + +// - - - - - - - - - - - - - - - - - + +fooProm = Promise.try(() => { + return fooThen; +}); +fooProm = Promise.try(() => { + return fooThen; +}, arr); +fooProm = Promise.try(() => { + return fooThen; +}, arr, x); + +// - - - - - - - - - - - - - - - - - + +fooProm = Promise.try(() => { + if (fooProm) { + return fooProm; + } + return foo; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = Promise.attempt(() => { + return getMaybePromise(); +}); +fooProm = Promise.attempt(() => { + return getMaybePromise(); +}); +fooProm = Promise.attempt(() => { + return foo; +}); +fooProm = Promise.attempt(() => { + return foo; +}, arr); +fooProm = Promise.attempt(() => { + return foo; +}, arr, x); + +// - - - - - - - - - - - - - - - - - + +fooProm = Promise.attempt(() => { + if (fooProm) { + return fooProm; + } + return foo; +}); + +// - - - - - - - - - - - - - - - - - + +fooProm = Promise.attempt(() => { + return fooThen; +}); +fooProm = Promise.attempt(() => { + return fooThen; +}, arr); +fooProm = Promise.attempt(() => { + return fooThen; +}, arr, x); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +func = Promise.method(function () { + +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = Promise.resolve(foo); +fooProm = Promise.resolve(fooThen); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +voidProm = Promise.reject(reason); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooResolver = Promise.defer(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = Promise.cast(foo); +fooProm = Promise.cast(fooThen); + +voidProm = Promise.bind(x); + +bool = Promise.is(value); + +Promise.longStackTraces(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +//TODO enable delay + +fooProm = Promise.delay(num, fooThen); +fooProm = Promise.delay(num, foo); +voidProm = Promise.delay(num); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +func = Promise.promisify(f); +func = Promise.promisify(f, obj); + +obj = Promise.promisifyAll(obj); +anyProm = Promise.fromNode(callback => nodeCallbackFunc(callback)); +anyProm = Promise.fromNode(callback => nodeCallbackFuncErrorOnly(callback)); +anyProm = Promise.fromNode(callback => nodeCallbackFunc(callback), {multiArgs : true}); +anyProm = Promise.fromNode(callback => nodeCallbackFuncErrorOnly(callback), {multiArgs : true}); + +anyProm = Promise.fromCallback(callback => nodeCallbackFunc(callback)); +anyProm = Promise.fromCallback(callback => nodeCallbackFuncErrorOnly(callback)); +anyProm = Promise.fromCallback(callback => nodeCallbackFunc(callback), {multiArgs : true}); +anyProm = Promise.fromCallback(callback => nodeCallbackFuncErrorOnly(callback), {multiArgs : true}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +declare var util: any; + +function defaultFilter(name: string, func: Function) { + return util.isIdentifier(name) && + name.charAt(0) !== "_" && + !util.isClass(func); +} + +function DOMPromisifier(originalMethod: Function) { + // return a function + return function promisified() { + var args = [].slice.call(arguments); + // Needed so that the original method can be called with the correct receiver + var self = this; + // which returns a promise + return new Promise(function(resolve, reject) { + args.push(resolve, reject); + originalMethod.apply(self, args); + }); + }; +} + +obj = Promise.promisifyAll(obj, { + suffix: "", + filter: defaultFilter, + promisifier: DOMPromisifier +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +//TODO enable generator +/* + func = Promise.coroutine(f); + + barProm = Promise.spawn(f); + */ +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +BlueBird = Promise.noConflict(); + +Promise.onPossiblyUnhandledRejection((reason: any) => { + +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +//TODO expand tests to overloads +fooArrProm = Promise.all(fooThenArrThen); +fooArrProm = Promise.all(fooArrProm); +fooArrProm = Promise.all(fooThenArr); +fooArrProm = Promise.all(fooArr); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +objProm = Promise.props(objProm); +objProm = Promise.props(obj); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +//TODO expand tests to overloads +fooInspectionArrProm = Promise.settle(fooThenArrThen); +fooInspectionArrProm = Promise.settle(fooArrProm); +fooInspectionArrProm = Promise.settle(fooThenArr); +fooInspectionArrProm = Promise.settle(fooArr); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +//TODO expand tests to overloads +fooProm = Promise.any(fooThenArrThen); +fooProm = Promise.any(fooArrProm); +fooProm = Promise.any(fooThenArr); +fooProm = Promise.any(fooArr); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +//TODO expand tests to overloads +fooProm = Promise.race(fooThenArrThen); +fooProm = Promise.race(fooArrProm); +fooProm = Promise.race(fooThenArr); +fooProm = Promise.race(fooArr); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +//TODO expand tests to overloads +fooArrProm = Promise.some(fooThenArrThen, num); +fooArrProm = Promise.some(fooArrThen, num); +fooArrProm = Promise.some(fooThenArr, num); +fooArrProm = Promise.some(fooArr, num); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooArrProm = Promise.join(foo, foo, foo); +fooArrProm = Promise.join(fooThen, fooThen, fooThen); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// map() + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArrThen + +barArrProm = Promise.map(fooThenArrThen, (item: Foo) => { + return bar; +}); +barArrProm = Promise.map(fooThenArrThen, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.map(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.map(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + +barArrProm = Promise.map(fooThenArrThen, (item: Foo) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooThenArrThen, (item: Foo) => { + return barThen; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}, { + concurrency: 1 +}); +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArrThen + +barArrProm = Promise.map(fooArrThen, (item: Foo) => { + return bar; +}); +barArrProm = Promise.map(fooArrThen, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.map(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.map(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + +barArrProm = Promise.map(fooArrThen, (item: Foo) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooArrThen, (item: Foo) => { + return barThen; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}, { + concurrency: 1 +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArr + +barArrProm = Promise.map(fooThenArr, (item: Foo) => { + return bar; +}); +barArrProm = Promise.map(fooThenArr, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.map(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.map(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + +barArrProm = Promise.map(fooThenArr, (item: Foo) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooThenArr, (item: Foo) => { + return barThen; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}, { + concurrency: 1 +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArr + +barArrProm = Promise.map(fooArr, (item: Foo) => { + return bar; +}); +barArrProm = Promise.map(fooArr, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.map(fooArr, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.map(fooArr, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + +barArrProm = Promise.map(fooArr, (item: Foo) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooArr, (item: Foo) => { + return barThen; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooArr, (item: Foo, index: number, arrayLength: number) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooArr, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}, { + concurrency: 1 +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// mapSeries() + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArrThen + +barArrProm = Promise.mapSeries(fooThenArrThen, (item: Foo) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooThenArrThen, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.mapSeries(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArrThen + +barArrProm = Promise.mapSeries(fooArrThen, (item: Foo) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooArrThen, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.mapSeries(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArr + +barArrProm = Promise.mapSeries(fooThenArr, (item: Foo) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooThenArr, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.mapSeries(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArr + +barArrProm = Promise.mapSeries(fooArr, (item: Foo) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooArr, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.mapSeries(fooArr, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooArr, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// reduce() + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArrThen + +barProm = Promise.reduce(fooThenArrThen, (memo: Bar, item: Foo) => { + return memo; +}, bar); +barProm = Promise.reduce(fooThenArrThen, (memo: Bar, item: Foo) => { + return barThen; +}, bar); +barProm = Promise.reduce(fooThenArrThen, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return memo; +}, bar); +barProm = Promise.reduce(fooThenArrThen, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return barThen; +}, bar); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArrThen + +barProm = Promise.reduce(fooArrThen, (memo: Bar, item: Foo) => { + return memo; +}, bar); +barProm = Promise.reduce(fooArrThen, (memo: Bar, item: Foo) => { + return barThen; +}, bar); +barProm = Promise.reduce(fooArrThen, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return memo; +}, bar); +barProm = Promise.reduce(fooArrThen, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return barThen; +}, bar); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArr + +barProm = Promise.reduce(fooThenArr, (memo: Bar, item: Foo) => { + return memo; +}, bar); +barProm = Promise.reduce(fooThenArr, (memo: Bar, item: Foo) => { + return barThen; +}, bar); +barProm = Promise.reduce(fooThenArr, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return memo; +}, bar); +barProm = Promise.reduce(fooThenArr, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return barThen; +}, bar); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArr + +barProm = Promise.reduce(fooArr, (memo: Bar, item: Foo) => { + return memo; +}, bar); +barProm = Promise.reduce(fooArr, (memo: Bar, item: Foo) => { + return barThen; +}, bar); +barProm = Promise.reduce(fooArr, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return memo; +}, bar); +barProm = Promise.reduce(fooArr, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return barThen; +}, bar); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// filter() + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArrThen + +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo) => { + return bool; +}); +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo) => { + return boolThen; +}); +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return bool; +}); +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}); + +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo) => { + return boolThen; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}, { + concurrency: 1 +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArrThen + +fooArrProm = Promise.filter(fooArrThen, (item: Foo) => { + return bool; +}); +fooArrProm = Promise.filter(fooArrThen, (item: Foo) => { + return boolThen; +}); +fooArrProm = Promise.filter(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return bool; +}); +fooArrProm = Promise.filter(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}); + +fooArrProm = Promise.filter(fooArrThen, (item: Foo) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooArrThen, (item: Foo) => { + return boolThen; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}, { + concurrency: 1 +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArr + +fooArrProm = Promise.filter(fooThenArr, (item: Foo) => { + return bool; +}); +fooArrProm = Promise.filter(fooThenArr, (item: Foo) => { + return boolThen; +}); +fooArrProm = Promise.filter(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return bool; +}); +fooArrProm = Promise.filter(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}); + +fooArrProm = Promise.filter(fooThenArr, (item: Foo) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooThenArr, (item: Foo) => { + return boolThen; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}, { + concurrency: 1 +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArr + +fooArrProm = Promise.filter(fooArr, (item: Foo) => { + return bool; +}); +fooArrProm = Promise.filter(fooArr, (item: Foo) => { + return boolThen; +}); +fooArrProm = Promise.filter(fooArr, (item: Foo, index: number, arrayLength: number) => { + return bool; +}); +fooArrProm = Promise.filter(fooArr, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}); + +fooArrProm = Promise.filter(fooArr, (item: Foo) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooArr, (item: Foo) => { + return boolThen; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooArr, (item: Foo, index: number, arrayLength: number) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooArr, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}, { + concurrency: 1 +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// each() + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArrThen + +fooArrThen = Promise.each(fooThenArrThen, (item: Foo) => bar); +fooArrThen = Promise.each(fooThenArrThen, (item: Foo) => barThen); +fooArrThen = Promise.each(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => bar); +fooArrThen = Promise.each(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => barThen); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArrThen + +fooArrThen = Promise.each(fooArrThen, (item: Foo) => bar); +fooArrThen = Promise.each(fooArrThen, (item: Foo) => barThen); +fooArrThen = Promise.each(fooArrThen, (item: Foo, index: number, arrayLength: number) => bar); +fooArrThen = Promise.each(fooArrThen, (item: Foo, index: number, arrayLength: number) => barThen); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArr + +fooArrThen = Promise.each(fooThenArr, (item: Foo) => bar); +fooArrThen = Promise.each(fooThenArr, (item: Foo) => barThen); +fooArrThen = Promise.each(fooThenArr, (item: Foo, index: number, arrayLength: number) => bar); +fooArrThen = Promise.each(fooThenArr, (item: Foo, index: number, arrayLength: number) => barThen); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArr + +fooArrThen = Promise.each(fooArr, (item: Foo) => bar); +fooArrThen = Promise.each(fooArr, (item: Foo) => barThen); +fooArrThen = Promise.each(fooArr, (item: Foo, index: number, arrayLength: number) => bar); +fooArrThen = Promise.each(fooArr, (item: Foo, index: number, arrayLength: number) => barThen); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/bluebird/bluebird-2.0.d.ts b/bluebird/bluebird-2.0.d.ts new file mode 100644 index 0000000000..34659859cb --- /dev/null +++ b/bluebird/bluebird-2.0.d.ts @@ -0,0 +1,773 @@ +// Type definitions for bluebird 2.0.0 +// Project: https://github.com/petkaantonov/bluebird +// Definitions by: Bart van der Schoor , falsandtru +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// ES6 model with generics overload was sourced and trans-multiplied from es6-promises.d.ts +// By: Campredon + +// Warning: recommended to use `tsc > v0.9.7` (critical bugs in earlier generic code): +// - https://github.com/DefinitelyTyped/DefinitelyTyped/issues/1563 + +// Note: replicate changes to all overloads in both definition and test file +// Note: keep both static and instance members inline (so similar) + +// TODO fix remaining TODO annotations in both definition and test + +// TODO verify support to have no return statement in handlers to get a Promise (more overloads?) + +declare var Promise: PromiseConstructor; + +interface PromiseCancelHandlerSetter { + (handler: () => void): void; +} + +interface PromiseConstructor { + /** + * Create a new promise. The passed in function will receive functions + * `resolve` and `reject` as its arguments which can be called to seal the + * fate of the created promise. + * + * If configured appropriately, it will also receive an `onCancel` + * function that can be used to configure a promise cancellation handler. + */ + new (callback: ( + resolve: (thenableOrResult?: T | PromiseLike) => void, + reject: (error: any) => void, + onCancel?: PromiseCancelHandlerSetter + ) => void): Promise; + + config(options: { + warnings?: boolean | {wForgottenReturn?: boolean}; + longStackTraces?: boolean; + cancellation?: boolean; + monitoring?: boolean; + }): void; + + // Ideally, we'd define e.g. "export class RangeError extends Error {}", + // but as Error is defined as an interface (not a class), TypeScript doesn't + // allow extending Error, only implementing it. + // However, if we want to catch() only a specific error type, we need to pass + // a constructor function to it. So, as a workaround, we define them here as such. + RangeError(): RangeError; + CancellationError(): Promise.CancellationError; + TimeoutError(): Promise.TimeoutError; + TypeError(): Promise.TypeError; + RejectionError(): Promise.RejectionError; + OperationalError(): Promise.OperationalError; + + /** + * Changes how bluebird schedules calls a-synchronously. + * + * @param scheduler Should be a function that asynchronously schedules + * the calling of the passed in function + */ + setScheduler(scheduler: (callback: (...args: any[]) => void) => void): void; + + /** + * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. + * + * Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call. + * + * Alias for `attempt();` for compatibility with earlier ECMAScript version. + */ + try(fn: () => T | PromiseLike, args?: any[], ctx?: any): Promise; + + attempt(fn: () => T | PromiseLike, args?: any[], ctx?: any): Promise; + + /** + * Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. + * This method is convenient when a function can sometimes return synchronously or throw synchronously. + */ + method(fn: Function): Function; + + /** + * Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state. + */ + resolve(value: T | PromiseLike): Promise; + resolve(): Promise; + + /** + * Create a promise that is rejected with the given `reason`. + */ + reject(reason: any): Promise; + reject(reason: any): Promise; + + /** + * Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution). + */ + defer(): Promise.Resolver; + + /** + * Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable. + */ + cast(value: T | PromiseLike): Promise; + + /** + * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. + */ + bind(thisArg: any): Promise; + + /** + * See if `value` is a trusted Promise. + */ + is(value: any): boolean; + + /** + * Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have alread been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency. + */ + longStackTraces(): void; + + /** + * Returns a promise that will be fulfilled with `value` (or `undefined`) after given `ms` milliseconds. If `value` is a promise, the delay will start counting down when it is fulfilled and the returned promise will be fulfilled with the fulfillment value of the `value` promise. + */ + // TODO enable more overloads + delay(ms: number, value: T | PromiseLike): Promise; + delay(ms: number): Promise; + + /** + * Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument. + * + * If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them. + * + * If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`. + */ + promisify(func: (callback: (err: any, result: T) => void) => void, receiver?: any): () => Promise; + promisify(func: (arg1: A1, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1) => Promise; + promisify(func: (arg1: A1, arg2: A2, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2) => Promise; + promisify(func: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3) => Promise; + promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Promise; + promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Promise; + promisify(nodeFunction: Function, receiver?: any): Function; + + /** + * Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object. + * + * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. + */ + // TODO how to model promisifyAll? + promisifyAll(target: Object, options?: Promise.PromisifyAllOptions): any; + + + /** + * Returns a promise that is resolved by a node style callback function. + */ + fromNode(resolver: (callback: (err: any, result?: any) => void) => void, options? : {multiArgs? : boolean}): Promise; + fromCallback(resolver: (callback: (err: any, result?: any) => void) => void, options? : {multiArgs? : boolean}): Promise; + + /** + * Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. + */ + // TODO fix coroutine GeneratorFunction + coroutine(generatorFunction: Function): Function; + + /** + * Spawn a coroutine which may yield promises to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. + */ + // TODO fix spawn GeneratorFunction + spawn(generatorFunction: Function): Promise; + + /** + * This is relevant to browser environments with no module loader. + * + * Release control of the `Promise` namespace to whatever it was before this library was loaded. Returns a reference to the library namespace so you can attach it to something else. + */ + noConflict(): typeof Promise; + + /** + * Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers. + * + * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. + */ + onPossiblyUnhandledRejection(handler: (reason: any) => any): void; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason. + */ + // TODO enable more overloads + // promise of array with promises of value + all(values: PromiseLike[]>): Promise; + // promise of array with values + all(values: PromiseLike): Promise; + // array with promises of value + all(values: PromiseLike[]): Promise; + // array with promises of different types + all(values: [PromiseLike, PromiseLike, PromiseLike, PromiseLike, PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + all(values: [PromiseLike, PromiseLike, PromiseLike, PromiseLike]): Promise<[T1, T2, T3, T4]>; + all(values: [PromiseLike, PromiseLike, PromiseLike]): Promise<[T1, T2, T3]>; + all(values: [PromiseLike, PromiseLike]): Promise<[T1, T2]>; + // array with values + all(values: T[]): Promise; + + /** + * Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason. + * + * If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties. + * + * *The original object is not modified.* + */ + // TODO verify this is correct + // trusted promise for object + props(object: Promise): Promise; + // object + props(object: Object): Promise; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are either fulfilled or rejected. The fulfillment value is an array of ``PromiseInspection`` instances at respective positions in relation to the input array. + * + * *original: The array is not modified. The input array sparsity is retained in the resulting array.* + */ + // promise of array with promises of value + settle(values: PromiseLike[]>): Promise[]>; + // promise of array with values + settle(values: PromiseLike): Promise[]>; + // array with promises of value + settle(values: PromiseLike[]): Promise[]>; + // array with values + settle(values: T[]): Promise[]>; + + /** + * Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly. + */ + // promise of array with promises of value + any(values: PromiseLike[]>): Promise; + // promise of array with values + any(values: PromiseLike): Promise; + // array with promises of value + any(values: PromiseLike[]): Promise; + // array with values + any(values: T[]): Promise; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value. + * + * **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending. + */ + // promise of array with promises of value + race(values: PromiseLike[]>): Promise; + // promise of array with values + race(values: PromiseLike): Promise; + // array with promises of value + race(values: PromiseLike[]): Promise; + // array with values + race(values: T[]): Promise; + + /** + * Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution. + * + * If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in. + * + * *The original array is not modified.* + */ + // promise of array with promises of value + some(values: PromiseLike[]>, count: number): Promise; + // promise of array with values + some(values: PromiseLike, count: number): Promise; + // array with promises of value + some(values: PromiseLike[], count: number): Promise; + // array with values + some(values: T[], count: number): Promise; + + /** + * Like `Promise.all()` but instead of having to pass an array, the array is generated from the passed variadic arguments. + */ + // variadic array with promises of value + join(...values: PromiseLike[]): Promise; + // variadic array with values + join(...values: T[]): Promise; + + /** + * Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. + * + * *The original array is not modified.* + */ + // promise of array with promises of value + map(values: PromiseLike[]>, mapper: (item: T, index: number, arrayLength: number) => U | PromiseLike, options?: Promise.ConcurrencyOption): Promise; + + // promise of array with values + map(values: PromiseLike, mapper: (item: T, index: number, arrayLength: number) => U | PromiseLike, options?: Promise.ConcurrencyOption): Promise; + + // array with promises of value + map(values: PromiseLike[], mapper: (item: T, index: number, arrayLength: number) => U | PromiseLike, options?: Promise.ConcurrencyOption): Promise; + + // array with values + map(values: T[], mapper: (item: T, index: number, arrayLength: number) => U | PromiseLike, options?: Promise.ConcurrencyOption): Promise; + + /** + * Similar to `map` with concurrency set to 1 but guaranteed to execute in sequential order + * + * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. + * + * *The original array is not modified.* + */ + // promise of array with promises of value + mapSeries(values: PromiseLike[]>, mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike): Promise; + + // promise of array with values + mapSeries(values: PromiseLike, mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike): Promise; + + // array with promises of value + mapSeries(values: PromiseLike[], mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike): Promise; + + // array with values + mapSeries(values: R[], mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike): Promise; + + + /** + * Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. + * + * *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.* + */ + // promise of array with promises of value + reduce(values: PromiseLike[]>, reducer: (total: U, current: T, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Promise; + + // promise of array with values + reduce(values: PromiseLike, reducer: (total: U, current: T, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Promise; + + // array with promises of value + reduce(values: PromiseLike[], reducer: (total: U, current: T, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Promise; + + // array with values + reduce(values: T[], reducer: (total: U, current: T, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Promise; + + /** + * Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result. + * + * *The original array is not modified. + */ + // promise of array with promises of value + filter(values: PromiseLike[]>, filterer: (item: T, index: number, arrayLength: number) => boolean | PromiseLike, option?: Promise.ConcurrencyOption): Promise; + + // promise of array with values + filter(values: PromiseLike, filterer: (item: T, index: number, arrayLength: number) => boolean | PromiseLike, option?: Promise.ConcurrencyOption): Promise; + + // array with promises of value + filter(values: PromiseLike[], filterer: (item: T, index: number, arrayLength: number) => boolean | PromiseLike, option?: Promise.ConcurrencyOption): Promise; + + // array with values + filter(values: T[], filterer: (item: T, index: number, arrayLength: number) => boolean | PromiseLike, option?: Promise.ConcurrencyOption): Promise; + + /** + * Iterate over an array, or a promise of an array, which contains promises (or a mix of promises and values) with the given iterator function with the signature (item, index, value) where item is the resolved value of a respective promise in the input array. Iteration happens serially. If any promise in the input array is rejected the returned promise is rejected as well. + * + * Resolves to the original array unmodified, this method is meant to be used for side effects. If the iterator function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. + */ + // promise of array with promises of value + each(values: PromiseLike[]>, iterator: (item: T, index: number, arrayLength: number) => U | PromiseLike): Promise; + // array with promises of value + each(values: PromiseLike[], iterator: (item: T, index: number, arrayLength: number) => U | PromiseLike): Promise; + // array with values OR promise of array with values + each(values: T[] | PromiseLike, iterator: (item: T, index: number, arrayLength: number) => U | PromiseLike): Promise; +} + +interface Promise extends PromiseLike, Promise.Inspection { + /** + * Promises/A+ `.then()` with progress handler. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. + */ + then(onFulfill: (value: T) => U | PromiseLike, onReject?: (error: any) => U | PromiseLike, onProgress?: (note: any) => any): Promise; + then(onFulfill: (value: T) => U | PromiseLike, onReject?: (error: any) => void | PromiseLike, onProgress?: (note: any) => any): Promise; + + /** + * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. + * + * Alias `.caught();` for compatibility with earlier ECMAScript version. + */ + catch(onReject?: (error: any) => T | PromiseLike | void | PromiseLike): Promise; + caught(onReject?: (error: any) => T | PromiseLike | void | PromiseLike): Promise; + + catch(onReject?: (error: any) => U | PromiseLike): Promise; + caught(onReject?: (error: any) => U | PromiseLike): Promise; + + /** + * This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called. + * + * This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called. + * + * Alias `.caught();` for compatibility with earlier ECMAScript version. + */ + catch(predicate: (error: any) => boolean, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Promise; + caught(predicate: (error: any) => boolean, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Promise; + + catch(predicate: (error: any) => boolean, onReject: (error: any) => U | PromiseLike): Promise; + caught(predicate: (error: any) => boolean, onReject: (error: any) => U | PromiseLike): Promise; + + catch(ErrorClass: Function, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Promise; + caught(ErrorClass: Function, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Promise; + + catch(ErrorClass: Function, onReject: (error: any) => U | PromiseLike): Promise; + caught(ErrorClass: Function, onReject: (error: any) => U | PromiseLike): Promise; + + + /** + * Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections. + */ + error(onReject: (reason: any) => PromiseLike): Promise; + error(onReject: (reason: any) => U): Promise; + + /** + * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler. + * + * Alias `.lastly();` for compatibility with earlier ECMAScript version. + */ + finally(handler: () => U | PromiseLike): Promise; + + lastly(handler: () => U | PromiseLike): Promise; + + /** + * Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise. + */ + bind(thisArg: any): Promise; + + /** + * Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error. + */ + done(onFulfilled?: (value: T) => PromiseLike, onRejected?: (error: any) => U | PromiseLike, onProgress?: (note: any) => any): void; + done(onFulfilled?: (value: T) => U, onRejected?: (error: any) => U | PromiseLike, onProgress?: (note: any) => any): void; + + /** + * Like `.finally()`, but not called for rejections. + */ + tap(onFulFill: (value: T) => U | PromiseLike): Promise; + + /** + * Shorthand for `.then(null, null, handler);`. Attach a progress handler that will be called if this promise is progressed. Returns a new promise chained from this promise. + */ + progressed(handler: (note: any) => any): Promise; + + /** + * Same as calling `Promise.delay(this, ms)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + delay(ms: number): Promise; + + /** + * Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. However, if this promise is not fulfilled or rejected within `ms` milliseconds, the returned promise is rejected with a `Promise.TimeoutError` instance. + * + * You may specify a custom error message with the `message` parameter. + */ + timeout(ms: number, message?: string): Promise; + + /** + * Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success. + * Returns back this promise instead of creating a new one. If the `callback` argument is not a function, this method does not do anything. + */ + nodeify(callback: (err: any, value?: T) => void, options?: Promise.SpreadOption): Promise; + nodeify(...sink: any[]): Promise; + + /** + * Marks this promise as cancellable. Promises by default are not cancellable after v0.11 and must be marked as such for `.cancel()` to have any effect. Marking a promise as cancellable is infectious and you don't need to remark any descendant promise. + */ + cancellable(): Promise; + + /** + * Cancel this promise. The cancellation will propagate to farthest cancellable ancestor promise which is still pending. + * + * That ancestor will then be rejected with a `CancellationError` (get a reference from `Promise.CancellationError`) object as the rejection reason. + * + * In a promise rejection handler you may check for a cancellation by seeing if the reason object has `.name === "Cancel"`. + * + * Promises are by default not cancellable. Use `.cancellable()` to mark a promise as cancellable. + */ + // TODO what to do with this? + cancel(reason?: any): Promise; + + /** + * Like `.then()`, but cancellation of the the returned promise or any of its descendant will not propagate cancellation to this promise or this promise's ancestors. + */ + fork(onFulfilled?: (value: T) => U | PromiseLike, onRejected?: (error: any) => U | PromiseLike, onProgress?: (note: any) => any): Promise; + + /** + * Create an uncancellable promise based on this promise. + */ + uncancellable(): Promise; + + /** + * See if this promise can be cancelled. + */ + isCancellable(): boolean; + + /** + * See if this `promise` has been fulfilled. + */ + isFulfilled(): boolean; + + /** + * See if this `promise` has been rejected. + */ + isRejected(): boolean; + + /** + * See if this `promise` is still defer. + */ + isPending(): boolean; + + /** + * See if this `promise` is resolved -> either fulfilled or rejected. + */ + isResolved(): boolean; + + /** + * Get the fulfillment value of the underlying promise. Throws if the promise isn't fulfilled yet. + * + * throws `TypeError` + */ + value(): T; + + /** + * Get the rejection reason for the underlying promise. Throws if the promise isn't rejected yet. + * + * throws `TypeError` + */ + reason(): any; + + /** + * Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of the promise as snapshotted at the time of calling `.inspect()`. + */ + inspect(): Promise.Inspection; + + /** + * This is a convenience method for doing: + * + * + * promise.then(function(obj){ + * return obj[propertyName].call(obj, arg...); + * }); + * + */ + call(propertyName: string, ...args: any[]): Promise; + + /** + * This is a convenience method for doing: + * + * + * promise.then(function(obj){ + * return obj[propertyName]; + * }); + * + */ + // TODO find way to fix get() + // get(propertyName: string): Promise; + + /** + * Convenience method for: + * + * + * .then(function() { + * return value; + * }); + * + * + * in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()` + * + * Alias `.thenReturn();` for compatibility with earlier ECMAScript version. + */ + return(): Promise; + thenReturn(): Promise; + return(value: U): Promise; + thenReturn(value: U): Promise; + + /** + * Convenience method for: + * + * + * .then(function() { + * throw reason; + * }); + * + * Same limitations apply as with `.return()`. + * + * Alias `.thenThrow();` for compatibility with earlier ECMAScript version. + */ + throw(reason: Error): Promise; + thenThrow(reason: Error): Promise; + + /** + * Convert to String. + */ + toString(): string; + + /** + * This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`. + */ + toJSON(): Object; + + /** + * Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers. + */ + // TODO how to model instance.spread()? like Q? + spread(onFulfill: Function, onReject?: (reason: any) => U | PromiseLike): Promise; + /* + // TODO or something like this? + spread(onFulfill: (...values: W[]) => PromiseLike, onReject?: (reason: any) => PromiseLike): Promise; + spread(onFulfill: (...values: W[]) => PromiseLike, onReject?: (reason: any) => U): Promise; + spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => PromiseLike): Promise; + spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => U): Promise; + */ + /** + * Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + all(): Promise; + + /** + * Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO how to model instance.props()? + props(): Promise; + + /** + * Same as calling `Promise.settle(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + settle(): Promise[]>; + + /** + * Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + any(): Promise; + + /** + * Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + some(count: number): Promise; + + /** + * Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + race(): Promise; + + /** + * Same as calling `Promise.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + map(mapper: (item: Q, index: number, arrayLength: number) => U | PromiseLike, options?: Promise.ConcurrencyOption): Promise; + + /** + * Same as `Promise.mapSeries(thisPromise, mapper)`. + */ + // TODO type inference from array-resolving promise? + mapSeries(mapper: (item: Q, index: number, arrayLength: number) => U | PromiseLike): Promise; + + /** + * Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Promise; + + /** + * Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + filter(filterer: (item: U, index: number, arrayLength: number) => boolean | PromiseLike, options?: Promise.ConcurrencyOption): Promise; + + /** + * Same as calling ``Promise.each(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + each(iterator: (item: T, index: number, arrayLength: number) => U | PromiseLike): Promise; +} + +/** + * Don't use variable namespace such as variables, functions, and classes. + * If you use this namespace, it will conflict in es6. + */ +declare namespace Promise { + export interface RangeError extends Error { + } + export interface CancellationError extends Error { + } + export interface TimeoutError extends Error { + } + export interface TypeError extends Error { + } + export interface RejectionError extends Error { + } + export interface OperationalError extends Error { + } + + export interface ConcurrencyOption { + concurrency: number; + } + export interface SpreadOption { + spread: boolean; + } + export interface PromisifyAllOptions { + suffix?: string; + filter?: (name: string, func: Function, target?: any, passesDefaultFilter?: boolean) => boolean; + // The promisifier gets a reference to the original method and should return a function which returns a promise + promisifier?: (originalMethod: Function) => () => PromiseLike; + } + + export interface Resolver { + /** + * Returns a reference to the controlled promise that can be passed to clients. + */ + promise: Promise; + + /** + * Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state. + */ + resolve(value: T): void; + resolve(): void; + + /** + * Reject the underlying promise with `reason` as the rejection reason. + */ + reject(reason: any): void; + + /** + * Progress the underlying promise with `value` as the progression value. + */ + progress(value: any): void; + + /** + * Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions. + * + * If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values. + */ + // TODO specify resolver callback + callback: (err: any, value: T, ...values: T[]) => void; + } + + export interface Inspection { + /** + * See if the underlying promise was fulfilled at the creation time of this inspection object. + */ + isFulfilled(): boolean; + + /** + * See if the underlying promise was rejected at the creation time of this inspection object. + */ + isRejected(): boolean; + + /** + * See if the underlying promise was defer at the creation time of this inspection object. + */ + isPending(): boolean; + + /** + * Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object. + * + * throws `TypeError` + */ + value(): T; + + /** + * Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object. + * + * throws `TypeError` + */ + reason(): any; + } +} + +declare module 'bluebird' { + export = Promise; +} diff --git a/bluebird/bluebird-tests.ts b/bluebird/bluebird-tests.ts index a24cdfd7ee..59cef89b1a 100644 --- a/bluebird/bluebird-tests.ts +++ b/bluebird/bluebird-tests.ts @@ -7,6 +7,8 @@ // Note: try to maintain the ordering and separators, and keep to the pattern +import Promise = require("bluebird"); + var obj: Object; var bool: boolean; var num: number; @@ -141,7 +143,7 @@ var fooResolver: Promise.Resolver; var barResolver: Promise.Resolver; var fooInspection: Promise.Inspection; -var barInspection: Promise.Inspection; +var fooInspectionPromise: Promise>; var fooInspectionArrProm: Promise[]>; var barInspectionArrProm: Promise[]>; @@ -195,8 +197,6 @@ fooResolver.resolve(foo); fooResolver.reject(err); -fooResolver.progress(bar); - fooResolver.callback = (err: any, value: Foo) => { }; @@ -204,24 +204,13 @@ fooResolver.callback = (err: any, value: Foo) => { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool = fooInspection.isFulfilled(); - bool = fooInspection.isRejected(); - bool = fooInspection.isPending(); - foo = fooInspection.value(); - x = fooInspection.reason(); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -barProm = fooProm.then((value: Foo) => { - return bar; -}, (reason: any) => { - return bar; -}, (note: any) => { - return bar; -}); barProm = fooProm.then((value: Foo) => { return bar; }, (reason: any) => { @@ -384,13 +373,6 @@ fooProm = fooProm.bind(obj); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -voidVar = fooProm.done((value: Foo) => { - return bar; -}, (reason: any) => { - return bar; -}, (note: any) => { - -}); voidVar = fooProm.done((value: Foo) => { return bar; }, (reason: any) => { @@ -402,13 +384,6 @@ voidVar = fooProm.done((value: Foo) => { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -voidVar = fooProm.done((value: Foo) => { - return barThen; -}, (reason: any) => { - return barThen; -}, (note: any) => { - -}); voidVar = fooProm.done((value: Foo) => { return barThen; }, (reason: any) => { @@ -436,11 +411,6 @@ fooProm = fooProm.tap(() => { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -fooProm = fooProm.progressed((note: any) => { - return foo; -}); -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - fooProm = fooProm.delay(num); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -460,52 +430,11 @@ fooProm = fooProm.nodeify((err: any, foo?: Foo) => { }, { spread: true }); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -barProm = fooProm.fork((value: Foo) => { - return bar; -}, (reason: any) => { - return bar; -}, (note: any) => { - -}); -barProm = fooProm.fork((value: Foo) => { - return bar; -}, (reason: any) => { - return bar; -}); -barProm = fooProm.fork((value: Foo) => { - return bar; -}); - -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -barProm = fooProm.fork((value: Foo) => { - return barThen; -}, (reason: any) => { - return barThen; -}, (note: any) => { - -}); -barProm = fooProm.fork((value: Foo) => { - return barThen; -}, (reason: any) => { - return barThen; -}); -barProm = fooProm.fork((value: Foo) => { - return barThen; -}); +voidVar = fooProm.cancel(); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -barProm = fooProm.cancel(); - -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -fooProm = fooProm.cancellable(); -fooProm = fooProm.uncancellable(); - -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -bool = fooProm.isCancellable(); +bool = fooProm.isCancelled(); bool = fooProm.isFulfilled(); bool = fooProm.isRejected(); bool = fooProm.isPending(); @@ -513,8 +442,6 @@ bool = fooProm.isResolved(); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -fooInspection = fooProm.inspect(); - anyProm = fooProm.call(str); anyProm = fooProm.call(str, 1, 2, 3); @@ -543,22 +470,12 @@ obj = fooProm.toJSON(); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -barProm = fooArrProm.spread((one: Foo, two: Bar) => { - return bar; -}, (reason: any) => { - return bar; -}); barProm = fooArrProm.spread((one: Foo, two: Bar, twotwo: Foo) => { return bar; }); // - - - - - - - - - - - - - - - - - -barProm = fooArrProm.spread((one: Foo, two: Bar) => { - return barThen; -}, (reason: any) => { - return barThen; -}); barProm = fooArrProm.spread((one: Foo, two: Bar, twotwo: Foo) => { return barThen; }); @@ -568,15 +485,10 @@ barProm = fooArrProm.spread((one: Foo, two: Bar, twotwo: Foo) => { //TODO fix collection inference barArrProm = fooProm.all(); - objProm = fooProm.props(); - -barInspectionArrProm = fooProm.settle(); - +fooInspectionPromise = fooProm.reflect(); barProm = fooProm.any(); - barArrProm = fooProm.some(num); - barProm = fooProm.race(); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -686,24 +598,12 @@ fooProm = Promise.try(() => { fooProm = Promise.try(() => { return foo; }); -fooProm = Promise.try(() => { - return foo; -}, arr); -fooProm = Promise.try(() => { - return foo; -}, arr, x); // - - - - - - - - - - - - - - - - - fooProm = Promise.try(() => { return fooThen; }); -fooProm = Promise.try(() => { - return fooThen; -}, arr); -fooProm = Promise.try(() => { - return fooThen; -}, arr, x); // - - - - - - - - - - - - - - - - - @@ -725,12 +625,6 @@ fooProm = Promise.attempt(() => { fooProm = Promise.attempt(() => { return foo; }); -fooProm = Promise.attempt(() => { - return foo; -}, arr); -fooProm = Promise.attempt(() => { - return foo; -}, arr, x); // - - - - - - - - - - - - - - - - - @@ -746,12 +640,6 @@ fooProm = Promise.attempt(() => { fooProm = Promise.attempt(() => { return fooThen; }); -fooProm = Promise.attempt(() => { - return fooThen; -}, arr); -fooProm = Promise.attempt(() => { - return fooThen; -}, arr, x); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -847,6 +735,7 @@ obj = Promise.promisifyAll(obj, { */ // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +BlueBird = Promise.getNewLibraryCopy(); BlueBird = Promise.noConflict(); Promise.onPossiblyUnhandledRejection((reason: any) => { @@ -868,14 +757,6 @@ objProm = Promise.props(obj); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//TODO expand tests to overloads -fooInspectionArrProm = Promise.settle(fooThenArrThen); -fooInspectionArrProm = Promise.settle(fooArrProm); -fooInspectionArrProm = Promise.settle(fooThenArr); -fooInspectionArrProm = Promise.settle(fooArr); - -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //TODO expand tests to overloads fooProm = Promise.any(fooThenArrThen); fooProm = Promise.any(fooArrProm); diff --git a/bluebird/bluebird.d.ts b/bluebird/bluebird.d.ts index 34659859cb..042347f096 100644 --- a/bluebird/bluebird.d.ts +++ b/bluebird/bluebird.d.ts @@ -1,773 +1,773 @@ -// Type definitions for bluebird 2.0.0 +// Type definitions for bluebird 3.0.0 // Project: https://github.com/petkaantonov/bluebird -// Definitions by: Bart van der Schoor , falsandtru +// Definitions by: Leonard Hecker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// ES6 model with generics overload was sourced and trans-multiplied from es6-promises.d.ts -// By: Campredon +/*! + * The code following this comment originates from: + * https://github.com/types/npm-bluebird + * + * Licensed under: + * The MIT License (MIT) + * + * Copyright (c) 2016 unional + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ -// Warning: recommended to use `tsc > v0.9.7` (critical bugs in earlier generic code): -// - https://github.com/DefinitelyTyped/DefinitelyTyped/issues/1563 +// Generated by typings +// Source: bluebird.d.ts +declare module 'bluebird' { +// Type definitions for Bluebird v3.x.x +// Project: http://bluebirdjs.com -// Note: replicate changes to all overloads in both definition and test file -// Note: keep both static and instance members inline (so similar) +class Bluebird implements Bluebird.Thenable, Bluebird.Inspection { + /** + * Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise. + * If promise cancellation is enabled, passed in function will receive one more function argument `onCancel` that allows to register an optional cancellation callback. + */ + constructor(callback: (resolve: (thenableOrResult?: R | Bluebird.Thenable) => void, reject: (error?: any) => void, onCancel?: (callback: () => void) => void) => void); -// TODO fix remaining TODO annotations in both definition and test + /** + * Promises/A+ `.then()`. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. + */ + then(onFulfill: (value: R) => U | Bluebird.Thenable, onReject?: (error: any) => U | Bluebird.Thenable): Bluebird; + then(onFulfill: (value: R) => U | Bluebird.Thenable, onReject?: (error: any) => void | Bluebird.Thenable): Bluebird; -// TODO verify support to have no return statement in handlers to get a Promise (more overloads?) + /** + * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. + * + * Alias `.caught();` for compatibility with earlier ECMAScript version. + */ + catch(onReject?: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + caught(onReject?: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + catch(onReject?: (error: any) => U | Bluebird.Thenable): Bluebird; + caught(onReject?: (error: any) => U | Bluebird.Thenable): Bluebird; -declare var Promise: PromiseConstructor; + /** + * This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called. + * + * This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called. + * + * Alias `.caught();` for compatibility with earlier ECMAScript version. + */ + catch(predicate: (error: any) => boolean, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + caught(predicate: (error: any) => boolean, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + catch(predicate: (error: any) => boolean, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; + caught(predicate: (error: any) => boolean, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; + catch(ErrorClass: Function, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + caught(ErrorClass: Function, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + catch(ErrorClass: Function, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; + caught(ErrorClass: Function, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; + catch(predicate: Object, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + caught(predicate: Object, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + catch(predicate: Object, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; + caught(predicate: Object, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; -interface PromiseCancelHandlerSetter { - (handler: () => void): void; + /** + * Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections. + */ + error(onReject: (reason: any) => U | Bluebird.Thenable): Bluebird; + + /** + * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler. + * + * Alias `.lastly();` for compatibility with earlier ECMAScript version. + */ + finally(handler: () => U | Bluebird.Thenable): Bluebird; + + lastly(handler: () => U | Bluebird.Thenable): Bluebird; + + /** + * Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise. + */ + bind(thisArg: any): Bluebird; + + /** + * Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error. + */ + done(onFulfilled?: (value: R) => U | Bluebird.Thenable, onRejected?: (error: any) => U | Bluebird.Thenable): void; + + /** + * Like `.finally()`, but not called for rejections. + */ + tap(onFulFill: (value: R) => Bluebird.Thenable): Bluebird; + tap(onFulfill: (value: R) => U): Bluebird; + + /** + * Same as calling `Promise.delay(ms, this)`. + */ + delay(ms: number): Bluebird; + + /** + * Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. + * However, if this promise is not fulfilled or rejected within ms milliseconds, the returned promise + * is rejected with a TimeoutError or the error as the reason. + * + * You may specify a custom error message with the `message` parameter. + */ + timeout(ms: number, message?: string | Error): Bluebird; + + /** + * Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success. + * If the `callback` argument is not a function, this method does not do anything. + */ + nodeify(callback: (err: any, value?: R) => void, options?: Bluebird.SpreadOption): this; + nodeify(...sink: any[]): this; + asCallback(callback: (err: any, value?: R) => void, options?: Bluebird.SpreadOption): this; + asCallback(...sink: any[]): this; + + /** + * See if this `promise` has been fulfilled. + */ + isFulfilled(): boolean; + + /** + * See if this `promise` has been rejected. + */ + isRejected(): boolean; + + /** + * See if this `promise` is still defer. + */ + isPending(): boolean; + + /** + * See if this `promise` has been cancelled. + */ + isCancelled(): boolean; + + /** + * See if this `promise` is resolved -> either fulfilled or rejected. + */ + isResolved(): boolean; + + /** + * Get the fulfillment value of the underlying promise. Throws if the promise isn't fulfilled yet. + * + * throws `TypeError` + */ + value(): R; + + /** + * Get the rejection reason for the underlying promise. Throws if the promise isn't rejected yet. + * + * throws `TypeError` + */ + reason(): any; + + /** + * Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of + * the promise as snapshotted at the time of calling `.reflect()`. + */ + reflect(): Bluebird>; + reflect(): Bluebird>; + + /** + * This is a convenience method for doing: + * + * + * promise.then(function(obj){ + * return obj[propertyName].call(obj, arg...); + * }); + * + */ + call(propertyName: string, ...args: any[]): Bluebird; + + /** + * This is a convenience method for doing: + * + * + * promise.then(function(obj){ + * return obj[propertyName]; + * }); + * + */ + // TODO: Use "type property type" once it's there + // @see https://github.com/Microsoft/TypeScript/issues/1295 + get(key: string | number): Bluebird; + + /** + * Convenience method for: + * + * + * .then(function() { + * return value; + * }); + * + * + * in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()` + * + * Alias `.thenReturn();` for compatibility with earlier ECMAScript version. + */ + return(): Bluebird; + thenReturn(): Bluebird; + return(value: U): Bluebird; + thenReturn(value: U): Bluebird; + + /** + * Convenience method for: + * + * + * .then(function() { + * throw reason; + * }); + * + * Same limitations apply as with `.return()`. + * + * Alias `.thenThrow();` for compatibility with earlier ECMAScript version. + */ + throw(reason: Error): Bluebird; + thenThrow(reason: Error): Bluebird; + + /** + * Convert to String. + */ + toString(): string; + + /** + * This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`. + */ + toJSON(): Object; + + /** + * Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers. + */ + spread(fulfilledHandler: (...values: W[]) => U | Bluebird.Thenable): Bluebird; + spread(fulfilledHandler: Function): Bluebird; + + /** + * Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + all(): Bluebird; + + /** + * Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO how to model instance.props()? + props(): Bluebird; + + /** + * Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + any(): Bluebird; + + /** + * Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + some(count: number): Bluebird; + + /** + * Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + race(): Bluebird; + + /** + * Same as calling `Bluebird.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + map(mapper: (item: Q, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + + /** + * Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; + + /** + * Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + filter(filterer: (item: U, index: number, arrayLength: number) => boolean | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + + /** + * Same as calling ``Bluebird.each(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + each(iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + + /** + * Same as calling ``Bluebird.mapSeries(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + mapSeries(iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + + /** + * Cancel this `promise`. Will not do anything if this promise is already settled or if the cancellation feature has not been enabled + */ + cancel(): void; + + /** + * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. + * + * Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call. + * + * Alias for `attempt();` for compatibility with earlier ECMAScript version. + */ + static try(fn: () => R | Bluebird.Thenable): Bluebird; + static attempt(fn: () => R | Bluebird.Thenable): Bluebird; + + /** + * Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. + * This method is convenient when a function can sometimes return synchronously or throw synchronously. + */ + static method(fn: Function): Function; + + /** + * Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state. + */ + static resolve(): Bluebird; + static resolve(value: R | Bluebird.Thenable): Bluebird; + + /** + * Create a promise that is rejected with the given `reason`. + */ + static reject(reason: any): Bluebird; + static reject(reason: any): Bluebird; + + /** + * Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution). + */ + static defer(): Bluebird.Resolver; + + /** + * Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable. + */ + static cast(value: R | Bluebird.Thenable): Bluebird; + + /** + * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. + */ + static bind(thisArg: any): Bluebird; + + /** + * See if `value` is a trusted Promise. + */ + static is(value: any): boolean; + + /** + * Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have already been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency. + */ + static longStackTraces(): void; + + /** + * Returns a promise that will be resolved with value (or undefined) after given ms milliseconds. + * If value is a promise, the delay will start counting down when it is fulfilled and the returned + * promise will be fulfilled with the fulfillment value of the value promise. + */ + static delay(ms: number, value: R | Bluebird.Thenable): Bluebird; + static delay(ms: number): Bluebird; + + /** + * Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument. + * + * If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them. + * + * If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`. + */ + static promisify(func: (callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): () => Bluebird; + static promisify(func: (arg1: A1, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1) => Bluebird; + static promisify(func: (arg1: A1, arg2: A2, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2) => Bluebird; + static promisify(func: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2, arg3: A3) => Bluebird; + static promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Bluebird; + static promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Bluebird; + static promisify(nodeFunction: Function, options?: Bluebird.PromisifyOptions): Function; + + /** + * Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object. + * + * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. + */ + // TODO how to model promisifyAll? + static promisifyAll(target: Object, options?: Bluebird.PromisifyAllOptions): Object; + + /** + * Returns a promise that is resolved by a node style callback function. + */ + static fromNode(resolver: (callback: (err: any, result?: any) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird; + static fromNode(resolver: (callback: (err: any, result?: T) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird; + static fromCallback(resolver: (callback: (err: any, result?: any) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird; + static fromCallback(resolver: (callback: (err: any, result?: T) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird; + + /** + * Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. + */ + // TODO fix coroutine GeneratorFunction + static coroutine(generatorFunction: Function): Function; + + /** + * Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers. + * + * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. + */ + static onPossiblyUnhandledRejection(handler: (reason: any) => any): void; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason. + */ + // TODO enable more overloads + // array with promises of different types + static all(values: [Bluebird.Thenable | T1, Bluebird.Thenable | T2, Bluebird.Thenable | T3, Bluebird.Thenable | T4, Bluebird.Thenable | T5]): Bluebird<[T1, T2, T3, T4, T5]>; + static all(values: [Bluebird.Thenable | T1, Bluebird.Thenable | T2, Bluebird.Thenable | T3, Bluebird.Thenable | T4]): Bluebird<[T1, T2, T3, T4]>; + static all(values: [Bluebird.Thenable | T1, Bluebird.Thenable | T2, Bluebird.Thenable | T3]): Bluebird<[T1, T2, T3]>; + static all(values: [Bluebird.Thenable | T1, Bluebird.Thenable | T2]): Bluebird<[T1, T2]>; + static all(values: [Bluebird.Thenable | T1]): Bluebird<[T1]>; + // array with values + static all(values: Bluebird.Thenable<(Bluebird.Thenable | R)[]> | (Bluebird.Thenable | R)[]): Bluebird; + + /** + * Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason. + * + * If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties. + * + * *The original object is not modified.* + */ + // TODO verify this is correct + // trusted promise for object + static props(object: Bluebird): Bluebird; + // object + static props(object: Object): Bluebird; + + /** + * Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly. + */ + static any(values: Bluebird.Thenable<(Bluebird.Thenable | R)[]> | (Bluebird.Thenable | R)[]): Bluebird; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value. + * + * **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending. + */ + static race(values: Bluebird.Thenable<(Bluebird.Thenable | R)[]> | (Bluebird.Thenable | R)[]): Bluebird; + + /** + * Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution. + * + * If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in. + * + * *The original array is not modified.* + */ + // promise of array with promises of value + static some(values: Bluebird.Thenable[]>, count: number): Bluebird; + // promise of array with values + static some(values: Bluebird.Thenable, count: number): Bluebird; + // array with promises of value + static some(values: Bluebird.Thenable[], count: number): Bluebird; + // array with values + static some(values: R[], count: number): Bluebird; + + /** + * Promise.join( + * Promise|any values..., + * function handler + * ) -> Promise + * For coordinating multiple concurrent discrete promises. + * + * Note: In 1.x and 0.x Promise.join used to be a Promise.all that took the values in as arguments instead in an array. This behavior has been deprecated but is still supported partially - when the last argument is an immediate function value the new semantics will apply + */ + static join(arg1: A1 | Bluebird.Thenable, handler: (arg1?: A1) => R | Bluebird.Thenable): Bluebird; + static join(arg1: A1 | Bluebird.Thenable, arg2: A2 | Bluebird.Thenable, handler: (arg1?: A1, arg2?: A2) => R | Bluebird.Thenable): Bluebird; + static join(arg1: A1 | Bluebird.Thenable, arg2: A2 | Bluebird.Thenable, arg3: A3 | Bluebird.Thenable, handler: (arg1?: A1, arg2?: A2, arg3?: A3) => R | Bluebird.Thenable): Bluebird; + static join(arg1: A1 | Bluebird.Thenable, arg2: A2 | Bluebird.Thenable, arg3: A3 | Bluebird.Thenable, arg4: A4 | Bluebird.Thenable, handler: (arg1?: A1, arg2?: A2, arg3?: A3, arg4?: A4) => R | Bluebird.Thenable): Bluebird; + static join(arg1: A1 | Bluebird.Thenable, arg2: A2 | Bluebird.Thenable, arg3: A3 | Bluebird.Thenable, arg4: A4 | Bluebird.Thenable, arg5: A5 | Bluebird.Thenable, handler: (arg1?: A1, arg2?: A2, arg3?: A3, arg4?: A4, arg5?: A5) => R | Bluebird.Thenable): Bluebird; + + // variadic array + /** @deprecated use .all instead */ + static join(...values: (R | Bluebird.Thenable)[]): Bluebird; + + /** + * Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. + * + * *The original array is not modified.* + */ + // promise of array with promises of value + static map(values: Bluebird.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + + // promise of array with values + static map(values: Bluebird.Thenable, mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + + // array with promises of value + static map(values: Bluebird.Thenable[], mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + + // array with values + static map(values: R[], mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + + /** + * Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. + * + * *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.* + */ + // promise of array with promises of value + static reduce(values: Bluebird.Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; + + // promise of array with values + static reduce(values: Bluebird.Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; + + // array with promises of value + static reduce(values: Bluebird.Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; + + // array with values + static reduce(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; + + /** + * Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result. + * + * *The original array is not modified. + */ + // promise of array with promises of value + static filter(values: Bluebird.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; + + // promise of array with values + static filter(values: Bluebird.Thenable, filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; + + // array with promises of value + static filter(values: Bluebird.Thenable[], filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; + + // array with values + static filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; + + /** + * Iterate over an array, or a promise of an array, which contains promises (or a mix of promises and values) with the given iterator function with the signature (item, index, value) where item is the resolved value of a respective promise in the input array. Iteration happens serially. If any promise in the input array is rejected the returned promise is rejected as well. + * + * Resolves to the original array unmodified, this method is meant to be used for side effects. If the iterator function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. + */ + // promise of array with promises of value + static each(values: Bluebird.Thenable[]>, iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + // array with promises of value + static each(values: Bluebird.Thenable[], iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + // array with values OR promise of array with values + static each(values: R[] | Bluebird.Thenable, iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + + /** + * Given an Iterable(arrays are Iterable), or a promise of an Iterable, which produces promises (or a mix of promises and values), iterate over all the values in the Iterable into an array and iterate over the array serially, in-order. + * + * Returns a promise for an array that contains the values returned by the iterator function in their respective positions. The iterator won't be called for an item until its previous item, and the promise returned by the iterator for that item are fulfilled. This results in a mapSeries kind of utility but it can also be used simply as a side effect iterator similar to Array#forEach. + * + * If any promise in the input array is rejected or any promise returned by the iterator function is rejected, the result will be rejected as well. + */ + static mapSeries(values: (R | Bluebird.Thenable)[] | Bluebird.Thenable<(R | Bluebird.Thenable)[]>, iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + + /** + * A meta method used to specify the disposer method that cleans up a resource when using `Promise.using`. + * + * Returns a Disposer object which encapsulates both the resource as well as the method to clean it up. + * The user can pass this object to `Promise.using` to get access to the resource when it becomes available, + * as well as to ensure its automatically cleaned up. + * + * The second argument passed to a disposer is the result promise of the using block, which you can + * inspect synchronously. + */ + disposer(disposeFn: (arg: R, promise: Bluebird) => void | Bluebird.Thenable): Bluebird.Disposer; + + /** + * In conjunction with `.disposer`, using will make sure that no matter what, the specified disposer + * will be called when the promise returned by the callback passed to using has settled. The disposer is + * necessary because there is no standard interface in node for disposing resources. + */ + static using(disposer: Bluebird.Disposer, executor: (transaction: R) => Bluebird.Thenable): Bluebird; + static using(disposer: Bluebird.Disposer, disposer2: Bluebird.Disposer, executor: (transaction1: R1, transaction2: R2) => Bluebird.Thenable): Bluebird; + static using(disposer: Bluebird.Disposer, disposer2: Bluebird.Disposer, disposer3: Bluebird.Disposer, executor: (transaction1: R1, transaction2: R2, transaction3: R3) => Bluebird.Thenable): Bluebird; + + /** + * Add handler as the handler to call when there is a possibly unhandled rejection. + * The default handler logs the error stack to stderr or console.error in browsers. + * + * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. + * + * Note: this hook is specific to the bluebird instance its called on, application developers should use global rejection events. + */ + static onPossiblyUnhandledRejection(handler?: (error: Error, promise: Bluebird) => void): void; + + /** + * Configure long stack traces, warnings, monitoring and cancellation. + * Note that even though false is the default here, a development environment might be detected which automatically + * enables long stack traces and warnings. + */ + static config(options: { + /** Enable warnings */ + warnings?: boolean | { + /** Enables all warnings except forgotten return statements. */ + wForgottenReturn: boolean; + }; + /** Enable long stack traces */ + longStackTraces?: boolean; + /** Enable cancellation */ + cancellation?: boolean; + /** Enable monitoring */ + monitoring?: boolean; + }): void; } -interface PromiseConstructor { +namespace Bluebird { + export interface ConcurrencyOption { + concurrency: number; + } + export interface SpreadOption { + spread: boolean; + } + export interface FromNodeOptions { + multiArgs?: boolean; + } + export interface PromisifyOptions { + context?: any; + multiArgs?: boolean; + } + export interface PromisifyAllOptions extends PromisifyOptions { + suffix?: string; + filter?: (name: string, func: Function, target?: any, passesDefaultFilter?: boolean) => boolean; + // The promisifier gets a reference to the original method and should return a function which returns a promise + promisifier?: (originalMethod: Function) => () => Thenable; + } + + /** + * Represents an error is an explicit promise rejection as opposed to a thrown error. + * For example, if an error is errbacked by a callback API promisified through undefined or undefined + * and is not a typed error, it will be converted to a `OperationalError` which has the original error in + * the `.cause` property. + * + * `OperationalError`s are caught in `.error` handlers. + */ + export class OperationalError extends Error { } + + /** + * Signals that an operation has timed out. Used as a custom cancellation reason in `.timeout`. + */ + export class TimeoutError extends Error { } + + /** + * Signals that an operation has been aborted or cancelled. The default reason used by `.cancel`. + */ + export class CancellationError extends Error {} + + /** + * A collection of errors. `AggregateError` is an array-like object, with numeric indices and a `.length` property. + * It supports all generic array methods such as `.forEach` directly. + * + * `AggregateError`s are caught in `.error` handlers, even if the contained errors are not operational. + * + * `Promise.some` and `Promise.any` use `AggregateError` as rejection reason when they fail. + */ + export class AggregateError extends Error {} + + /** + * returned by `Bluebird.disposer()`. + */ + export class Disposer { + } + + export interface Thenable { + then(onFulfilled: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; + then(onFulfilled: (value: R) => U | Thenable, onRejected?: (error: any) => void | Thenable): Thenable; + } + + export interface Resolver { /** - * Create a new promise. The passed in function will receive functions - * `resolve` and `reject` as its arguments which can be called to seal the - * fate of the created promise. + * Returns a reference to the controlled promise that can be passed to clients. + */ + promise: Bluebird; + + /** + * Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state. + */ + resolve(value: R): void; + resolve(): void; + + /** + * Reject the underlying promise with `reason` as the rejection reason. + */ + reject(reason: any): void; + + /** + * Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions. * - * If configured appropriately, it will also receive an `onCancel` - * function that can be used to configure a promise cancellation handler. + * If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values. */ - new (callback: ( - resolve: (thenableOrResult?: T | PromiseLike) => void, - reject: (error: any) => void, - onCancel?: PromiseCancelHandlerSetter - ) => void): Promise; - - config(options: { - warnings?: boolean | {wForgottenReturn?: boolean}; - longStackTraces?: boolean; - cancellation?: boolean; - monitoring?: boolean; - }): void; - - // Ideally, we'd define e.g. "export class RangeError extends Error {}", - // but as Error is defined as an interface (not a class), TypeScript doesn't - // allow extending Error, only implementing it. - // However, if we want to catch() only a specific error type, we need to pass - // a constructor function to it. So, as a workaround, we define them here as such. - RangeError(): RangeError; - CancellationError(): Promise.CancellationError; - TimeoutError(): Promise.TimeoutError; - TypeError(): Promise.TypeError; - RejectionError(): Promise.RejectionError; - OperationalError(): Promise.OperationalError; + // TODO specify resolver callback + callback: (err: any, value: R, ...values: R[]) => void; + } + export interface Inspection { /** - * Changes how bluebird schedules calls a-synchronously. - * - * @param scheduler Should be a function that asynchronously schedules - * the calling of the passed in function - */ - setScheduler(scheduler: (callback: (...args: any[]) => void) => void): void; - - /** - * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. - * - * Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call. - * - * Alias for `attempt();` for compatibility with earlier ECMAScript version. - */ - try(fn: () => T | PromiseLike, args?: any[], ctx?: any): Promise; - - attempt(fn: () => T | PromiseLike, args?: any[], ctx?: any): Promise; - - /** - * Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. - * This method is convenient when a function can sometimes return synchronously or throw synchronously. - */ - method(fn: Function): Function; - - /** - * Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state. - */ - resolve(value: T | PromiseLike): Promise; - resolve(): Promise; - - /** - * Create a promise that is rejected with the given `reason`. - */ - reject(reason: any): Promise; - reject(reason: any): Promise; - - /** - * Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution). - */ - defer(): Promise.Resolver; - - /** - * Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable. - */ - cast(value: T | PromiseLike): Promise; - - /** - * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. - */ - bind(thisArg: any): Promise; - - /** - * See if `value` is a trusted Promise. - */ - is(value: any): boolean; - - /** - * Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have alread been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency. - */ - longStackTraces(): void; - - /** - * Returns a promise that will be fulfilled with `value` (or `undefined`) after given `ms` milliseconds. If `value` is a promise, the delay will start counting down when it is fulfilled and the returned promise will be fulfilled with the fulfillment value of the `value` promise. - */ - // TODO enable more overloads - delay(ms: number, value: T | PromiseLike): Promise; - delay(ms: number): Promise; - - /** - * Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument. - * - * If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them. - * - * If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`. - */ - promisify(func: (callback: (err: any, result: T) => void) => void, receiver?: any): () => Promise; - promisify(func: (arg1: A1, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1) => Promise; - promisify(func: (arg1: A1, arg2: A2, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2) => Promise; - promisify(func: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3) => Promise; - promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Promise; - promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Promise; - promisify(nodeFunction: Function, receiver?: any): Function; - - /** - * Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object. - * - * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. - */ - // TODO how to model promisifyAll? - promisifyAll(target: Object, options?: Promise.PromisifyAllOptions): any; - - - /** - * Returns a promise that is resolved by a node style callback function. - */ - fromNode(resolver: (callback: (err: any, result?: any) => void) => void, options? : {multiArgs? : boolean}): Promise; - fromCallback(resolver: (callback: (err: any, result?: any) => void) => void, options? : {multiArgs? : boolean}): Promise; - - /** - * Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. - */ - // TODO fix coroutine GeneratorFunction - coroutine(generatorFunction: Function): Function; - - /** - * Spawn a coroutine which may yield promises to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. - */ - // TODO fix spawn GeneratorFunction - spawn(generatorFunction: Function): Promise; - - /** - * This is relevant to browser environments with no module loader. - * - * Release control of the `Promise` namespace to whatever it was before this library was loaded. Returns a reference to the library namespace so you can attach it to something else. - */ - noConflict(): typeof Promise; - - /** - * Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers. - * - * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. - */ - onPossiblyUnhandledRejection(handler: (reason: any) => any): void; - - /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason. - */ - // TODO enable more overloads - // promise of array with promises of value - all(values: PromiseLike[]>): Promise; - // promise of array with values - all(values: PromiseLike): Promise; - // array with promises of value - all(values: PromiseLike[]): Promise; - // array with promises of different types - all(values: [PromiseLike, PromiseLike, PromiseLike, PromiseLike, PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; - all(values: [PromiseLike, PromiseLike, PromiseLike, PromiseLike]): Promise<[T1, T2, T3, T4]>; - all(values: [PromiseLike, PromiseLike, PromiseLike]): Promise<[T1, T2, T3]>; - all(values: [PromiseLike, PromiseLike]): Promise<[T1, T2]>; - // array with values - all(values: T[]): Promise; - - /** - * Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason. - * - * If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties. - * - * *The original object is not modified.* - */ - // TODO verify this is correct - // trusted promise for object - props(object: Promise): Promise; - // object - props(object: Object): Promise; - - /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are either fulfilled or rejected. The fulfillment value is an array of ``PromiseInspection`` instances at respective positions in relation to the input array. - * - * *original: The array is not modified. The input array sparsity is retained in the resulting array.* - */ - // promise of array with promises of value - settle(values: PromiseLike[]>): Promise[]>; - // promise of array with values - settle(values: PromiseLike): Promise[]>; - // array with promises of value - settle(values: PromiseLike[]): Promise[]>; - // array with values - settle(values: T[]): Promise[]>; - - /** - * Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly. - */ - // promise of array with promises of value - any(values: PromiseLike[]>): Promise; - // promise of array with values - any(values: PromiseLike): Promise; - // array with promises of value - any(values: PromiseLike[]): Promise; - // array with values - any(values: T[]): Promise; - - /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value. - * - * **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending. - */ - // promise of array with promises of value - race(values: PromiseLike[]>): Promise; - // promise of array with values - race(values: PromiseLike): Promise; - // array with promises of value - race(values: PromiseLike[]): Promise; - // array with values - race(values: T[]): Promise; - - /** - * Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution. - * - * If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in. - * - * *The original array is not modified.* - */ - // promise of array with promises of value - some(values: PromiseLike[]>, count: number): Promise; - // promise of array with values - some(values: PromiseLike, count: number): Promise; - // array with promises of value - some(values: PromiseLike[], count: number): Promise; - // array with values - some(values: T[], count: number): Promise; - - /** - * Like `Promise.all()` but instead of having to pass an array, the array is generated from the passed variadic arguments. - */ - // variadic array with promises of value - join(...values: PromiseLike[]): Promise; - // variadic array with values - join(...values: T[]): Promise; - - /** - * Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. - * - * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. - * - * *The original array is not modified.* - */ - // promise of array with promises of value - map(values: PromiseLike[]>, mapper: (item: T, index: number, arrayLength: number) => U | PromiseLike, options?: Promise.ConcurrencyOption): Promise; - - // promise of array with values - map(values: PromiseLike, mapper: (item: T, index: number, arrayLength: number) => U | PromiseLike, options?: Promise.ConcurrencyOption): Promise; - - // array with promises of value - map(values: PromiseLike[], mapper: (item: T, index: number, arrayLength: number) => U | PromiseLike, options?: Promise.ConcurrencyOption): Promise; - - // array with values - map(values: T[], mapper: (item: T, index: number, arrayLength: number) => U | PromiseLike, options?: Promise.ConcurrencyOption): Promise; - - /** - * Similar to `map` with concurrency set to 1 but guaranteed to execute in sequential order - * - * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. - * - * *The original array is not modified.* - */ - // promise of array with promises of value - mapSeries(values: PromiseLike[]>, mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike): Promise; - - // promise of array with values - mapSeries(values: PromiseLike, mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike): Promise; - - // array with promises of value - mapSeries(values: PromiseLike[], mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike): Promise; - - // array with values - mapSeries(values: R[], mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike): Promise; - - - /** - * Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. - * - * If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. - * - * *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.* - */ - // promise of array with promises of value - reduce(values: PromiseLike[]>, reducer: (total: U, current: T, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Promise; - - // promise of array with values - reduce(values: PromiseLike, reducer: (total: U, current: T, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Promise; - - // array with promises of value - reduce(values: PromiseLike[], reducer: (total: U, current: T, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Promise; - - // array with values - reduce(values: T[], reducer: (total: U, current: T, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Promise; - - /** - * Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. - * - * The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result. - * - * *The original array is not modified. - */ - // promise of array with promises of value - filter(values: PromiseLike[]>, filterer: (item: T, index: number, arrayLength: number) => boolean | PromiseLike, option?: Promise.ConcurrencyOption): Promise; - - // promise of array with values - filter(values: PromiseLike, filterer: (item: T, index: number, arrayLength: number) => boolean | PromiseLike, option?: Promise.ConcurrencyOption): Promise; - - // array with promises of value - filter(values: PromiseLike[], filterer: (item: T, index: number, arrayLength: number) => boolean | PromiseLike, option?: Promise.ConcurrencyOption): Promise; - - // array with values - filter(values: T[], filterer: (item: T, index: number, arrayLength: number) => boolean | PromiseLike, option?: Promise.ConcurrencyOption): Promise; - - /** - * Iterate over an array, or a promise of an array, which contains promises (or a mix of promises and values) with the given iterator function with the signature (item, index, value) where item is the resolved value of a respective promise in the input array. Iteration happens serially. If any promise in the input array is rejected the returned promise is rejected as well. - * - * Resolves to the original array unmodified, this method is meant to be used for side effects. If the iterator function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. - */ - // promise of array with promises of value - each(values: PromiseLike[]>, iterator: (item: T, index: number, arrayLength: number) => U | PromiseLike): Promise; - // array with promises of value - each(values: PromiseLike[], iterator: (item: T, index: number, arrayLength: number) => U | PromiseLike): Promise; - // array with values OR promise of array with values - each(values: T[] | PromiseLike, iterator: (item: T, index: number, arrayLength: number) => U | PromiseLike): Promise; -} - -interface Promise extends PromiseLike, Promise.Inspection { - /** - * Promises/A+ `.then()` with progress handler. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. - */ - then(onFulfill: (value: T) => U | PromiseLike, onReject?: (error: any) => U | PromiseLike, onProgress?: (note: any) => any): Promise; - then(onFulfill: (value: T) => U | PromiseLike, onReject?: (error: any) => void | PromiseLike, onProgress?: (note: any) => any): Promise; - - /** - * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. - * - * Alias `.caught();` for compatibility with earlier ECMAScript version. - */ - catch(onReject?: (error: any) => T | PromiseLike | void | PromiseLike): Promise; - caught(onReject?: (error: any) => T | PromiseLike | void | PromiseLike): Promise; - - catch(onReject?: (error: any) => U | PromiseLike): Promise; - caught(onReject?: (error: any) => U | PromiseLike): Promise; - - /** - * This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called. - * - * This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called. - * - * Alias `.caught();` for compatibility with earlier ECMAScript version. - */ - catch(predicate: (error: any) => boolean, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Promise; - caught(predicate: (error: any) => boolean, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Promise; - - catch(predicate: (error: any) => boolean, onReject: (error: any) => U | PromiseLike): Promise; - caught(predicate: (error: any) => boolean, onReject: (error: any) => U | PromiseLike): Promise; - - catch(ErrorClass: Function, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Promise; - caught(ErrorClass: Function, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Promise; - - catch(ErrorClass: Function, onReject: (error: any) => U | PromiseLike): Promise; - caught(ErrorClass: Function, onReject: (error: any) => U | PromiseLike): Promise; - - - /** - * Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections. - */ - error(onReject: (reason: any) => PromiseLike): Promise; - error(onReject: (reason: any) => U): Promise; - - /** - * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler. - * - * Alias `.lastly();` for compatibility with earlier ECMAScript version. - */ - finally(handler: () => U | PromiseLike): Promise; - - lastly(handler: () => U | PromiseLike): Promise; - - /** - * Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise. - */ - bind(thisArg: any): Promise; - - /** - * Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error. - */ - done(onFulfilled?: (value: T) => PromiseLike, onRejected?: (error: any) => U | PromiseLike, onProgress?: (note: any) => any): void; - done(onFulfilled?: (value: T) => U, onRejected?: (error: any) => U | PromiseLike, onProgress?: (note: any) => any): void; - - /** - * Like `.finally()`, but not called for rejections. - */ - tap(onFulFill: (value: T) => U | PromiseLike): Promise; - - /** - * Shorthand for `.then(null, null, handler);`. Attach a progress handler that will be called if this promise is progressed. Returns a new promise chained from this promise. - */ - progressed(handler: (note: any) => any): Promise; - - /** - * Same as calling `Promise.delay(this, ms)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - delay(ms: number): Promise; - - /** - * Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. However, if this promise is not fulfilled or rejected within `ms` milliseconds, the returned promise is rejected with a `Promise.TimeoutError` instance. - * - * You may specify a custom error message with the `message` parameter. - */ - timeout(ms: number, message?: string): Promise; - - /** - * Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success. - * Returns back this promise instead of creating a new one. If the `callback` argument is not a function, this method does not do anything. - */ - nodeify(callback: (err: any, value?: T) => void, options?: Promise.SpreadOption): Promise; - nodeify(...sink: any[]): Promise; - - /** - * Marks this promise as cancellable. Promises by default are not cancellable after v0.11 and must be marked as such for `.cancel()` to have any effect. Marking a promise as cancellable is infectious and you don't need to remark any descendant promise. - */ - cancellable(): Promise; - - /** - * Cancel this promise. The cancellation will propagate to farthest cancellable ancestor promise which is still pending. - * - * That ancestor will then be rejected with a `CancellationError` (get a reference from `Promise.CancellationError`) object as the rejection reason. - * - * In a promise rejection handler you may check for a cancellation by seeing if the reason object has `.name === "Cancel"`. - * - * Promises are by default not cancellable. Use `.cancellable()` to mark a promise as cancellable. - */ - // TODO what to do with this? - cancel(reason?: any): Promise; - - /** - * Like `.then()`, but cancellation of the the returned promise or any of its descendant will not propagate cancellation to this promise or this promise's ancestors. - */ - fork(onFulfilled?: (value: T) => U | PromiseLike, onRejected?: (error: any) => U | PromiseLike, onProgress?: (note: any) => any): Promise; - - /** - * Create an uncancellable promise based on this promise. - */ - uncancellable(): Promise; - - /** - * See if this promise can be cancelled. - */ - isCancellable(): boolean; - - /** - * See if this `promise` has been fulfilled. + * See if the underlying promise was fulfilled at the creation time of this inspection object. */ isFulfilled(): boolean; /** - * See if this `promise` has been rejected. + * See if the underlying promise was rejected at the creation time of this inspection object. */ isRejected(): boolean; /** - * See if this `promise` is still defer. + * See if the underlying promise was cancelled at the creation time of this inspection object. + */ + isCancelled(): boolean; + + /** + * See if the underlying promise was defer at the creation time of this inspection object. */ isPending(): boolean; /** - * See if this `promise` is resolved -> either fulfilled or rejected. - */ - isResolved(): boolean; - - /** - * Get the fulfillment value of the underlying promise. Throws if the promise isn't fulfilled yet. + * Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object. * * throws `TypeError` */ - value(): T; + value(): R; /** - * Get the rejection reason for the underlying promise. Throws if the promise isn't rejected yet. + * Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object. * * throws `TypeError` */ reason(): any; + } - /** - * Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of the promise as snapshotted at the time of calling `.inspect()`. - */ - inspect(): Promise.Inspection; + /** + * Returns a new independent copy of the Bluebird library. + * + * This method should be used before you use any of the methods which would otherwise alter the global Bluebird object - to avoid polluting global state. + */ + export function getNewLibraryCopy(): typeof Bluebird; - /** - * This is a convenience method for doing: - * - * - * promise.then(function(obj){ - * return obj[propertyName].call(obj, arg...); - * }); - * - */ - call(propertyName: string, ...args: any[]): Promise; + /** + * This is relevant to browser environments with no module loader. + * + * Release control of the Promise namespace to whatever it was before this library was loaded. Returns a reference to the library namespace so you can attach it to something else. + */ + export function noConflict(): typeof Bluebird; - /** - * This is a convenience method for doing: - * - * - * promise.then(function(obj){ - * return obj[propertyName]; - * }); - * - */ - // TODO find way to fix get() - // get(propertyName: string): Promise; - - /** - * Convenience method for: - * - * - * .then(function() { - * return value; - * }); - * - * - * in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()` - * - * Alias `.thenReturn();` for compatibility with earlier ECMAScript version. - */ - return(): Promise; - thenReturn(): Promise; - return(value: U): Promise; - thenReturn(value: U): Promise; - - /** - * Convenience method for: - * - * - * .then(function() { - * throw reason; - * }); - * - * Same limitations apply as with `.return()`. - * - * Alias `.thenThrow();` for compatibility with earlier ECMAScript version. - */ - throw(reason: Error): Promise; - thenThrow(reason: Error): Promise; - - /** - * Convert to String. - */ - toString(): string; - - /** - * This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`. - */ - toJSON(): Object; - - /** - * Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers. - */ - // TODO how to model instance.spread()? like Q? - spread(onFulfill: Function, onReject?: (reason: any) => U | PromiseLike): Promise; - /* - // TODO or something like this? - spread(onFulfill: (...values: W[]) => PromiseLike, onReject?: (reason: any) => PromiseLike): Promise; - spread(onFulfill: (...values: W[]) => PromiseLike, onReject?: (reason: any) => U): Promise; - spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => PromiseLike): Promise; - spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => U): Promise; - */ - /** - * Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - all(): Promise; - - /** - * Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO how to model instance.props()? - props(): Promise; - - /** - * Same as calling `Promise.settle(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - settle(): Promise[]>; - - /** - * Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - any(): Promise; - - /** - * Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - some(count: number): Promise; - - /** - * Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - race(): Promise; - - /** - * Same as calling `Promise.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - map(mapper: (item: Q, index: number, arrayLength: number) => U | PromiseLike, options?: Promise.ConcurrencyOption): Promise; - - /** - * Same as `Promise.mapSeries(thisPromise, mapper)`. - */ - // TODO type inference from array-resolving promise? - mapSeries(mapper: (item: Q, index: number, arrayLength: number) => U | PromiseLike): Promise; - - /** - * Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Promise; - - /** - * Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - filter(filterer: (item: U, index: number, arrayLength: number) => boolean | PromiseLike, options?: Promise.ConcurrencyOption): Promise; - - /** - * Same as calling ``Promise.each(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - each(iterator: (item: T, index: number, arrayLength: number) => U | PromiseLike): Promise; + /** + * Changes how bluebird schedules calls a-synchronously. + * + * @param scheduler Should be a function that asynchronously schedules + * the calling of the passed in function + */ + export function setScheduler(scheduler: (callback: (...args: any[]) => void) => void): void; } -/** - * Don't use variable namespace such as variables, functions, and classes. - * If you use this namespace, it will conflict in es6. - */ -declare namespace Promise { - export interface RangeError extends Error { - } - export interface CancellationError extends Error { - } - export interface TimeoutError extends Error { - } - export interface TypeError extends Error { - } - export interface RejectionError extends Error { - } - export interface OperationalError extends Error { - } - - export interface ConcurrencyOption { - concurrency: number; - } - export interface SpreadOption { - spread: boolean; - } - export interface PromisifyAllOptions { - suffix?: string; - filter?: (name: string, func: Function, target?: any, passesDefaultFilter?: boolean) => boolean; - // The promisifier gets a reference to the original method and should return a function which returns a promise - promisifier?: (originalMethod: Function) => () => PromiseLike; - } - - export interface Resolver { - /** - * Returns a reference to the controlled promise that can be passed to clients. - */ - promise: Promise; - - /** - * Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state. - */ - resolve(value: T): void; - resolve(): void; - - /** - * Reject the underlying promise with `reason` as the rejection reason. - */ - reject(reason: any): void; - - /** - * Progress the underlying promise with `value` as the progression value. - */ - progress(value: any): void; - - /** - * Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions. - * - * If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values. - */ - // TODO specify resolver callback - callback: (err: any, value: T, ...values: T[]) => void; - } - - export interface Inspection { - /** - * See if the underlying promise was fulfilled at the creation time of this inspection object. - */ - isFulfilled(): boolean; - - /** - * See if the underlying promise was rejected at the creation time of this inspection object. - */ - isRejected(): boolean; - - /** - * See if the underlying promise was defer at the creation time of this inspection object. - */ - isPending(): boolean; - - /** - * Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object. - * - * throws `TypeError` - */ - value(): T; - - /** - * Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object. - * - * throws `TypeError` - */ - reason(): any; - } -} - -declare module 'bluebird' { - export = Promise; +export = Bluebird; } diff --git a/bookshelf/bookshelf.d.ts b/bookshelf/bookshelf.d.ts index 0ca3a1ebcd..34f58d62ed 100644 --- a/bookshelf/bookshelf.d.ts +++ b/bookshelf/bookshelf.d.ts @@ -3,7 +3,7 @@ // Definitions by: Andrew Schurman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /// /// /// diff --git a/bootbox/bootbox.d.ts b/bootbox/bootbox.d.ts index ce422de880..c94b60625f 100644 --- a/bootbox/bootbox.d.ts +++ b/bootbox/bootbox.d.ts @@ -9,7 +9,7 @@ interface BootboxBaseOptions { title?: string | Element; callback?: (result: boolean | string) => any; - onEscape?: () => any | boolean; + onEscape?: (() => any) | boolean; show?: boolean; backdrop?: boolean; closeButton?: boolean; diff --git a/bootstrap.datepicker/bootstrap.datepicker-tests.ts b/bootstrap-datepicker/bootstrap-datepicker-tests.ts similarity index 98% rename from bootstrap.datepicker/bootstrap.datepicker-tests.ts rename to bootstrap-datepicker/bootstrap-datepicker-tests.ts index b275ee25a8..d290a5b8fa 100644 --- a/bootstrap.datepicker/bootstrap.datepicker-tests.ts +++ b/bootstrap-datepicker/bootstrap-datepicker-tests.ts @@ -1,4 +1,4 @@ -/// +/// function tests_simple() { $('#datepicker').datepicker(); diff --git a/bootstrap.datepicker/bootstrap.datepicker.d.ts b/bootstrap-datepicker/bootstrap-datepicker.d.ts similarity index 98% rename from bootstrap.datepicker/bootstrap.datepicker.d.ts rename to bootstrap-datepicker/bootstrap-datepicker.d.ts index f60a0ffed6..1a2bb2124b 100644 --- a/bootstrap.datepicker/bootstrap.datepicker.d.ts +++ b/bootstrap-datepicker/bootstrap-datepicker.d.ts @@ -1,4 +1,4 @@ -// Type definitions for bootstrap.datepicker +// Type definitions for bootstrap-datepicker // Project: https://github.com/eternicode/bootstrap-datepicker // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/bowser/bowser-tests.ts b/bowser/bowser-tests.ts index 2f7cb8904c..79a846f3fb 100644 --- a/bowser/bowser-tests.ts +++ b/bowser/bowser-tests.ts @@ -7,3 +7,13 @@ Bowser.test(['msie']) === true; Bowser.a === Bowser.c; Bowser.osversion > 10; Bowser.osversion === '10.1A'; + +bowser.msedge === true; +bowser.test(['msie']) === true; +bowser.a === bowser.c; +bowser.osversion > 10; +bowser.osversion === '10.1A'; +bowser.compareVersions(['9.0', '10']); +bowser() === {android: true, x: true}; +bowser.check({msie: "11"}, window.navigator.userAgent); +bowser.isUnsupportedBrowser({msie: "10"}, window.navigator.userAgent); \ No newline at end of file diff --git a/bowser/bowser.d.ts b/bowser/bowser.d.ts index 2bf1b3d510..4d1840ff6a 100644 --- a/bowser/bowser.d.ts +++ b/bowser/bowser.d.ts @@ -3,52 +3,104 @@ // Definitions by: Paulo Cesar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare var bowser: BowserModule.IBowser; + declare module 'bowser' { - var def: BowserModule.IBowser; - export = def; + export = bowser; } declare namespace BowserModule { - export interface IBowserUA { - msie: boolean; + export interface IBowserOS { + mac: boolean; + /**other than Windows Phone */ + windows: boolean; + windowsphone: boolean; + /**other than android, chromeos, webos, tizen, and sailfish */ + linux: boolean; + chromeos: boolean; + android: boolean; + /** also sets one of iphone/ipad/ipod */ + ios: boolean; + blackberry: boolean; + firefoxos: boolean; + /** may also set touchpad */ + webos: boolean; + bada: boolean; + tizen: boolean; + sailfish: boolean; + } + + export interface IBowserVersions { chrome: boolean; - webkit: boolean; - phantom: boolean; - opera: boolean; + firefox: boolean; + msie: boolean; + msedge: boolean; safari: boolean; android: boolean; ios: boolean; - webos: boolean; - msedge: boolean; - seamonkey: boolean; - firefox: boolean; - yandexbrowser: boolean; + opera: boolean; + phantom: boolean; blackberry: boolean; - tablet: boolean; - mobile: boolean; + webos: boolean; silk: boolean; bada: boolean; tizen: boolean; - windowsphone: boolean; - firefoxos: boolean; - gecko: boolean; + seamonkey: boolean; sailfish: boolean; - chromeBook: boolean; + ucbrowser: boolean; + qupzilla: boolean; + vivaldi: boolean; + sleipnir: boolean; + kMeleon: boolean; + } + + export interface IBowserEngines { + /** IE <= 11 */ + msie: boolean; + /**Chrome 0-27, Android <4.4, iOs, BB, etc. */ + webkit: boolean; + /**Chrome >=28, Android >=4.4, Opera, etc. */ + blink: boolean; + /**Firefox, etc. */ + gecko: boolean; + /** IE > 11 */ + msedge: boolean; + /** If a tablet device is detected, the flag tablet is set instead of mobile. */ + tablet: boolean; + /** All detected mobile OSes are additionally flagged mobile, unless it's a tablet */ + mobile: boolean; + + } + + export interface IBowserGrade { /** Grade A browser */ a: boolean; /** Grade C browser */ c: boolean; /** Grade X browser */ x: boolean; + /**A human readable name for this browser. E.g. 'Chrome', '' */ name: string; + /**Version number for the browser. E.g. '32.0' */ version: string|number; osversion: string|number; } - export interface IBowser extends IBowserUA { + export interface IBowserDetection extends IBowserGrade, IBowserEngines, IBowserOS, IBowserVersions { } + + export interface IBowserMinVersions { + // { msie: "11", "firefox": "4" } + [index: string]: string; + } + + export interface IBowser extends IBowserDetection { + (): IBowserDetection; test(browserList: string[]): boolean; _detect(ua: string): IBowser; + compareVersions(versions: string[]): number; + check(minVersions: IBowserMinVersions, strictMode?: boolean|string, ua?: string): Boolean; + isUnsupportedBrowser(minVersions: IBowserMinVersions, strictMode?: boolean|string, ua?: string): boolean; } } diff --git a/chroma-js/chroma-js-tests.ts b/chroma-js/chroma-js-tests.ts index ccc9d5a1a7..a994af975f 100644 --- a/chroma-js/chroma-js-tests.ts +++ b/chroma-js/chroma-js-tests.ts @@ -1,5 +1,7 @@ /// +import * as myChroma from "chroma-js"; + function test_chroma() { chroma('hotpink'); chroma('#ff3399'); @@ -41,6 +43,9 @@ function test_chroma() { chroma.limits(data, 'e', 5); chroma.limits(data, 'q', 5); chroma.limits(data, 'k', 5); + + myChroma(0xff3399); + myChroma.limits(data, 'k', 5); } function test_color() { @@ -99,6 +104,10 @@ function test_color() { chroma('#cbdbff').temperature(); chroma('#b3ccff').temperature(); chroma('33cc00').gl(); + + myChroma('teal').alpha(0.5).css(); + myChroma('teal').css('hsl'); + myChroma('orange').rgb(); } function test_scale() { @@ -163,4 +172,17 @@ function test_scale() { chroma.scale('OrRd').classes(5); chroma.scale('OrRd').classes(8); -} \ No newline at end of file + + myChroma.cubehelix() + .start(200) + .rotations(-0.35) + .gamma(0.7) + .lightness([0.3, 0.8]) + .scale() // convert to chroma.scale + + .correctLightness() + .colors(5); + + myChroma.scale('RdYlBu'); + myChroma.scale('RdYlBu').padding(0.15); +} diff --git a/chroma-js/chroma-js.d.ts b/chroma-js/chroma-js.d.ts index 654c4d8cef..e3f463d368 100644 --- a/chroma-js/chroma-js.d.ts +++ b/chroma-js/chroma-js.d.ts @@ -263,3 +263,7 @@ declare namespace Chroma { } declare var chroma: Chroma.ChromaStatic; + +declare module "chroma-js" { + export = chroma; +} diff --git a/consolidate/consolidate.d.ts b/consolidate/consolidate.d.ts index ff54a83a8e..aa07150f20 100644 --- a/consolidate/consolidate.d.ts +++ b/consolidate/consolidate.d.ts @@ -6,7 +6,7 @@ // Imported from: https://github.com/soywiz/typescript-node-definitions/consolidate.d.ts /// -/// +/// declare module "consolidate" { var cons: Consolidate; diff --git a/cordova/cordova-tests.ts b/cordova/cordova-tests.ts index 7e97305a25..6d98471b12 100644 --- a/cordova/cordova-tests.ts +++ b/cordova/cordova-tests.ts @@ -126,12 +126,27 @@ function fsaccessor(fs: FileSystem) { (err: FileError)=> { alert('Error: ' + err.code); }); } + + +//---------------------------------------------------------------------- +// FileSystem plugin +// +//cordova states that the enums for requestFileSystem live on LocalFileSystem +// window.requestFileSystem( - window.TEMPORARY, + LocalFileSystem.TEMPORARY, 1024 * 1024 * 5, fsaccessor, (err: FileError) => { alert('Error: ' + err.code); } ); +window.requestFileSystem( + LocalFileSystem.PERSISTENT, + 1024 * 1024 * 5, + fsaccessor, + (err: FileError) => { alert('Error: ' + err.code); } +); +// FileSystem plugin +//---------------------------------------------------------------------- window.resolveLocalFileSystemURI(cordova.file.applicationDirectory, (entry: Entry)=> { diff --git a/cordova/plugins/Contacts.d.ts b/cordova/plugins/Contacts.d.ts index d940fccd77..90b21ae2bb 100644 --- a/cordova/plugins/Contacts.d.ts +++ b/cordova/plugins/Contacts.d.ts @@ -42,6 +42,40 @@ interface Contacts { */ pickContact(onSuccess: (contact: Contact) => void, onError: (error: ContactError) => void): void + + /** + * This allows us to use an enumeration when setting the desired fields for the ContactFindOptions. + * The values will correspond to the type of string literals in ContactFieldType. + */ + fieldType: { + addresses: "addresses", + birthday: "birthday", + categories: "categories", + country: "country", + department: "department", + displayName: "displayName", + emails: "emails", + familyName: "familyName", + formatted: "formatted", + givenName: "givenName", + honorificPrefix: "honorificPrefix", + honorificSuffix: "honorificSuffix", + id: "id", + ims: "ims", + locality: "locality", + middleName: "middleName", + name: "name", + nickname: "nickname", + note: "note", + organizations: "organizations", + phoneNumbers: "phoneNumbers", + photos: "photos", + postalCode: "postalCode", + region: "region", + streetAddress: "streetAddress", + title: "title", + urls: "urls" + } } interface ContactProperties { @@ -105,7 +139,7 @@ interface Contact extends ContactProperties { declare var Contact: { /** Constructor of Contact object */ - new(id?: string, + new (id?: string, displayName?: string, name?: ContactName, nickname?: string, @@ -130,7 +164,7 @@ interface ContactError { } declare var ContactError: { - new(code: number): ContactError; + new (code: number): ContactError; UNKNOWN_ERROR: number; INVALID_ARGUMENT_ERROR: number; TIMEOUT_ERROR: number; @@ -158,7 +192,7 @@ interface ContactName { declare var ContactName: { /** Constructor for ContactName object */ - new(formatted?: string, + new (formatted?: string, familyName?: string, givenName?: string, middleName?: string, @@ -189,7 +223,7 @@ interface ContactField { declare var ContactField: { /** Constructor for ContactField object */ - new(type?: string, + new (type?: string, value?: string, pref?: boolean): ContactField }; @@ -219,7 +253,7 @@ interface ContactAddress { declare var ContactAddress: { /** Constructor of ContactAddress object */ - new(pref?: boolean, + new (pref?: boolean, type?: string, formatted?: string, streetAddress?: string, @@ -248,7 +282,7 @@ interface ContactOrganization { declare var ContactOrganization: { /** Constructor for ContactOrganization object */ - new(pref?: boolean, + new (pref?: boolean, type?: string, name?: string, department?: string, @@ -262,12 +296,42 @@ interface ContactFindOptions { /** Determines if the find operation returns multiple navigator.contacts. */ multiple?: boolean; /* Contact fields to be returned back. If specified, the resulting Contact object only features values for these fields. */ - desiredFields?: string[]; + desiredFields?: ContactFieldType[]; } +/** these are the string values that are valid for the desired fields in ContactFindOptions */ +declare type ContactFieldType = + "addresses" + | "birthday" + | "categories" + | "country" + | "department" + | "displayName" + | "emails" + | "familyName" + | "formatted" + | "givenName" + | "honorificPrefix" + | "honorificSuffix" + | "id" + | "ims" + | "locality" + | "middleName" + | "name" + | "nickname" + | "note" + | "organizations" + | "phoneNumbers" + | "photos" + | "postalCode" + | "region" + | "streetAddress" + | "title" + | "urls"; + declare var ContactFindOptions: { /** Constructor for ContactFindOptions object */ - new(filter?: string, + new (filter?: string, multiple?: boolean, - desiredFields?: string[]): ContactFindOptions -}; \ No newline at end of file + desiredFields?: ContactFieldType[]): ContactFindOptions +}; diff --git a/cordova/plugins/FileSystem.d.ts b/cordova/plugins/FileSystem.d.ts index 66a6014dea..f9471eda72 100644 --- a/cordova/plugins/FileSystem.d.ts +++ b/cordova/plugins/FileSystem.d.ts @@ -15,7 +15,7 @@ interface Window { * @param errorCallback A callback that is called when errors happen, or when the request to obtain the filesystem is denied. */ requestFileSystem( - type: number, + type: LocalFileSystem, size: number, successCallback: (fileSystem: FileSystem) => void, errorCallback?: (fileError: FileError) => void): void; @@ -371,3 +371,8 @@ interface Cordova { } } + +declare enum LocalFileSystem { + PERSISTENT=0, + TEMPORARY=1 +} diff --git a/countdown/countdown-tests.ts b/countdown/countdown-tests.ts index c803f1acc2..3ad8890aab 100644 --- a/countdown/countdown-tests.ts +++ b/countdown/countdown-tests.ts @@ -1,15 +1,15 @@ /// -import { countdown, Timespan, CountdownStatic, Format } from 'countdown'; +import * as countdown from 'countdown'; -let ts: Timespan; +let ts: countdown.Timespan; let interval: number; -ts = countdown(new Date()); -ts = countdown(150); +ts = countdown(new Date()); +ts = countdown(150); interval = countdown(new Date(), - function (ts: Timespan) { + function (ts: countdown.Timespan) { document.getElementById('pageTimer').innerHTML = ts.toHTML('strong'); }, countdown.HOURS | countdown.MINUTES | countdown.SECONDS, diff --git a/countdown/countdown.d.ts b/countdown/countdown.d.ts index 5b40541dd0..bcb0d07976 100644 --- a/countdown/countdown.d.ts +++ b/countdown/countdown.d.ts @@ -3,11 +3,11 @@ // Definitions by: Gabriel Juchault // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'countdown' { - export type DateFunction = (timespan: Timespan) => void; - export type DateTime = number | Date | DateFunction; +declare namespace countdown { + type DateFunction = (timespan: Timespan) => void; + type DateTime = number | Date | DateFunction; - export interface Timespan { + interface Timespan { start?: Date; end?: Date; units?: number; @@ -26,7 +26,7 @@ declare module 'countdown' { toHTML(tagName?: string, label?: string): string; } - export interface Format { + interface Format { singular?: string | Array; plural?: string | Array; last?: string; @@ -36,7 +36,7 @@ declare module 'countdown' { formatter?(value: number, unit: number): string; } - export interface CountdownStatic { + interface CountdownStatic { (start: DateTime, end?: DateTime, units?: number, max?: number, digits?: number): Timespan | number; MILLENNIA: number; CENTURIES: number; @@ -64,6 +64,9 @@ declare module 'countdown' { resetFormat(): void; setFormat(format: Format): void; } +} - export let countdown: CountdownStatic; +declare module 'countdown' { + let countdown: countdown.CountdownStatic; + export = countdown; } diff --git a/daterangepicker/daterangepicker.d.ts b/daterangepicker/daterangepicker.d.ts index f3534a197e..a86614cfe8 100644 --- a/daterangepicker/daterangepicker.d.ts +++ b/daterangepicker/daterangepicker.d.ts @@ -11,7 +11,7 @@ interface JQuery { daterangepicker(settings?: daterangepicker.Settings, callback?: (start?: string | Date | moment.Moment, end?: string | Date | moment.Moment, label?: string) => any): JQuery; } -declare module daterangepicker { +declare namespace daterangepicker { interface DatepickerEventObject extends JQueryEventObject { date: Date; @@ -164,3 +164,7 @@ declare module daterangepicker { monthNames?: string[]; } } + +declare module "daterangepicker" { + export = daterangepicker; +} diff --git a/db-migrate-base/db-migrate-base-tests.ts b/db-migrate-base/db-migrate-base-tests.ts new file mode 100644 index 0000000000..55d471b98f --- /dev/null +++ b/db-migrate-base/db-migrate-base-tests.ts @@ -0,0 +1,322 @@ +// Test file for db-migrate-base Definition file +/// + +import * as DbMigrateBase from "db-migrate-base"; + +// Throw together a dummy driver +let db = {}; + +let callback = (err: any, response: any) => { + // Do nothing. +}; + +/// createTable(tableName, columnSpec, callback) +db.createTable('pets', { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' +}, callback); + +db.createTable('pets', { + columns: { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' + }, + ifNotExists: true +}, callback); + +db.createTable('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: 'id' + } + } +}, callback); + +db.createTable('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + product_id: 'id' + } + } + } +}, callback); + +/// dropTable(tableName, [options,] callback) +db.dropTable('pets', callback); + +db.dropTable('pets', { ifExists: true }, callback); + +/// renameTable(tableName, newTableName, callback) +db.renameTable('pets', 'pets_OLD', callback); + +/// addColumn(tableName, columnName, columnSpec, callback) +db.addColumn('pets', 'eyeColor', { + type: 'string', + length: 25, + notNull: true, +}, callback); + +db.addColumn('pets', 'id', { + type: 'int', + primaryKey: true, + autoIncrement: true, + notNull: true, + unique: true +}, callback); + +/// renameColumn(tableName, oldColumnName, newColumnName, callback) +db.renameColumn('pets', 'id', 'pet_id', callback); + +/// changeColumn(tableName, columnName, columnSpec, callback) +db.changeColumn('pets', 'eye_color', { + type: 'int', + unsigned: true, + notNull: true, + foreignKey: { + name: 'pets_eye_color_id_fk', + table: 'eye_color', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + eye_color: 'id' + } + } +}, callback); + +/// addIndex(tableName, indexName, columns, [unique,] callback) +db.addIndex('pets', 'pets_eye_color_idx', ['eye_color'], callback); +db.addIndex('pets', 'pets_registration_code_idx', ['registration_code'], true, callback); + +/// addForeignKey(tableName, referencedTableName, keyName, fieldMapping, rules, callback) +db.addForeignKey('module_user', 'modules', 'module_user_module_id_fk', +{ + 'module_id': 'id' +}, +{ + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' +}, callback); + +/// removeForeignKey(tableName, keyName, options, callback) +db.removeForeignKey('module_user', 'module_uer_module_id_foreign', callback); +db.removeForeignKey('module_user', 'module_user_module_id_foreign', { + dropIndex: true, +}, callback); + +/// insert(tableName, [columnNameArray,] valueArray, callback) +db.insert('module_user', ['first_name', 'last_name'], ['Test', 'Testerson'], callback); +db.insert('module_user', ['Test', 'Testerson'], callback); + +/// removeIndex([tableName,] indexName, callback) +db.removeIndex('pets', 'pets_eye_color_idx', callback); +db.removeIndex('pets_eye_color_idx', callback); + +/// runSql(sql, [params,] callback) +db.runSql('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [ + 'first_name', 'last_name', + 'Test', 'Testerson' +], callback); +db.runSql('DROP TABLE `pets`', callback); + +/// all(sql, [params,] callback) +db.all('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test'], callback); +db.all('SELECT * FROM `module_user`', callback); + +/// ========= +/// Async +/// ========= + +let onResolve = (result: any) => {}; + +/// createTableAsync(tableName, columnSpec) +db.createTableAsync('pets', { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' +}).then(onResolve); + +db.createTableAsync('pets', { + columns: { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' + }, + ifNotExists: true +}).then(onResolve); + +db.createTableAsync('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: 'id' + } + } +}).then(onResolve); + +db.createTableAsync('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + product_id: 'id' + } + } + } +}).then(onResolve); + +/// dropTableAsync(tableName, [options]) +db.dropTableAsync('pets').then(onResolve); +db.dropTableAsync('pets', { ifExists: true }).then(onResolve); + +/// renameTableAsync(tableName, newTableName) +db.renameTableAsync('pets', 'pets_OLD').then(onResolve); + +/// addColumnAsync(tableName, columnName, columnSpec) +db.addColumnAsync('pets', 'eyeColor', { + type: 'string', + length: 25, + notNull: true, +}).then(onResolve); + +db.addColumnAsync('pets', 'id', { + type: 'int', + primaryKey: true, + autoIncrement: true, + notNull: true, + unique: true +}).then(onResolve); + +/// renameColumnAsync(tableName, oldColumnName, newColumnName) +db.renameColumnAsync('pets', 'id', 'pet_id').then(onResolve); + +/// changeColumnAsync(tableName, columnName, columnSpec) +db.changeColumnAsync('pets', 'eye_color', { + type: 'int', + unsigned: true, + notNull: true, + foreignKey: { + name: 'pets_eye_color_id_fk', + table: 'eye_color', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + eye_color: 'id' + } + } +}).then(onResolve); + +/// addIndexAsync(tableName, indexName, columns, [unique]) +db.addIndexAsync('pets', 'pets_eye_color_idx', ['eye_color']).then(onResolve); +db.addIndexAsync('pets', 'pets_registration_code_idx', ['registration_code'], true).then(onResolve); + +/// addForeignKeyAsync(tableName, referencedTableName, keyName, fieldMapping, rules) +db.addForeignKeyAsync('module_user', 'modules', 'module_user_module_id_fk', +{ + 'module_id': 'id' +}, +{ + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' +}).then(onResolve); + +/// removeForeignKeyAsync(tableName, keyName, options) +db.removeForeignKeyAsync('module_user', 'module_uer_module_id_foreign').then(onResolve); +db.removeForeignKeyAsync('module_user', 'module_user_module_id_foreign', { + dropIndex: true, +}).then(onResolve); + +/// insertAsync(tableName, [columnNameArray,] valueArray) +db.insertAsync('module_user', ['first_name', 'last_name'], ['Test', 'Testerson']).then(onResolve); +db.insertAsync('module_user', ['Test', 'Testerson']).then(onResolve); + +/// removeIndexAsync([tableName,] indexName) +db.removeIndexAsync('pets', 'pets_eye_color_idx').then(onResolve); +db.removeIndexAsync('pets_eye_color_idx').then(onResolve); + +/// runSqlAsync(sql, [params]) +db.runSqlAsync('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [ + 'first_name', 'last_name', + 'Test', 'Testerson' +]).then(onResolve); +db.runSqlAsync('DROP TABLE `pets`').then(onResolve); + +/// allAsync(sql, [params]) +db.allAsync('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test']).then(onResolve); +db.allAsync('SELECT * FROM `module_user`').then(onResolve); \ No newline at end of file diff --git a/db-migrate-base/db-migrate-base.d.ts b/db-migrate-base/db-migrate-base.d.ts new file mode 100644 index 0000000000..d24388fdaf --- /dev/null +++ b/db-migrate-base/db-migrate-base.d.ts @@ -0,0 +1,152 @@ +// Type definitions for db-migrate-base +// Project: https://github.com/db-migrate/db-migrate-base +// Definitions by: nickiannone +// Definitions: https://github.com/nickiannone/DefinitelyTyped + +/// +/// + +declare module "db-migrate-base" { + + import * as Promise from "bluebird"; + + export interface CallbackFunction { (err: any, response: any): void; } + + export interface InternalModule { + log: any; + type: any; + } + + export interface InternalOptions { + mod: InternalModule; + } + + export interface ColumnSpec { + length?: number; + type: string; + unsigned?: boolean; + primaryKey?: boolean; + autoIncrement?: boolean; + notNull?: boolean; + unique?: boolean; + defaultValue?: any; + foreignKey?: ForeignKeySpec; + } + + export interface ForeignKeySpec { + name: string; + table: string; + rules?: ForeignKeyRules; + mapping: string | any; + } + + export interface ForeignKeyRules { + onDelete: string; + onUpdate: string; + } + + export interface RemoveForeignKeyOptions { + dropIndex?: boolean; + } + + export interface ColumnDef { + foreignKey?: any; // TODO Figure this out! + constraints: string; + } + + export interface CreateTableOptions { + columns?: Array; + ifNotExists?: boolean; + } + + export interface DropTableOptions { + ifExists?: boolean; + } + + export class Base { + constructor(intern: InternalOptions); + + close(callback?: CallbackFunction): void; + mapDataType(str: string): string; + truncate(tableName: string, callback: CallbackFunction): void; + checkDBMS(dbms: any, callback: CallbackFunction): void; + createDatabase(...options: any[]): void; + switchDatabase(...options: any[]): void; + dropDatabase(...options: any[]): void; + recurseCallbackArray(foreignKeys: Array, callback: CallbackFunction): void; + bindForeignKey(tableName: string, columnName: string, fkOptions: ForeignKeySpec): (callback: CallbackFunction) => void; + createColumnDef(name: string, spec: ColumnSpec, options?: any): ColumnDef; // TODO Figure out a type for `options`! + //createColumnConstraint(spec: ColumnSpec, options?: any, ...implementationDefinedOptions: any[]): string; + createMigrationsTable(callback: CallbackFunction): void; + createSeedsTable(callback: CallbackFunction): void; + createTable(tableName: string, options: any | CreateTableOptions, callback: CallbackFunction): void; + dropTable(tableName: string, optionsOrCb?: DropTableOptions | CallbackFunction, callback?: CallbackFunction): void; + renameTable(tableName: string, newTableName: string, callback: CallbackFunction): void; + addColumn(tableName: string, columnName: string, columnSpec: ColumnSpec, callback: CallbackFunction): void; + removeColumn(tableName: string, columnName: string, callback: CallbackFunction): void; + renameColumn(tableName: string, oldColumnName: string, newColumnName: string, callback: CallbackFunction): void; + changeColumn(tableName: string, columnName: string, columnSpec: ColumnSpec, callback: CallbackFunction): void; + quoteDDLArr(arr: Array): Array; + quoteArr(arr: Array): Array; + addIndex(tableName: string, indexName: string, columns: string | Array, uniqueOrCb?: boolean | CallbackFunction, callback?: CallbackFunction): void; + insert(tableName: string, columnNameOrValueArray: any, valueArrayOrCb?: any | CallbackFunction, callback?: CallbackFunction): void; + update(tableName: string, columnNameOrValueArray: any, valueArrayOrIds?: any, idsOrCb?: any | CallbackFunction, callback?: CallbackFunction): void; + lookup(tableName: string, column: string, id?: any, callback?: CallbackFunction): void; + removeIndex(tableNameOrIndexName: string, indexNameOrCb?: string | CallbackFunction, callback?: CallbackFunction): void; + addForeignKey(tableName: string, referencedTableName: string, keyName: string, fieldMapping: any, rules: ForeignKeyRules, callback: CallbackFunction): void; + removeForeignKey(tableName: string, keyName: string, optionsOrCb?: RemoveForeignKeyOptions | CallbackFunction, callback?: CallbackFunction): void; + normalizeColumnSpec(spec: string | ColumnSpec): ColumnSpec; + addMigrationRecord(name: string, callback: CallbackFunction): void; + addSeedRecord(name: string, callback: CallbackFunction): void; + startMigration(callback: CallbackFunction): void; + endMigration(callback: CallbackFunction): void; + runSql(sql?: string, paramsOrCb?: Array | CallbackFunction, callback?: CallbackFunction): void; + allLoadedMigrations(callback: CallbackFunction): void; + allLoadedSeeds(callback: CallbackFunction): void; + deleteMigration(migrationName: string, callback: CallbackFunction): void; + remove(table: string, ids: any, callback: CallbackFunction): void; // TODO Make ids match the type of ids in buildWhereClause(ids); + buildWhereClause(ids: any): string; + deleteSeed(seedName: string, callback: CallbackFunction): void; + all(sql: string, paramsOrCb?: Array | CallbackFunction, callback?: CallbackFunction): void; + escape(str: string): string; + escapeString(str: string): string; + escapeDDL(str: string): string; + + // Promisified methods + closeAsync(): Promise; + truncateAsync(tableName: string): Promise; + checkDBMSAsync(dbms: any): Promise; + createDatabaseAsync(...options: any[]): Promise; + switchDatabaseAsync(...options: any[]): Promise; + dropDatabaseAsync(...options: any[]): Promise; + recurseCallbackArrayAsync(foreignKeys: Array): Promise; + createMigrationsTableAsync(): Promise; + createSeedsTableAsync(): Promise; + createTableAsync(tableName: string, options: any | CreateTableOptions): Promise; + dropTableAsync(tableName: string, options?: DropTableOptions): Promise; + renameTableAsync(tableName: string, newTableName: string): Promise; + addColumnAsync(tableName: string, columnName: string, columnSpec: ColumnSpec): Promise; + removeColumnAsync(tableName: string, columnName: string): Promise; + renameColumnAsync(tableName: string, oldColumnName: string, newColumnName: string): Promise; + changeColumnAsync(tableName: string, columnName: string, columnSpec: ColumnSpec): Promise; + addIndexAsync(tableName: string, indexName: string, columns: string | Array, unique?: boolean): Promise; + insertAsync(tableName: string, columnNameOrValueArray: any, valueArrayOrCb?: any | CallbackFunction, callback?: CallbackFunction): Promise; + updateAsync(tableName: string, columnNameOrValueArray: any, valueArrayOrIds?: any, idsOrCb?: any | CallbackFunction, callback?: CallbackFunction): Promise; + lookupAsync(tableName: string, column: string, id?: any, callback?: CallbackFunction): Promise; + removeIndexAsync(tableNameOrIndexName: string, indexName?: string): Promise; + addForeignKeyAsync(tableName: string, referencedTableName: string, keyName: string, fieldMapping: any, rules: ForeignKeyRules): Promise; + removeForeignKeyAsync(tableName: string, keyName: string, options?: RemoveForeignKeyOptions): Promise; + addMigrationRecordAsync(name: string): Promise; + addSeedRecordAsync(name: string): Promise; + startMigrationAsync(): Promise; + endMigrationAsync(callback: CallbackFunction): Promise; + runSqlAsync(sql?: string, params?: Array): Promise; + allLoadedMigrationsAsync(): Promise; + allLoadedSeedsAsync(): Promise; + deleteMigrationAsync(migrationName: string): Promise; + removeAsync(table: string, ids: any): Promise; + deleteSeedAsync(seedName: string): Promise; + allAsync(sql: string, params?: Array): Promise; + } + +} \ No newline at end of file diff --git a/db-migrate-pg/db-migrate-pg-tests.ts b/db-migrate-pg/db-migrate-pg-tests.ts new file mode 100644 index 0000000000..3878c54607 --- /dev/null +++ b/db-migrate-pg/db-migrate-pg-tests.ts @@ -0,0 +1,411 @@ +// Test file for db-migrate-pg Definition file +/// + +import * as DbMigratePg from "db-migrate-pg"; + +// Throw together a dummy driver +let db = {}; + +let callback = (err: any, response: any) => { + // Do nothing. +}; + +/// createTable(tableName, columnSpec, callback) +db.createTable('pets', { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' +}, callback); + +db.createTable('pets', { + columns: { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' + }, + ifNotExists: true +}, callback); + +db.createTable('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: 'id' + } + } +}, callback); + +db.createTable('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + product_id: 'id' + } + } + } +}, callback); + +/// dropTable(tableName, [options,] callback) +db.dropTable('pets', callback); + +db.dropTable('pets', { ifExists: true }, callback); + +/// renameTable(tableName, newTableName, callback) +db.renameTable('pets', 'pets_OLD', callback); + +/// addColumn(tableName, columnName, columnSpec, callback) +db.addColumn('pets', 'eyeColor', { + type: 'string', + length: 25, + notNull: true, +}, callback); + +db.addColumn('pets', 'id', { + type: 'int', + primaryKey: true, + autoIncrement: true, + notNull: true, + unique: true +}, callback); + +/// renameColumn(tableName, oldColumnName, newColumnName, callback) +db.renameColumn('pets', 'id', 'pet_id', callback); + +/// changeColumn(tableName, columnName, columnSpec, callback) +db.changeColumn('pets', 'eye_color', { + type: 'int', + unsigned: true, + notNull: true, + foreignKey: { + name: 'pets_eye_color_id_fk', + table: 'eye_color', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + eye_color: 'id' + } + } +}, callback); + +/// addIndex(tableName, indexName, columns, [unique,] callback) +db.addIndex('pets', 'pets_eye_color_idx', ['eye_color'], callback); +db.addIndex('pets', 'pets_registration_code_idx', ['registration_code'], true, callback); + +/// addForeignKey(tableName, referencedTableName, keyName, fieldMapping, rules, callback) +db.addForeignKey('module_user', 'modules', 'module_user_module_id_fk', +{ + 'module_id': 'id' +}, +{ + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' +}, callback); + +/// removeForeignKey(tableName, keyName, options, callback) +db.removeForeignKey('module_user', 'module_uer_module_id_foreign', callback); +db.removeForeignKey('module_user', 'module_user_module_id_foreign', { + dropIndex: true, +}, callback); + +/// insert(tableName, [columnNameArray,] valueArray, callback) +db.insert('module_user', ['first_name', 'last_name'], ['Test', 'Testerson'], callback); +db.insert('module_user', ['Test', 'Testerson'], callback); + +/// removeIndex([tableName,] indexName, callback) +db.removeIndex('pets', 'pets_eye_color_idx', callback); +db.removeIndex('pets_eye_color_idx', callback); + +/// runSql(sql, [params,] callback) +db.runSql('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [ + 'first_name', 'last_name', + 'Test', 'Testerson' +], callback); +db.runSql('DROP TABLE `pets`', callback); + +/// all(sql, [params,] callback) +db.all('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test'], callback); +db.all('SELECT * FROM `module_user`', callback); + +/// ========= +/// Async +/// ========= + +let onResolve = (result: any) => {}; + +/// createTableAsync(tableName, columnSpec) +db.createTableAsync('pets', { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' +}).then(onResolve); + +db.createTableAsync('pets', { + columns: { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' + }, + ifNotExists: true +}).then(onResolve); + +db.createTableAsync('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: 'id' + } + } +}).then(onResolve); + +db.createTableAsync('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + product_id: 'id' + } + } + } +}).then(onResolve); + +/// dropTableAsync(tableName, [options]) +db.dropTableAsync('pets').then(onResolve); +db.dropTableAsync('pets', { ifExists: true }).then(onResolve); + +/// renameTableAsync(tableName, newTableName) +db.renameTableAsync('pets', 'pets_OLD').then(onResolve); + +/// addColumnAsync(tableName, columnName, columnSpec) +db.addColumnAsync('pets', 'eyeColor', { + type: 'string', + length: 25, + notNull: true, +}).then(onResolve); + +db.addColumnAsync('pets', 'id', { + type: 'int', + primaryKey: true, + autoIncrement: true, + notNull: true, + unique: true +}).then(onResolve); + +/// renameColumnAsync(tableName, oldColumnName, newColumnName) +db.renameColumnAsync('pets', 'id', 'pet_id').then(onResolve); + +/// changeColumnAsync(tableName, columnName, columnSpec) +db.changeColumnAsync('pets', 'eye_color', { + type: 'int', + unsigned: true, + notNull: true, + foreignKey: { + name: 'pets_eye_color_id_fk', + table: 'eye_color', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + eye_color: 'id' + } + } +}).then(onResolve); + +/// addIndexAsync(tableName, indexName, columns, [unique]) +db.addIndexAsync('pets', 'pets_eye_color_idx', ['eye_color']).then(onResolve); +db.addIndexAsync('pets', 'pets_registration_code_idx', ['registration_code'], true).then(onResolve); + +/// addForeignKeyAsync(tableName, referencedTableName, keyName, fieldMapping, rules) +db.addForeignKeyAsync('module_user', 'modules', 'module_user_module_id_fk', +{ + 'module_id': 'id' +}, +{ + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' +}).then(onResolve); + +/// removeForeignKeyAsync(tableName, keyName, options) +db.removeForeignKeyAsync('module_user', 'module_uer_module_id_foreign').then(onResolve); +db.removeForeignKeyAsync('module_user', 'module_user_module_id_foreign', { + dropIndex: true, +}).then(onResolve); + +/// insertAsync(tableName, [columnNameArray,] valueArray) +db.insertAsync('module_user', ['first_name', 'last_name'], ['Test', 'Testerson']).then(onResolve); +db.insertAsync('module_user', ['Test', 'Testerson']).then(onResolve); + +/// removeIndexAsync([tableName,] indexName) +db.removeIndexAsync('pets', 'pets_eye_color_idx').then(onResolve); +db.removeIndexAsync('pets_eye_color_idx').then(onResolve); + +/// runSqlAsync(sql, [params]) +db.runSqlAsync('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [ + 'first_name', 'last_name', + 'Test', 'Testerson' +]).then(onResolve); +db.runSqlAsync('DROP TABLE `pets`').then(onResolve); + +/// allAsync(sql, [params]) +db.allAsync('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test']).then(onResolve); +db.allAsync('SELECT * FROM `module_user`').then(onResolve); + +/// ==================== +/// PG-specific tests +/// ==================== + +/// createColumnConstraint(spec, options, tableName, columnName) (INTERNAL USE ONLY) +let constraint: DbMigratePg.ColumnConstraint; + +constraint = db.createColumnConstraint({ + type: 'int', + length: 10, + unsigned: true, + primaryKey: false, + autoIncrement: false, + notNull: true, + unique: false, + defaultValue: 0, + foreignKey: { + name: 'pets_eye_color_id_fk', + table: 'eye_color', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + 'eye_color': 'id' + } + } +}, { + emitPrimaryKey: false +}, 'pets', 'eye_color'); + +// Print the SQL constraints +console.log(constraint.constraints); + +// Invoke the foreign key builder +constraint.foreignKey(callback); + +/// Public Callback Methods: + +/// createDatabase(dbName, [options,] callback) +db.createDatabase('petstore', callback); +db.createDatabase('petstore', {}, callback); + +/// dropDatabase(dbName, [options,] callback) +db.dropDatabase('petstore', callback); +db.dropDatabase('petstore', { ifExists: true }, callback); + +/// createSequence(sqName, [options,] callback) +db.createSequence('pets_id_sq', callback); +db.createSequence('pets_id_sq', { temp: true }, callback); + +/// switchDatabase(options, callback) +db.switchDatabase('petstore', callback); +db.switchDatabase({ database: 'petstore' }, callback); + +/// dropSequence(sqName, [options,] callback) +db.dropSequence('pets_id_sq', callback); +db.dropSequence('pets_id_sq', { + ifExists: true, + cascade: true, + restrict: true, +}, callback); + +/// Public Promisified Methods: + +/// createDatabaseAsync(dbName, [options]) +db.createDatabaseAsync('petstore').then(onResolve); +db.createDatabaseAsync('petstore', {}).then(onResolve); + +/// dropDatabaseAsync(dbName, [options]) +db.dropDatabaseAsync('petstore').then(onResolve); +db.dropDatabaseAsync('petstore', { ifExists: true }).then(onResolve); + +/// createSequenceAsync(sqName, [options]) +db.createSequenceAsync('pets_id_sq').then(onResolve); +db.createSequenceAsync('pets_id_sq', { temp: true }).then(onResolve); + +/// switchDatabaseAsync(options) +db.switchDatabaseAsync('petstore').then(onResolve); +db.switchDatabaseAsync({ database: 'petstore' }).then(onResolve); + +/// dropSequenceAsync(sqName, [options]) +db.dropSequenceAsync('pets_id_sq').then(onResolve); +db.dropSequenceAsync('pets_id_sq', { + ifExists: true, + cascade: true, + restrict: true, +}).then(onResolve); diff --git a/db-migrate-pg/db-migrate-pg.d.ts b/db-migrate-pg/db-migrate-pg.d.ts new file mode 100644 index 0000000000..533b8ff91d --- /dev/null +++ b/db-migrate-pg/db-migrate-pg.d.ts @@ -0,0 +1,60 @@ +// Type definitions for db-migrate-pg +// Project: https://github.com/db-migrate/pg +// Definitions by: nickiannone +// Definitions: https://github.com/nickiannone/DefinitelyTyped + +/// +/// + +declare module "db-migrate-pg" { + + import * as pg from "pg"; + import * as DbMigrateBase from "db-migrate-base"; + import * as Promise from "bluebird"; + + // Yes, this is a dummy interface for now; the current implementation of the pg driver doesn't need any options. + export interface CreateDatabaseOptions {} + + export interface DropDatabaseOptions { + ifExists?: boolean; + } + + export interface CreateSequenceOptions { + temp?: boolean; + } + + export interface SwitchDatabaseOptions { + database?: string; + } + + export interface DropSequenceOptions { + ifExists?: boolean; + cascade?: boolean; + restrict?: boolean; + } + + export interface ColumnConstraint { + foreignKey: (callback: DbMigrateBase.CallbackFunction) => void; + constraints: string; + } + + export interface ColumnConstraintOptions { + emitPrimaryKey?: boolean; + } + + export class PgDriver extends DbMigrateBase.Base { + constructor(connection: pg.Client, schema: string, intern: DbMigrateBase.InternalOptions); + createDatabase(dbName: string, optionsOrCb: CreateDatabaseOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void; + dropDatabase(dbName: string, optionsOrCb: DropDatabaseOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void; + createSequence(sqName: string, optionsOrCb: CreateSequenceOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void; + switchDatabase(options: string | SwitchDatabaseOptions, callback: DbMigrateBase.CallbackFunction): void; + dropSequence(dbName: string, optionsOrCb: DropSequenceOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void; + createColumnConstraint(spec: DbMigrateBase.ColumnSpec, options: ColumnConstraintOptions, tableName: string, columnName: string): ColumnConstraint; + + createDatabaseAsync(dbName: string, options?: CreateDatabaseOptions): Promise; + dropDatabaseAsync(dbName: string, options?: DropDatabaseOptions): Promise; + createSequenceAsync(sqName: string, options?: CreateSequenceOptions): Promise; + switchDatabaseAsync(options: string | SwitchDatabaseOptions): Promise; + dropSequenceAsync(dbName: string, options?: DropSequenceOptions): Promise; + } +} \ No newline at end of file diff --git a/devexpress-web/devexpress-web.d.ts b/devexpress-web/devexpress-web.d.ts index 6671a45ec4..c2e0014f85 100644 --- a/devexpress-web/devexpress-web.d.ts +++ b/devexpress-web/devexpress-web.d.ts @@ -250,6 +250,9 @@ interface ASPxClientDashboardItemWidgetCreatedEventHandler { */ (source: S, e: ASPxClientDashboardItemWidgetEventArgs): void; } +/** + * References a method that will handle the ItemWidgetUpdating event. + */ interface ASPxClientDashboardItemWidgetUpdatingEventHandler { /** * References a method that will handle the ItemWidgetUpdating event. @@ -258,6 +261,9 @@ interface ASPxClientDashboardItemWidgetUpdatingEventHandler { */ (source: S, e: ASPxClientDashboardItemWidgetEventArgs): void; } +/** + * References a method that will handle the ItemWidgetUpdated event. + */ interface ASPxClientDashboardItemWidgetUpdatedEventHandler { /** * References a method that will handle the ItemWidgetUpdated event. @@ -616,6 +622,11 @@ interface ASPxClientDashboardDesigner extends ASPxClientControl { * Occurs after a dashboard displayed in the ASPxClientDashboardDesigner is changed. */ DashboardChanged: ASPxClientEvent>; + /** + * For internal use. + */ + CustomizeMenuItems: ASPxClientEvent>; + BeforeRender: ASPxClientEvent>; /** * Switches the ASPxClientDashboardDesigner to the viewer mode. */ @@ -650,6 +661,9 @@ interface ASPxClientDashboardDesigner extends ASPxClientControl { */ SaveDashboard(): void; } +/** + * References a method that will handle the DashboardStateChanged event. + */ interface ASPxClientDashboardStateChangedEventHandler { /** * References a method that will handle the DashboardStateChanged event. @@ -668,6 +682,9 @@ interface ASPxClientDashboardStateChangedEventArgs extends ASPxClientEventArgs { */ DashboardState: string; } +/** + * References a method that will handle the DashboardChanged event. + */ interface ASPxClientDashboardChangedEventHandler { /** * References a method that will handle the DashboardChanged event. @@ -691,6 +708,26 @@ interface ASPxClientDashboardChangedEventArgs extends ASPxClientEventArgs { */ DashboardName: string; } +interface ASPxClientDashboardDesignerCustomizeMenuItemsEventHandler { + (source: S, e: ASPxClientDashboardDesignerCustomizeMenuItemsEventArgs): void; +} +interface ASPxClientDashboardDesignerMenuItem { + id: string; + title: string; + template: string; + selected: boolean; + disabled: boolean; + hasSeparator: boolean; + click: Function; + hotKey: number; +} +interface ASPxClientDashboardDesignerCustomizeMenuItemsEventArgs extends ASPxClientEventArgs { + Items: ASPxClientDashboardDesignerMenuItem[]; + FindById(itemId: string): ASPxClientDashboardDesignerMenuItem; +} +interface ASPxClientDashboardDesignerBeforeRenderEventHandler { + (source: S, e: ASPxClientEventArgs): void; +} /** * A client-side equivalent of the ASPxDashboardViewer control. */ @@ -1332,6 +1369,9 @@ interface ASPxClientDashboardActionAvailabilityChangedEventArgs extends ASPxClie */ ItemActions: ASPxClientDashboardItemAction[]; } +/** + * References a method that will handle the DataLoadingError event. + */ interface ASPxClientDashboardDataLoadingErrorEventHandler { /** * References a method that will handle the DataLoadingError event. @@ -1630,11 +1670,11 @@ interface ASPxClientBinaryImage extends ASPxClientEdit { */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param parameter A string value that contains any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * Represents the client-side equivalent of the ASPxButton control. @@ -2482,8 +2522,8 @@ interface ASPxClientListEdit extends ASPxClientEdit { */ interface ASPxClientListEditItem { /** - * Gets a value that indicates whether a list box item is selected. - * Value: true if a list box item is selected; otherwise, false. + * Gets a value that indicates whether a list edit item is selected. + * Value: true if a list edit item is selected; otherwise, false. */ selected: boolean; /** @@ -3367,11 +3407,11 @@ interface ASPxClientGaugeControl extends ASPxClientControl { */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * Represents the client ASPxGridView. @@ -6159,7 +6199,7 @@ interface ASPxClientVerticalGrid extends ASPxClientGridBase { */ RowSorting: ASPxClientEvent>; /** - * Fires on the client side before the expansion state of a row is changed via end-user interaction. + * Fires on the client side before the expansion state of a row is changed by end-user interaction. */ RowExpandedChanging: ASPxClientEvent>; /** @@ -7406,6 +7446,27 @@ interface ASPxClientHtmlEditorInsertYouTubeVideoCommandArguments extends ASPxCli */ interface ASPxClientHtmlEditorChangeYouTubeVideoCommandArguments extends ASPxClientHtmlEditorInsertYouTubeVideoCommandArguments { } +/** + * A method that will handle the DialogInitialized client event. + */ +interface ASPxClientHtmlEditorDialogInitializedEventHandler { + /** + * A method that will handle the client DialogInitialized event. + * @param source An object representing the event's source. + * @param e An ASPxClientHtmlEditorDialogInitializedEventArgs object that contains event data. + */ + (source: S, e: ASPxClientHtmlEditorDialogInitializedEventArgs): void; +} +/** + * Provides data for the DialogInitialized client event. + */ +interface ASPxClientHtmlEditorDialogInitializedEventArgs extends ASPxClientEventArgs { + /** + * Gets the name of the dialog that has been initialized. + * Value: A string value that is the name of the initialized dialog. + */ + dialogName: string; +} /** * A method that will handle the CommandExecuting event. */ @@ -7634,6 +7695,10 @@ interface ASPxClientHtmlEditorBeforePasteEventArgs extends ASPxClientEventArgs { * Represents a client-side equivalent of the ASPxHtmlEditor control. */ interface ASPxClientHtmlEditor extends ASPxClientControl { + /** + * Occurs on the client side after a dialog has been initialized. + */ + DialogInitialized: ASPxClientEvent>; /** * Occurs before a default or custom command has been executed and allows you to cancel the action. */ @@ -7797,7 +7862,7 @@ interface ASPxClientHtmlEditor extends ASPxClientControl { */ SetToolbarDropDownItemPickerValue(commandName: string, value: string): void; /** - * Specifies the visibility of a ribbon context tab ?ategory specified by its name. + * Specifies the visibility of a ribbon context tab category specified by its name. * @param categoryName A Name property value of the required category. * @param active true to make a category visible; false to make it hidden. */ @@ -7958,11 +8023,11 @@ interface ASPxClientPivotGrid extends ASPxClientControl { */ PerformCallback(args: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param args A string value that represents any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param args + * @param onSuccess */ - PerformCallback(args: string, onSuccess: Function): void; + PerformCallback(args: string, onSuccess: (arg1: string) => void): void; } /** * A method that will handle the CellDblClick event. @@ -8239,11 +8304,11 @@ interface ASPxClientRichEdit extends ASPxClientControl { */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; /** * Indicates whether any unsaved changes are contained in the current document. */ @@ -9122,11 +9187,7 @@ interface RichEditCommands { * Value: A object that provides methods for executing the command and checking its state. */ toggleTableCellBottomBorder: ToggleTableCellBottomBorderCommand; - /** - * Gets a command to toggle left borders for selected cells on/off. - * Value: A object that provides methods for executing the command and checking its state. - */ - toggleTableCellsLeftBorder: ToggleTableCellsLeftBorderCommand; + toggleTableCellLeftBorder: ToggleTableCellLeftBorderCommand; /** * Gets a command to remove the borders of the selected table cells. * Value: A object that provides methods for executing the command and checking its state. @@ -9202,6 +9263,7 @@ interface RichEditCommands { * Value: A object that provides methods for executing the command and checking its state. */ replaceNext: ReplaceNextCommand; + openSpellingDialog: OpenSpellingDialogCommand; } /** * Serves as a base for objects that implement different client command functionalities. @@ -10814,10 +10876,10 @@ interface OpenPageMarginsDialogCommand extends CommandWithSimpleStateBase { */ interface ChangePageOrientationCommand extends CommandBase { /** - * Executes the ChangePageOrientationCommand command by applying the specified setting. May result in taking no action if the command's state does not allow command execution. Use the object's getState method to check the command state. - * @param isPortrait true to apply portrait page orientation, false to apply landscape page orientation. + * + * @param isPortrait */ - execute(isPortrait: boolean): boolean; + execute(isPortrait: any): boolean; /** * Gets information about the command state. */ @@ -11428,6 +11490,9 @@ declare enum ParagraphFirstLineIndent { Indented=1, Hanging=2 } +interface OpenSpellingDialogCommand extends CommandWithSimpleStateBase { + execute(): boolean; +} /** * A command to invoke the Insert Table dialog. */ @@ -11519,7 +11584,7 @@ interface ChangeTableColumnPreferredWidthCommand extends CommandBase { interface ChangeTableCellFormattingCommand extends CommandBase { /** * Executes the ChangeTableCellFormattingCommand command by applying the specified setting. May result in taking no action if the command's state does not allow command execution. Use the object's getState method to check the command state. - * @param settings A TableFormattingSettings object specifying ?ell formatting of the selected table elements. + * @param settings A TableFormattingSettings object specifying cell formatting of the selected table elements. */ execute(settings: TableCellFormattingSettings): boolean; /** @@ -11656,7 +11721,7 @@ interface SplitTableCellsDialogCommand extends CommandWithSimpleStateBase { /** * A command to split the selected table cells based on the specified options. */ -interface SplitTableCellsCommand extends CommandBase { +interface SplitTableCellsCommand extends CommandWithSimpleStateBase { /** * Executes the SplitTableCellsCommand command by applying the specified settings. May result in taking no action if the command's state does not allow command execution. Use the object's getState method to check the command state. * @param rowCount An integer value specifying number of rows in the splitted table cells. @@ -11664,10 +11729,6 @@ interface SplitTableCellsCommand extends CommandBase { * @param mergeBeforeSplit true to merge the selected cells before splitting; otherwise, false. */ execute(rowCount: number, columnCount: number, mergeBeforeSplit: boolean): boolean; - /** - * Gets information about the command state. - */ - getState(): SimpleCommandState; } /** * A command to insert table cells with a vertical shift into the selected table. @@ -11829,13 +11890,7 @@ interface ToggleTableCellBottomBorderCommand extends CommandWithBooleanStateBase */ execute(): boolean; } -/** - * A command to toggle left borders for selected cells on/off. - */ -interface ToggleTableCellsLeftBorderCommand extends CommandWithBooleanStateBase { - /** - * Executes the ToggleTableCellsLeftBorderCommand command by imitating the corresponding end-user action made in the RichEdit's UI. May result in taking no action if the command's state does not allow command execution. Use the object's getState method to check the command state. - */ +interface ToggleTableCellLeftBorderCommand extends CommandWithBooleanStateBase { execute(): boolean; } /** @@ -12202,10 +12257,6 @@ interface TableHeightUnit { * Value: An integer value specifying the table height. */ value: number; - /** - * Gets or sets the unit type for the table height. - * Value: One of the values. - */ type: any; } declare enum TableHeightUnitType { @@ -12816,18 +12867,42 @@ interface ASPxClientAppointment { * A client point object. */ interface ASPxClientPoint { + /** + * Gets the point's X-coordinate. + */ GetX(): number; + /** + * Gets the point's Y-coordinate. + */ GetY(): number; } /** * A client rectangle object. */ interface ASPxClientRect { + /** + * Gets the X-coordinate of the rectangle's left edge. + */ GetLeft(): number; + /** + * Gets the X-coordinate of the rectangle's right edge. + */ GetRight(): number; + /** + * Gets the Y-coordinate of the rectangle's top edge. + */ GetTop(): number; + /** + * Gets the Y-coordinate of the rectangle's bottom edge. + */ GetBottom(): number; + /** + * Gets the rectangle's width. + */ GetWidth(): number; + /** + * Gets the rectangle's height. + */ GetHeight(): number; } /** @@ -13078,10 +13153,13 @@ interface ASPxClientWeekOfMonth { * Represents a client-side equivalent of the WeekDaysCheckEdit control. */ interface ASPxClientWeekDaysCheckEdit extends ASPxClientControl { + /** + * Gets the selection state of the week day check boxes. + */ GetValue(): ASPxClientWeekDays; /** - * - * @param value + * Gets the selection state of the week day check boxes. + * @param value An ASPxClientWeekDays object specifying the selection state of the week day check boxes. */ SetValue(value: ASPxClientWeekDays): void; } @@ -13089,22 +13167,31 @@ interface ASPxClientWeekDaysCheckEdit extends ASPxClientControl { * Represents a client-side equivalent of the RecurrenceRangeControl. */ interface ASPxClientRecurrenceRangeControl extends ASPxClientControl { + /** + * Gets the type of the recurrence range. + */ GetRange(): ASPxClientRecurrenceRange; + /** + * Gets how many times the appointment occurs. + */ GetOccurrenceCount(): number; + /** + * Gets the recurrence end date. + */ GetEndDate(): Date; /** - * - * @param range + * Sets the type of the recurrence range. + * @param range An ASPxClientRecurrenceRangeenumeration value that specifies the recurrence range type. */ SetRange(range: ASPxClientRecurrenceRange): void; /** - * - * @param occurrenceCount + * Sets how many times the appointment occurs. + * @param occurrenceCount An integer value that specifies how many times the appointment occurs. */ SetOccurrenceCount(occurrenceCount: number): void; /** - * - * @param date + * Sets the recurrence end date. + * @param date A JavaScript Date object that specifies the end date for the recurrence. */ SetEndDate(date: Date): void; } @@ -13112,10 +13199,13 @@ interface ASPxClientRecurrenceRangeControl extends ASPxClientControl { * A base for client equivalents of recurrence controls available in the XtraScheduler library. */ interface ASPxClientRecurrenceControlBase extends ASPxClientControl { + /** + * Returns an object providing access to the ASPxClientRecurrenceControlBase control's editor values. + */ CreateValueAccessor(): DefaultRecurrenceRuleValuesAccessor; /** - * - * @param recurrenceInfo + * Updates values of editors displayed by the ASPxClientRecurrenceControlBase control. + * @param recurrenceInfo An ASPxClientRecurrenceInfo object containing new editor values. */ Update(recurrenceInfo: ASPxClientRecurrenceInfo): void; } @@ -13123,10 +13213,13 @@ interface ASPxClientRecurrenceControlBase extends ASPxClientControl { * Represents a client-side equivalent of the DailyRecurrenceControl - a control for specifying the daily recurrence. */ interface ASPxClientDailyRecurrenceControl extends ASPxClientRecurrenceControlBase { + /** + * Returns an object providing access to the ASPxClientDailyRecurrenceControl's editor values. + */ CreateValueAccessor(): DefaultRecurrenceRuleValuesAccessor; /** - * - * @param recurrenceInfo + * Updates values of editors displayed by the ASPxClientDailyRecurrenceControl. + * @param recurrenceInfo An ASPxClientRecurrenceInfo object containing new editor values. */ Update(recurrenceInfo: ASPxClientRecurrenceInfo): void; } @@ -13134,10 +13227,13 @@ interface ASPxClientDailyRecurrenceControl extends ASPxClientRecurrenceControlBa * Represents a client-side equivalent of the WeeklyRecurrenceControl. */ interface ASPxClientWeeklyRecurrenceControl extends ASPxClientRecurrenceControlBase { + /** + * Returns an object providing access to the ASPxClientWeeklyRecurrenceControl's editor values. + */ CreateValueAccessor(): DefaultRecurrenceRuleValuesAccessor; /** - * - * @param recurrenceInfo + * Updates values of editors displayed by the ASPxClientWeeklyRecurrenceControl. + * @param recurrenceInfo An ASPxClientRecurrenceInfo object containing new editor values. */ Update(recurrenceInfo: ASPxClientRecurrenceInfo): void; } @@ -13145,10 +13241,13 @@ interface ASPxClientWeeklyRecurrenceControl extends ASPxClientRecurrenceControlB * Represents a client-side equivalent of the MonthlyRecurrenceControl. */ interface ASPxClientMonthlyRecurrenceControl extends ASPxClientRecurrenceControlBase { + /** + * Returns an object providing access to the ASPxClientMonthlyRecurrenceControl's editor values. + */ CreateValueAccessor(): DefaultRecurrenceRuleValuesAccessor; /** - * - * @param recurrenceInfo + * Updates values of editors displayed by the ASPxClientMonthlyRecurrenceControll. + * @param recurrenceInfo An ASPxClientRecurrenceInfo object containing new editor values. */ Update(recurrenceInfo: ASPxClientRecurrenceInfo): void; } @@ -13156,55 +13255,139 @@ interface ASPxClientMonthlyRecurrenceControl extends ASPxClientRecurrenceControl * Represents a client-side equivalent of the YearlyRecurrenceControl. */ interface ASPxClientYearlyRecurrenceControl extends ASPxClientRecurrenceControlBase { + /** + * Returns an object providing access to the ASPxClientYearlyRecurrenceControl's editor values. + */ CreateValueAccessor(): DefaultRecurrenceRuleValuesAccessor; /** - * - * @param recurrenceInfo + * Updates values of editors displayed by the ASPxClientYearlyRecurrenceControl. + * @param recurrenceInfo An ASPxClientRecurrenceInfo object containing new editor values. */ Update(recurrenceInfo: ASPxClientRecurrenceInfo): void; } +/** + * An object providing access to an ASPxClientRecurrenceControlBase control's editor values. + */ interface DefaultRecurrenceRuleValuesAccessor { + /** + * Get the frequency with which the appointment occurs with respect to the appointment's recurrence type. + */ GetPeriodicity(): number; + /** + * Gets the number of the month's day in which the appointment is scheduled. + */ GetDayNumber(): number; + /** + * Gets or sets the month's number. + */ GetMonth(): number; + /** + * Gets the days of the week to which a weekly recurrent appointment is scheduled. + */ GetWeekDays(): ASPxClientWeekDays; + /** + * Gets the number of the week in a month when an appointment is scheduled. + */ GetWeekOfMonth(): ASPxClientWeekOfMonth; } +/** + * An object providing access to an ASPxClientDailyRecurrenceControl's editor values. + */ interface DailyRecurrenceValuesAccessor extends DefaultRecurrenceRuleValuesAccessor { + /** + * Gets the number of days between appointment occurrences. + */ GetPeriodicity(): number; + /** + * Gets the days of the week to which a daily recurrent appointment is scheduled. + */ GetWeekDays(): ASPxClientWeekDays; } +/** + * An object providing access to an ASPxClientWeeklyRecurrenceControl's editor values. + */ interface WeeklyRecurrenceValuesAccessor extends DefaultRecurrenceRuleValuesAccessor { + /** + * Gets the number of weeks between appointment occurrences. + */ GetPeriodicity(): number; + /** + * Gets the days of the week to which a weekly recurrent appointment is scheduled. + */ GetWeekDays(): ASPxClientWeekDays; } +/** + * An object providing access to an ASPxClientMonthlyRecurrenceControl's editor values. + */ interface MonthlyRecurrenceValuesAccessor extends DefaultRecurrenceRuleValuesAccessor { + /** + * Gets the number of the month's day in which the appointment is scheduled. + */ GetDayNumber(): number; + /** + * Gets the number of months between appointment occurrences. + */ GetPeriodicity(): number; + /** + * Gets the days of the week to which a monthly recurrent appointment is scheduled. + */ GetWeekDays(): ASPxClientWeekDays; + /** + * Gets the number of the week in a month when an appointment is scheduled. + */ GetWeekOfMonth(): ASPxClientWeekOfMonth; } +/** + * An object providing access to an ASPxClientYearlyRecurrenceControl's editor values. + */ interface YearlyRecurrenceValuesAccessor extends DefaultRecurrenceRuleValuesAccessor { + /** + * Gets the number of the month's day in which the appointment is scheduled. + */ GetDayNumber(): number; + /** + * Gets or sets the month's number. + */ GetMonth(): number; + /** + * Gets the days of the week to which a yearly recurrent appointment is scheduled. + */ GetWeekDays(): ASPxClientWeekDays; + /** + * Gets or sets the number of a week in a month when an appointment is scheduled. + */ GetWeekOfMonth(): ASPxClientWeekOfMonth; } +/** + * Provides base functionality for ASPxClientScheduler's forms. + */ interface ASPxClientFormBase { + /** + * Occurs when the form has been closed. + */ FormClosed: ASPxClientEvent>; + /** + * Closes the form. + */ Close(): void; /** - * - * @param element - * @param isVisible + * Sets the visibility state of the specified form element. + * @param element An object specifying the element whose visibility state should be changed. + * @param isVisible true to display the element; false to hide the element. */ SetVisibleCore(element: Object, isVisible: boolean): void; } +/** + * Represents a client-side equivalent of the RecurrenceTypeEdit. + */ interface ASPxClientRecurrenceTypeEdit extends ASPxClientRadioButtonList { + /** + * Gets the selected recurrence type. + */ GetRecurrenceType(): ASPxClientRecurrenceType; /** - * - * @param recurrenceType + * Sets the selected recurrence type. + * @param recurrenceType An ASPxClientRecurrenceType enumeration value. */ SetRecurrenceType(recurrenceType: ASPxClientRecurrenceType): void; } @@ -13227,10 +13410,13 @@ interface AppointmentPropertyNames { * Represents the client-side equivalent of the TimeInterval class. */ interface ASPxClientTimeInterval { + /** + * Gets a value indicating if the time interval is All-Day. + */ GetAllDay(): boolean; /** - * - * @param allDayValue + * Sets a value specifying if the time interval is All-Day. + * @param allDayValue true, if this is an all-day time interval; otherwise, false. */ SetAllDay(allDayValue: boolean): void; /** @@ -13908,23 +14094,44 @@ interface ASPxClientAppointmentResizeEventArgs extends ASPxClientEventArgs { */ operation: ASPxClientAppointmentOperation; } +/** + * Contains information about a client tooltip. + */ interface ASPxClientSchedulerToolTipData { + /** + * Returns the client appointment for which the tooltip is displayed. + */ GetAppointment(): ASPxClientAppointment; + /** + * Returns the client time interval for which the tooltip is displayed. + */ GetInterval(): ASPxClientTimeInterval; + /** + * Returns the resources associated with the appointment for which the tooltip is displayed. + */ GetResources(): Object[]; } +/** + * A client-side equivalent of the ASPxSchedulerToolTipBase control. + */ interface ASPxClientToolTipBase { + /** + * Returns the value that indicates whether or not the tooltip can be displayed. + */ CanShowToolTip(): boolean; /** - * - * @param toolTipData + * Ends updating the tooltip content. + * @param toolTipData An ASPxClientSchedulerToolTipData object providing data required to update the tooltip content. */ FinalizeUpdate(toolTipData: ASPxClientSchedulerToolTipData): void; /** - * - * @param toolTipData + * Updates the tooltip content. + * @param toolTipData An ASPxClientSchedulerToolTipData object providing data required to update the tooltip content. */ Update(toolTipData: ASPxClientSchedulerToolTipData): void; + /** + * Closes the tooltip. + */ Close(): void; /** * @@ -13932,18 +14139,18 @@ interface ASPxClientToolTipBase { */ CalculatePosition(bounds: Object): ASPxClientPoint; /** - * - * @param eventObject + * Displays the Appointment Menu in the position of the tooltip. + * @param eventObject An object containing information about the event on which the menu is displayed. */ ShowAppointmentMenu(eventObject: Object): void; /** - * - * @param eventObject + * Displays the View Menu in the position of the tooltip. + * @param eventObject An object containing information about the event on which the menu is displayed. */ ShowViewMenu(eventObject: Object): void; /** - * - * @param interval + * Returns the string representation of the specified interval. + * @param interval An ASPxClientTimeInterval object to convert. */ ConvertIntervalToString(interval: ASPxClientTimeInterval): string; } @@ -14222,11 +14429,11 @@ interface ASPxClientSpreadsheet extends ASPxClientControl { */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side DocumentCallback event, passing it the specified argument. * @param parameter A string value that represents any information that needs to be sent to the server-side DocumentCallback event. @@ -14373,6 +14580,7 @@ interface ASPxClientTreeList extends ASPxClientControl { * Sets input focus to the ASPxTreeList. */ Focus(): void; + GetPopupEditForm(): ASPxClientPopupControl; /** * Returns the focused node's key value. */ @@ -14430,11 +14638,11 @@ interface ASPxClientTreeList extends ASPxClientControl { */ PerformCallback(args: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param args A string value that represents any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param args + * @param onSuccess */ - PerformCallback(args: string, onSuccess: Function): void; + PerformCallback(args: string, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side CustomDataCallback event passing it the specified argument. * @param arg A string value that represents any information that needs to be sent to the server-side CustomDataCallback event. @@ -15011,22 +15219,22 @@ interface MVCxClientCallbackPanel extends ASPxClientCallbackPanel { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the Callback Panel by processing the passed information on the server, in an Action specified by the Callback Panel's CallbackRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified by the CallbackRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the CardView extension. @@ -15042,11 +15250,11 @@ interface MVCxClientCardView extends ASPxClientCardView { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the CardView by processing the passed information on the server, in an Action specified via the CardView's CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the CardView's CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback with a parameter to process the passed information on the server, in an Action specified via the CardView's CustomDataActionRouteValues property, and then process the returned result in the specified client function. This method does not update the CardView. * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomDataActionRouteValues property. @@ -15079,22 +15287,22 @@ interface MVCxClientChart extends ASPxClientWebChartControl { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update a Chart by processing the passed information on the server, in an Action specified via the Chart's CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side event, passing it the specified argument. * @param args A string value that represents any information that needs to be sent to the server-side event. */ PerformCallback(args: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param args A string value that represents any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param args + * @param onSuccess */ - PerformCallback(args: string, onSuccess: Function): void; + PerformCallback(args: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the ComboBox and ComboBoxFor extensions. @@ -15110,11 +15318,11 @@ interface MVCxClientComboBox extends ASPxClientComboBox { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the ComboBox by processing the passed information on the server, in an Action specified by the ComboBox's CallbackRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified by the CallbackRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. @@ -15135,22 +15343,22 @@ interface MVCxClientDataView extends ASPxClientDataView { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the DataView by processing the passed information on the server, in an Action specified via the DataView's CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. * @param parameter A string value that represents any information that needs to be sent to the server-side CustomCallback event. */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the DateEdit extension. @@ -15167,22 +15375,22 @@ interface MVCxClientDockManager extends ASPxClientDockManager { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the DockManager by processing the passed information on the server, in an Action specified by the DockManager's CallbackRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified by the CallbackRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. * @param parameter A string value that contains any information that needs to be sent to the server-side Callback event. */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that contains any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the DockPanel extension. @@ -15198,11 +15406,11 @@ interface MVCxClientDockPanel extends ASPxClientDockPanel { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the DockPanel by processing the passed information on the server, in an Action specified by the DockPanel's DockPanelSettings.CallbackRouteValues) property. - * @param data An object containing any information that needs to be passed to a handling Action specified by the CallbackRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side WindowCallback event, passing the specified argument to it. * @param parameter A string value that is any information that needs to be sent to the server-side WindowCallback event. @@ -15223,22 +15431,22 @@ interface MVCxClientFileManager extends ASPxClientFileManager { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the FileManager by processing the passed information on the server, in an Action specified via the extension's CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the file manager's CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. * @param args A string value that specifies any information that needs to be sent to the server-side CustomCallback event. */ PerformCallback(args: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param args A string value that specifies any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param args + * @param onSuccess */ - PerformCallback(args: string, onSuccess: Function): void; + PerformCallback(args: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the GridView extension. @@ -15254,11 +15462,11 @@ interface MVCxClientGridView extends ASPxClientGridView { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the GridView by processing the passed information on the server, in an Action specified via the grid's CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the grid's CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback with a parameter to process the passed information on the server, in an Action specified via the GridView's CustomDataActionRouteValues property, and then process the returned result in the specified client function. This method does not update the GridView. * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomDataActionRouteValues property. @@ -15317,22 +15525,22 @@ interface MVCxClientImageGallery extends ASPxClientImageGallery { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the ImageGallery by processing the passed information on the server, in an Action specified via the ImageGallery's CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. * @param parameter A string value that represents any information that needs to be sent to the server-side CustomCallback event. */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the ListBox and ListBoxFor extensions. @@ -15348,11 +15556,11 @@ interface MVCxClientListBox extends ASPxClientListBox { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the ListBox by processing the passed information on the server, in an Action specified by the ListBox's CallbackRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified by the CallbackRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server, and generates the server-side Callback event, passing it the specified argument. * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. @@ -15382,11 +15590,11 @@ interface MVCxClientPivotGrid extends ASPxClientPivotGrid { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the PivotGrid by processing the passed information on the server, in an Action specified via the grid's CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the grid's CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Passes PivotGrid callback parameters to the specified object. * @param obj An object that receives PivotGrid callback parameters. @@ -15398,11 +15606,11 @@ interface MVCxClientPivotGrid extends ASPxClientPivotGrid { */ PerformCallback(args: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param args A string value that represents any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param args + * @param onSuccess */ - PerformCallback(args: string, onSuccess: Function): void; + PerformCallback(args: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the PopupControl extension. @@ -15418,11 +15626,11 @@ interface MVCxClientPopupControl extends ASPxClientPopupControl { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the PopupControl by processing the passed information on the server, in an Action specified via the PopupControl's CallbackRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the CallbackRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback with a parameters to update the popup window by processing the related popup window and the passed information on the server, in an Action specified by the PopupControl's CallbackRouteValues property. * @param window A ASPxClientPopupWindow object identifying the processed popup window. @@ -15436,12 +15644,12 @@ interface MVCxClientPopupControl extends ASPxClientPopupControl { */ PerformWindowCallback(window: ASPxClientPopupWindow, parameter: string): void; /** - * Sends a callback to the server and generates the server-side WindowCallback event, passing it the related popup window object and the specified argument. - * @param window An ASPxClientPopupWindow object identifying the processed popup window. - * @param parameter A string value specifying any information that needs to be sent to the server-side WindowCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param window + * @param parameter + * @param onSuccess */ - PerformWindowCallback(window: ASPxClientPopupWindow, parameter: string, onSuccess: Function): void; + PerformWindowCallback(window: ASPxClientPopupWindow, parameter: string, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side WindowCallback event, passing the specified argument to it. * @param parameter A string value that is any information that needs to be sent to the server-side WindowCallback event. @@ -15513,22 +15721,22 @@ interface MVCxClientReportDesigner extends ASPxClientReportDesigner { */ PerformCallback(arg: Object): void; /** - * Sends a callback to the server with the specified argument. - * @param arg A Object value, specifying the callback argument. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param arg + * @param onSuccess */ - PerformCallback(arg: Object, onSuccess: Function): void; + PerformCallback(arg: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server with the specified argument. * @param arg A String value, specifying the callback argument. */ PerformCallback(arg: string): void; /** - * Sends a callback to the server with the specified argument. - * @param arg A String value, specifying the callback argument. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param arg + * @param onSuccess */ - PerformCallback(arg: string, onSuccess: Function): void; + PerformCallback(arg: string, onSuccess: (arg1: string) => void): void; } /** * A method that will handle the SaveCommandExecuted event. @@ -15565,22 +15773,22 @@ interface MVCxClientRichEdit extends ASPxClientRichEdit { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the RichEdit by processing the passed information on the server, in an Action specified via the CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. * @param parameter A string value that represents any information that needs to be sent to the server-side event. */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the RoundPanel extension. @@ -15596,22 +15804,22 @@ interface MVCxClientRoundPanel extends ASPxClientRoundPanel { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the Round Panel by processing the passed information on the server, in an Action specified by the Round Panel's CallbackRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified by the CallbackRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side ContentCallback event, passing it the specified argument. * @param parameter A string value that is any information that needs to be sent to the server-side ContentCallback event. */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side ContentCallback event, passing it the specified argument. - * @param parameter A string value that is any information that needs to be sent to the server-side ContentCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the Scheduler extension. @@ -15628,11 +15836,11 @@ interface MVCxClientScheduler extends ASPxClientScheduler { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the Scheduler by processing the passed information on the server, in an Action specified via the Scheduler's CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument * @param parameter A string value that represents any information that needs to be sent to the server-side CustomCallback event. @@ -15682,22 +15890,22 @@ interface MVCxClientSpreadsheet extends ASPxClientSpreadsheet { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the Spreadsheet by processing the passed information on the server, in an Action specified via the CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. * @param parameter A string value that represents any information that needs to be sent to the server-side event. */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the PageControl extension. @@ -15713,22 +15921,22 @@ interface MVCxClientPageControl extends ASPxClientPageControl { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the PageControl by processing the passed information on the server, in an Action specified by the PageControl's CallbackRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified by the CallbackRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the TokenBox and TokenBoxFor extensions. @@ -15744,11 +15952,11 @@ interface MVCxClientTokenBox extends ASPxClientTokenBox { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the TokenBox by processing the passed information on the server, in an Action specified by the TokenBox's CallbackRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified by the CallbackRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. @@ -15769,11 +15977,11 @@ interface MVCxClientTreeList extends ASPxClientTreeList { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the TreeList by processing the passed information on the server, in an Action specified via the TreeList's CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback with a parameter to process the passed information on the server, in an Action specified via the TreeList's CustomDataCallback event. This method does not update the TreeList. * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomDataActionRouteValues property. @@ -15785,11 +15993,11 @@ interface MVCxClientTreeList extends ASPxClientTreeList { */ PerformCallback(args: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param args A string value that represents any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param args + * @param onSuccess */ - PerformCallback(args: string, onSuccess: Function): void; + PerformCallback(args: string, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side CustomDataCallback event passing it the specified argument. * @param arg A string value that represents any information that needs to be sent to the server-side CustomDataCallback event. @@ -15887,11 +16095,11 @@ interface MVCxClientVerticalGrid extends ASPxClientVerticalGrid { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the VerticalGrid by processing the passed information on the server in an Action specified via the grid's CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the grid's CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback with a parameter to process the passed information on the server, in an Action specified via the VerticalGrid's CustomDataActionRouteValues property, and then process the returned result in the specified client function. This method does not update the VerticalGrid. * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomDataActionRouteValues property. @@ -16013,11 +16221,11 @@ interface ASPxClientCallback extends ASPxClientControl { */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * A method that will handle the client events related to completion of callback server-side processing. @@ -16072,11 +16280,11 @@ interface ASPxClientCallbackPanel extends ASPxClientControl { */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; /** * Returns the text displayed within the control's loading panel. */ @@ -16460,6 +16668,12 @@ interface ASPxClientControlsInitializedEventArgs extends ASPxClientEventArgs { */ isCallback: boolean; } +interface ASPxClientControlPredicate { + (control: Object): boolean; +} +interface ASPxClientControlAction { + (control: Object): void; +} /** * A collection object used on the client side to maintain particular client control objects */ @@ -16498,6 +16712,21 @@ interface ASPxClientControlCollection { * @param name A string value that is the hierarchically-qualified identifier of the required DevExpress control. */ GetByName(name: string): Object; + /** + * + * @param predicate + */ + GetControlsByPredicate(predicate: ASPxClientControlPredicate): Object[]; + /** + * + * @param type + */ + GetControlsByType(type: Object): Object[]; + /** + * + * @param action + */ + ForEachControl(action: ASPxClientControlAction): void; } /** * Represents a client-side equivalent of the ASPxDataView object. @@ -16559,11 +16788,11 @@ interface ASPxClientDataView extends ASPxClientControl { */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * A JavaScript function which returns a value specifying whether an object meets the criteria defined within the method specified by this delegate. @@ -16629,11 +16858,11 @@ interface ASPxClientDockManager extends ASPxClientControl { */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that contains any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; /** * Returns a zone specified by its unique identifier (zoneUID). * @param zoneUID A string value specifying the unique identifier of the zone. @@ -17375,11 +17604,11 @@ interface ASPxClientFileManager extends ASPxClientControl { */ PerformCallback(args: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param args A string value that specifies any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param args + * @param onSuccess */ - PerformCallback(args: string, onSuccess: Function): void; + PerformCallback(args: string, onSuccess: (arg1: string) => void): void; } /** * A JavaScript function which receives callback data obtained via a call to the client SetCurrentFolderPath method. @@ -17448,6 +17677,7 @@ interface ASPxClientFileManagerFile extends ASPxClientFileManagerItem { * A client-side equivalent of the FileManagerFolder object. */ interface ASPxClientFileManagerFolder extends ASPxClientFileManagerItem { + isParentFolder: boolean; } /** * A JavaScript function which receives callback data obtained by a call to the client GetAllItems method. @@ -18659,6 +18889,7 @@ interface ASPxClientMenuBase extends ASPxClientControl { * Represents a client collection that maintains client menu objects. */ interface ASPxClientMenuCollection extends ASPxClientControlCollection { + RecalculateAll(): void; /** * Hides all menus maitained by the collection. */ @@ -19358,12 +19589,12 @@ interface ASPxClientPopupControl extends ASPxClientPopupControlBase { */ PerformWindowCallback(window: ASPxClientPopupWindow, parameter: string): void; /** - * Sends a callback to the server and generates the server-side WindowCallback event, passing it the related popup window object and the specified argument. - * @param window An ASPxClientPopupWindow object identifying the processed popup window. - * @param parameter A string value specifying any information that needs to be sent to the server-side WindowCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param window + * @param parameter + * @param onSuccess */ - PerformWindowCallback(window: ASPxClientPopupWindow, parameter: string, onSuccess: Function): void; + PerformWindowCallback(window: ASPxClientPopupWindow, parameter: string, onSuccess: (arg1: string) => void): void; /** * Specifies the default popup window's size. * @param width An integer value that specifies the default popup window's width. @@ -20006,7 +20237,7 @@ interface ASPxClientRibbon extends ASPxClientControl { */ GetMinimized(): boolean; /** - * Specifies the visibility of a context tab ?ategory specified by its name. + * Specifies the visibility of a context tab category specified by its name. * @param categoryName A Name property value of the required category. * @param visible true to make a category visible; false to make it hidden. */ @@ -20248,11 +20479,11 @@ interface ASPxClientRoundPanel extends ASPxClientPanelBase { */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side ContentCallback event, passing it the specified argument. - * @param parameter A string value that is any information that needs to be sent to the server-side ContentCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; /** * Returns the text displayed within the panel's header. */ @@ -20623,11 +20854,11 @@ interface ASPxClientPageControl extends ASPxClientTabControlBase { */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * Represents a client-side equivalent of a tab control's TabPage object. @@ -21481,11 +21712,15 @@ interface ASPxClientChartDesigner extends ASPxClientControl { */ PerformCallback(arg: string): void; /** - * Sends a callback to the server and generates the server-side event, passing it the specified argument. - * @param arg A string value that represents any information that needs to be sent to the server-side event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param arg + * @param onSuccess + */ + PerformCallback(arg: string, onSuccess: (arg1: string) => void): void; + /** + * Updates the localization settings of the ASPxClientChartDesigner properties. + * @param localization A dictionary containing the property names, along with their localized equivalents. */ - PerformCallback(arg: string, onSuccess: Function): void; UpdateLocalization(localization: { [key: string]: string; }): void; /** * Returns the model of the Client Chart Designer. @@ -21636,11 +21871,11 @@ interface ASPxClientWebChartControl extends ASPxClientControl { */ PerformCallback(args: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param args A string value that represents any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param args + * @param onSuccess */ - PerformCallback(args: string, onSuccess: Function): void; + PerformCallback(args: string, onSuccess: (arg1: string) => void): void; /** * Prints the current chart on the client side. */ @@ -23640,11 +23875,15 @@ interface ASPxClientQueryBuilder extends ASPxClientControl { */ PerformCallback(arg: string): void; /** - * Sends a callback to the server with the specified argument. - * @param arg A String value, specifying the callback argument. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param arg + * @param onSuccess + */ + PerformCallback(arg: string, onSuccess: (arg1: string) => void): void; + /** + * Updates the localization settings of the ASPxClientQueryBuilder properties. + * @param localization A dictionary containing the property names, along with their localized equivalents. */ - PerformCallback(arg: string, onSuccess: Function): void; UpdateLocalization(localization: { [key: string]: string; }): void; /** * Returns the object model of a Query Builder. @@ -23797,11 +24036,15 @@ interface ASPxClientReportDesigner extends ASPxClientControl { */ PerformCallback(arg: string): void; /** - * Sends a callback to the server with the specified argument. - * @param arg A String value, specifying the callback argument. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param arg + * @param onSuccess + */ + PerformCallback(arg: string, onSuccess: (arg1: string) => void): void; + /** + * Updates the localization settings of the ASPxClientReportDesigner properties. + * @param localization A dictionary containing the property names, along with their localized equivalents. */ - PerformCallback(arg: string, onSuccess: Function): void; UpdateLocalization(localization: { [key: string]: string; }): void; /** * Returns the object model of a Web Report Designer. @@ -24013,6 +24256,10 @@ interface ASPxClientReportViewer extends ASPxClientControl { * Occurs on the client side when another report page is loaded into this ASPxClientReportViewer instance. */ PageLoad: ASPxClientEvent>; + /** + * Submits the values of the specified parameters. + * @param parameters A dictionary containing the parameter names, along with their Object values. + */ SubmitParameters(parameters: { [key: string]: Object; }): void; /** * Prints a report shown in the ReportViewer. @@ -24260,6 +24507,10 @@ interface ASPxClientWebDocumentViewer extends ASPxClientControl { * @param format A String value, specifying the export format. The following formats are currently supported: 'csv', 'html', 'image', 'mht', 'pdf', 'rtf', 'txt', 'xls', and 'xlsx'. */ ExportTo(format: string): void; + /** + * Updates the localization settings of the ASPxClientWebDocumentViewer properties. + * @param localization A dictionary containing the property names, along with their localized equivalents. + */ UpdateLocalization(localization: { [key: string]: string; }): void; } /** @@ -25661,30 +25912,30 @@ interface ASPxClientRichEditStatic extends ASPxClientControlStatic { } interface ASPxSchedulerDateTimeHelperStatic { /** - * - * @param date + * Returns the date part of the specified DateTime value. + * @param date A DateTime object from which to extract the date. */ TruncToDate(date: Date): Date; /** - * - * @param date + * Returns the day time part of the specified DateTime value. + * @param date A DateTime object from which to extract the day time. */ ToDayTime(date: Date): any; /** - * - * @param date + * Adds the specified number of days to a DateTime object and returns the result. + * @param date A DateTime object to which to add days. */ AddDays(date: Date): Date; /** - * - * @param date - * @param timeSpan + * Adds the specified timespan to a DateTime object and returns the result. + * @param date A DateTime object to which to add a timespan. + * @param timeSpan A TimeSpan object specifying the timespan to add. */ AddTimeSpan(date: Date, timeSpan: any): Date; /** - * - * @param date - * @param spanInMs + * Rounds a DateTime value up to the nearest interval. + * @param date A DateTime object containing a value to round. + * @param spanInMs A TimeSpan object specifying an interval to which to round. */ CeilDateTime(date: Date, spanInMs: any): Date; } @@ -25706,9 +25957,9 @@ interface ASPxClientRecurrenceTypeEditStatic extends ASPxClientRadioButtonListSt } interface ASPxClientTimeIntervalStatic { /** - * - * @param start - * @param end + * Gets the duration of a time interval between two points in time. + * @param start A DateTime object specifying the starting point of the time interval. + * @param end A DateTime object specifying the ending point of the time interval. */ CalculateDuration(start: Date, end: Date): number; } diff --git a/devtools-detect/devtools-detect-tests.ts b/devtools-detect/devtools-detect-tests.ts new file mode 100644 index 0000000000..9cd1d2f7a7 --- /dev/null +++ b/devtools-detect/devtools-detect-tests.ts @@ -0,0 +1,12 @@ +/// + +// check if it's open +console.log('is DevTools open?', window.devtools.open); +// check it's orientation, null if not open +console.log('and DevTools orientation?', window.devtools.orientation); + +// get notified when it's opened/closed or orientation changes +window.addEventListener('devtoolschange', function (e) { + console.log('is DevTools open?', e.detail.open); + console.log('and DevTools orientation?', e.detail.orientation); +}); diff --git a/devtools-detect/devtools-detect.d.ts b/devtools-detect/devtools-detect.d.ts new file mode 100644 index 0000000000..c66d63f0fa --- /dev/null +++ b/devtools-detect/devtools-detect.d.ts @@ -0,0 +1,16 @@ +// Type definitions for ajv +// Project: https://github.com/sindresorhus/devtools-detect +// Definitions by: York Yao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type DevTools = { + open: boolean; + orientation: "vertical" | "horizontal"; +} +interface DevToolsEvent extends Event { + detail: DevTools; +} +interface Window { + devtools: DevTools; + addEventListener(type: "devtoolschange", listener: (ev: DevToolsEvent) => any, useCapture?: boolean): void; +} diff --git a/diff2html/diff2html-tests.ts b/diff2html/diff2html-tests.ts new file mode 100644 index 0000000000..35448baa90 --- /dev/null +++ b/diff2html/diff2html-tests.ts @@ -0,0 +1,26 @@ +/// + +import Diff2Html = require('diff2html'); + +let d2h = Diff2Html.Diff2Html; + +class Diff2HtmlOptionsImpl implements Diff2Html.Options { + constructor (public inputFormat: string) { + } +} + +let strInput = + 'diff --git a/sample b/sample\n' + + 'index 0000001..0ddf2ba\n' + + '--- a/sample\n' + + '+++ b/sample\n' + + '@@ -1 +1 @@\n' + + '-test\n' + + '+test1r\n'; + +let strConfiguration = new Diff2HtmlOptionsImpl('diff'); +let diffInput = d2h.getJsonFromDiff(strInput, strConfiguration); + +let diffConfiguration = new Diff2HtmlOptionsImpl('json'); +let htmlString = d2h.getPrettyHtml(diffInput, diffConfiguration); +console.log(htmlString); diff --git a/diff2html/diff2html.d.ts b/diff2html/diff2html.d.ts new file mode 100644 index 0000000000..398cb1aba1 --- /dev/null +++ b/diff2html/diff2html.d.ts @@ -0,0 +1,66 @@ +// Type definitions for diff2html +// Project: https://github.com/rtfpessoa/diff2html +// Definitions by: rtfpessoa +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Diff2Html { + + export interface Options { + inputFormat?: string; + outputFormat?: string; + showFiles?: boolean; + matching?: string; + synchronisedScroll?: boolean; + matchWordsThreshold?: number; + matchingMaxComparisons?: number; + } + + export interface Line { + content: string; + type: string; + oldNumber: number; + newNumber: number; + } + + export interface Block { + oldStartLine: number; + oldStartLine2?: number; + newStartLine: number; + header: string; + lines: Line[]; + } + + export interface Result { + addedLines: number; + deletedLines: number; + isCombined: boolean; + isGitDiff: boolean; + oldName: string; + newName: string; + language: string; + blocks: Block[]; + oldMode?: string; + newMode?: string; + deletedFileMode?: string; + newFileMode?: string; + isDeleted?: boolean; + isNew?: boolean; + isCopy?: boolean; + isRename?: boolean; + unchangedPercentage?: number; + changedPercentage?: number; + checksumBefore?: string; + checksumAfter?: string; + mode?: string; + } + + export interface Diff2Html { + getJsonFromDiff(input: string, configuration?: Options): Result; + getPrettyHtml(input: any, configuration?: Options): string; + } +} + +declare module "diff2html" { + var d2h: { "Diff2Html": Diff2Html.Diff2Html }; + export = d2h; +} diff --git a/documentdb/documentdb.d.ts b/documentdb/documentdb.d.ts index 1d901179a6..b37cec9313 100644 --- a/documentdb/documentdb.d.ts +++ b/documentdb/documentdb.d.ts @@ -93,8 +93,13 @@ declare module 'documentdb' { /** Represents the result returned from a query. */ interface QueryIterator { - - toArray(callback: (error: QueryError, result: TResultRow[]) => void): void; + current(): TResultRow; + executeNext(callback: (error: QueryError, result: TResultRow[], responseHeaders? : any) => void): void; + forEach(iteratorFunction : (error: QueryError, element: TResultRow, responseHeaders? : any) => void): void; + hasMoreResults(): boolean; + nextItem(callback: (error : QueryError, item : TResultRow, responseHeaders? : any) => void): void; + reset() : void; + toArray(callback: (error: QueryError, result: TResultRow[], responseHeaders? : any) => void): void; } /** Reprents an object with a unique identifier. */ diff --git a/domurl/domurl-tests.ts b/domurl/domurl-tests.ts new file mode 100644 index 0000000000..825dcdd7d0 --- /dev/null +++ b/domurl/domurl-tests.ts @@ -0,0 +1,81 @@ +/// + +interface UModel extends QueryString { + a: any; + b: string; +} + +interface U2Model extends QueryString { + a: any; +} + +interface U3Model extends QueryString { + foo: string; +} + +var u = new Url(); // current document URL will be used +// or we can instantiate as +var u2 = new Url("http://example.com/some/path?a=b&c=d#someAnchor"); +// it should support relative URLs also +var u3 = new Url("/my/site/doc/path?foo=bar#baz"); + +// get the value of some query string parameter +console.log(u2.query.a); +// or +console.log(u3.query["foo"]); + +// Manipulating query string parameters +u.query.a = [1, 2, 3]; // adds/replaces in query string params a=1&a=2&a=3 +u.query.b = 'woohoo'; // adds/replaces in query string param b=woohoo + +if (u.query.a instanceof Array) { // the way to add a parameter + u.query.a.push(4); // now it's "a=1&a=2&a=3&a=4&b=woohoo" +} + +else { // if not an array but scalar value here is a way how to convert to array + u.query.a = [u.query.a]; + u.query.a.push(8) +} + + +// The way to remove the parameter: +delete u.query.a; +// or: +delete u.query["a"]; + +// If you need to remove all query string params: +console.log(u.clearQuery()); +console.log(u.queryLength()); +console.log(u.isEmptyQuery()); + +// Lookup URL parts: +console.log( + 'protocol = ' + u.protocol + '\n' + + 'user = ' + u.user + '\n' + + 'pass = ' + u.pass + '\n' + + 'host = ' + u.host + '\n' + + 'port = ' + u.port + '\n' + + 'path = ' + u.path + '\n' + + 'query = ' + u.query + '\n' + + 'hash = ' + u.hash +); + +// Manipulating URL parts +u.path = '/some/new/path'; // the way to change URL path +u.protocol = 'https'; // the way to force https protocol on the source URL + +// inject into string +var str = 'My Cool Link'; + +// or use in DOM context +var a = document.createElement('a'); +a.href = u.toString(); +a.innerHTML = 'test'; +document.body.appendChild(a); + +// Stringify +var su1 = u + ''; +var su2 = String(u); +var su3 = u.toString(); +// NOTE, that usually it will be done automatically, so only in special +// cases direct stringify is required diff --git a/domurl/domurl.d.ts b/domurl/domurl.d.ts new file mode 100644 index 0000000000..8c418c75cc --- /dev/null +++ b/domurl/domurl.d.ts @@ -0,0 +1,30 @@ +// Type definitions for domurl +// Project: https://github.com/Mikhus/domurl +// Definitions by: Mikhus +// Definitions: https://github.com/Mikhus/DefinitelyTyped + +declare class QueryString { + constructor(qs?: string); + toString: () => string; +} + +declare class Url { + constructor(url?: string); + query: T; + protocol: string; + user: string; + pass: string; + host: string; + port: string; + path: string; + hash: string; + href: string; + toString: () => string; + encode: (s: string) => string; + decode: (s: string) => string; + isAbsolute: () => boolean; + paths: (paths?: [string]) => [string]; + isEmptyQuery: () => boolean; + queryLength: () => number; + clearQuery: () => Url; +} diff --git a/dustjs-linkedin/dustjs-linkedin.d.ts b/dustjs-linkedin/dustjs-linkedin.d.ts index 70bd288a39..9bb05b1424 100644 --- a/dustjs-linkedin/dustjs-linkedin.d.ts +++ b/dustjs-linkedin/dustjs-linkedin.d.ts @@ -89,7 +89,7 @@ declare module "dustjs-linkedin" { * Registers an event listener. Streams accept a single listener for a given event. * @param evt the event. Possible values are data, end, error (maybe more, look in the source). */ - on(evt: string, callback: (data?: any) => any); + on(evt: string, callback: (data?: any) => any): this; pipe(stream: Stream): Stream; } @@ -126,8 +126,8 @@ declare module "dustjs-linkedin" { * @param name the template name. * @param context a plain object or an instance of dust.Context. */ - export function render(name: string, context: any, callback: (err: any, out: string) => any); - export function render(name: string, context: Context, callback: (err: any, out: string) => any); + export function render(name: string, context: any, callback: (err: any, out: string) => any): void; + export function render(name: string, context: Context, callback: (err: any, out: string) => any): void; /** * Compiles and renders source, invoking callback on completion. If no callback is supplied this function returns a Stream object. Use this function when precompilation is not required. diff --git a/elasticsearch/elasticsearch-tests.ts b/elasticsearch/elasticsearch-tests.ts index 9a85f2c908..14070aa8cc 100644 --- a/elasticsearch/elasticsearch-tests.ts +++ b/elasticsearch/elasticsearch-tests.ts @@ -32,4 +32,17 @@ client.indices.delete({ ignore: [404] }).then(function (body) { }, function (error) { +}); + +client.create({ + id: '123', + index: 'index', + type: 'type' +}); + +client.create({ + id: '123', + index: 'index', + type: 'type' +}, (err, repsonse, status) => { }); \ No newline at end of file diff --git a/elasticsearch/elasticsearch.d.ts b/elasticsearch/elasticsearch.d.ts index b06c11f6bc..ec67e6a59d 100644 --- a/elasticsearch/elasticsearch.d.ts +++ b/elasticsearch/elasticsearch.d.ts @@ -9,6 +9,8 @@ declare module Elasticsearch { indices: Indices; bulk(params: BulkIndexDocumentsParams): PromiseLike; bulk(params: BulkIndexDocumentsParams, callback: (error: any, response: any) => void): void; + create(params: CreateDocumentParams): PromiseLike; + create(params: CreateDocumentParams, callback: (err: any, response: any, status: any) => void): void; delete(params: DeleteDocumentParams): PromiseLike; delete(params: DeleteDocumentParams, callback: (error: any, response: any) => void): void; get(params: GetParams, callback: (error: any, response: any) => void): void; @@ -102,6 +104,21 @@ declare module Elasticsearch { index?: string; } + export interface CreateDocumentParams extends GenericParams { + consistency?: "one" | "quorum" | "all"; + parent?: string; + refressh?: boolean; + routing?: string; + timeout?: number | Date; + timestamp?: number | Date; + ttl?: number; + version?: number; + versionType?: "internal" | "external" | "external_gte" | "force"; + id: string; + index: string; + type: string; + } + export interface IndicesGetParams extends GenericParams { ignoreUnavailable?: boolean; index: string | string[] | boolean; diff --git a/electron-notifications/electron-notifications-tests.ts b/electron-notifications/electron-notifications-tests.ts new file mode 100644 index 0000000000..7730747acc --- /dev/null +++ b/electron-notifications/electron-notifications-tests.ts @@ -0,0 +1,13 @@ +/// + +import * as notifier from 'electron-notifications'; + +const data: ElectronNotifications.NotifierOptions = { + message: 'message', + icon: 'icon', + buttons: ['ok', 'cancel'] +}; +const notification = notifier.notify('title', data); +notification.on('clicked', () => { console.log('clicked') }); +notification.on('swipedRight', () => { console.log('swipedRight') }); +notification.on('buttonClicked', (text) => { console.log(`buttonClicked: ${text}`) }); \ No newline at end of file diff --git a/electron-notifications/electron-notifications.d.ts b/electron-notifications/electron-notifications.d.ts new file mode 100644 index 0000000000..5cbb655246 --- /dev/null +++ b/electron-notifications/electron-notifications.d.ts @@ -0,0 +1,41 @@ +// Type definitions for electron-notifications v0.0.3 +// Project: https://github.com/blainesch/electron-notifications +// Definitions by: Daniel Pereira +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace ElectronNotifications { + + interface NotifierOptions { + + /** A message to display under the title. */ + message?: string, + + /** The absolute URL of a icon displayed to the left of the text. */ + icon?: string, + + /** One or two buttons to display on the right of the notification. */ + buttons?: string[] + } + + class NotificationWindow extends Electron.BrowserWindow { + + /** When the notification was clicked, but not dragged. This usually does the default action, or closes the notification. */ + on(event: 'clicked', listener: Function): this; + + /** When the notification has been swiped to the right. This usually indiciated the user wants to dismiss the notification. */ + on(event: 'swipedRight', listener: Function): this; + + /** When any one of the buttons are clicked, it will trigger a buttonClicked event, and pass the text that was clicked to the handler. */ + on(event: 'buttonClicked', listener: (text: string) => void): this; + + on(event: string, listener: Function): this; + } + +} + +/** A node module for sending notifications in electron applications */ +declare module 'electron-notifications' { + export function notify(title: string, data?: ElectronNotifications.NotifierOptions): ElectronNotifications.NotificationWindow; +} \ No newline at end of file diff --git a/electron-notify/electron-notify-tests.ts b/electron-notify/electron-notify-tests.ts new file mode 100644 index 0000000000..95e2edf998 --- /dev/null +++ b/electron-notify/electron-notify-tests.ts @@ -0,0 +1,26 @@ +/// + +import * as eNotify from 'electron-notify'; + +eNotify.setConfig({ + appIcon: 'images/otherIcon.png', + displayTime: 6000, + defaultStyleText: { + color: '#FF0000', + fontWeight: 'bold' + } +}); + +eNotify.notify({ + title: 'Title', + text: 'Some text', + image: 'path/to/image.png', + url: 'http://google.de', + sound: 'notification.wav', + onClickFunc: (event) => { + console.log('onClick ' + event.id); + event.closeNotification('onClick'); + }, + onShowFunc: (event) => { console.log('onShow ' + event.id) }, + onCloseFunc: (event) => { console.log('onClose ' + event.id) } +}); \ No newline at end of file diff --git a/electron-notify/electron-notify.d.ts b/electron-notify/electron-notify.d.ts new file mode 100644 index 0000000000..b29efa0e50 --- /dev/null +++ b/electron-notify/electron-notify.d.ts @@ -0,0 +1,64 @@ +// Type definitions for electron-notify v0.1.0 +// Project: https://github.com/hankbao/electron-notify +// Definitions by: Daniel Pereira +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** Nice and simple notifications for electron apps */ +declare module 'electron-notify' { + + export interface ICustomConfig { + width?: number, + height?: number, + padding?: number, + borderRadius?: number, + displayTime?: number, + animationSteps?: number, + animationStepMs?: number, + animateInParallel?: boolean, + appIcon?: string, + pathToModule?: string, + logging?: boolean, + defaultWindow?: Electron.BrowserWindowOptions, + defaultStyleContainer?: any, + defaultStyleAppIcon?: any, + defaultStyleImage?: any, + defaultStyleClose?: any, + defaultStyleText?: any + } + + export interface ICloseNotificationEvent { + event: 'close' | 'show' | 'click', + id: number + } + + export interface INotificationEvent extends ICloseNotificationEvent { + closeNotification: (reason: any) => void, + } + + export interface INotification { + title: string, + text?: string, + image?: string, + url?: string, + sound?: string, + onClickFunc?: (event: INotificationEvent) => void, + onShowFunc?: (event: INotificationEvent) => void, + onCloseFunc?: (event: ICloseNotificationEvent) => void + } + + /** Change some config options. Can be run multiple times, also between notify()-calls to change electron-notifys behaviour. */ + export function setConfig(customConfig: ICustomConfig): void; + + /** Displays new notification. */ + export function notify(notification: INotification): void; + + /** Clears the animation queue and closes all windows opened by electron-notify. Call this to clean up before quiting your app. */ + export function closeAll(): void; + + export function getTemplatePath(): string; + + export function setTemplatePath(path: string): void; + +} \ No newline at end of file diff --git a/epub/epub-tests.ts b/epub/epub-tests.ts new file mode 100644 index 0000000000..6e61a26634 --- /dev/null +++ b/epub/epub-tests.ts @@ -0,0 +1,9 @@ +/// +import EPub = require("epub"); + +var epub = new EPub("./file.epub"); +epub.on("end", function(){ + epub.getChapter("chapter_id", function(err: Error, text: string) {}); +}); + +epub.parse(); diff --git a/epub/epub.d.ts b/epub/epub.d.ts new file mode 100644 index 0000000000..7c813e003d --- /dev/null +++ b/epub/epub.d.ts @@ -0,0 +1,66 @@ +// Type definitions for epub +// Project: https://github.com/julien-c/epub +// Definitions by: Julien Chaumond +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** + * new EPub(fname[, imageroot][, linkroot]) + * - fname (String): filename for the ebook + * - imageroot (String): URL prefix for images + * - linkroot (String): URL prefix for links + * + * Creates an Event Emitter type object for parsing epub files + * + * var epub = new EPub("book.epub"); + * epub.on("end", function () { + * console.log(epub.spine); + * }); + * epub.on("error", function (error) { ... }); + * epub.parse(); + * + * Image and link URL format is: + * + * imageroot + img_id + img_zip_path + * + * So an image "logo.jpg" which resides in "OPT/" in the zip archive + * and is listed in the manifest with id "logo_img" will have the + * following url (providing that imageroot is "/images/"): + * + * /images/logo_img/OPT/logo.jpg + **/ +declare module "epub" { + + import {EventEmitter} from "events"; + + interface TocElement { + level: number; + order: number; + title: string; + id: string; + href?: string; + } + + class EPub extends EventEmitter { + constructor(epubfile: string, imagewebroot?: string, chapterwebroot?: string); + + metadata: Object; + manifest: Object; + spine: Object; + flow: Array; + toc: Array; + + parse(): void; + + getChapter(chapterId: string, callback: (error: Error, text: string) => void): void; + + getChapterRaw(chapterId: string, callback: (error: Error, text: string) => void): void; + + getImage(id: string, callback: (error: Error, data: Buffer, mimeType: string) => void): void; + + getFile(id: string, callback: (error: Error, data: Buffer, mimeType: string) => void): void; + } + + export = EPub; +} diff --git a/esprima-walk/esprima-walk-tests.ts b/esprima-walk/esprima-walk-tests.ts new file mode 100644 index 0000000000..4588ebb615 --- /dev/null +++ b/esprima-walk/esprima-walk-tests.ts @@ -0,0 +1,25 @@ +/// +/// + +import * as walk from 'esprima-walk' + +var program: ESTree.Program +var string: string +var node: ESTree.Node + +walk(program, _node => { + string = node.type + node = _node +}) + +walk.walk(program, _node => { + string = node.type + node = _node +}) + +walk.walkAddParent(program, _node => { + node = _node + node = _node.parent + string = node.type +}) + diff --git a/esprima-walk/esprima-walk.d.ts b/esprima-walk/esprima-walk.d.ts new file mode 100644 index 0000000000..d18cf96bb1 --- /dev/null +++ b/esprima-walk/esprima-walk.d.ts @@ -0,0 +1,40 @@ +// Type definitions for esprima-walk v0.1.0 +// Project: https://github.com/jrajav/esprima-walk +// Definitions by: tswaters +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "esprima-walk" { + + interface NodeWithParent extends ESTree.Node { + parent?: ESTree.Node + } + + /** + * Walk the provided AST; fn is called once for each node with a `type` + * @param {ESTree.Program} ast program to walk + * @param {function} fn function invoked for each node with type + */ + function walk (ast: ESTree.Program, fn:(node: ESTree.Node)=>void) :void + + namespace walk { + /** + * Walk the provided AST; fn is called once for each node with a `type` + * @param {ESTree.Program} ast program to walk + * @param {function} fn function invoked for each node + */ + export function walk (ast: ESTree.Program, fn:(node: ESTree.Node)=>void) :void + + /** + * Walk the provided AST; fn is called once for each node with a `type`. + * Adds a parent property prior to invoking fn when applicable + * @param {ESTree.Program} ast program to walk + * @param {function} fn function invoked for each node + */ + export function walkAddParent (ast: ESTree.Program, fn:(node: NodeWithParent)=>void) :void + } + + export = walk +} + diff --git a/esprima/esprima-tests.ts b/esprima/esprima-tests.ts index f1a0f7ad92..2bca0d5e54 100644 --- a/esprima/esprima-tests.ts +++ b/esprima/esprima-tests.ts @@ -12,6 +12,7 @@ var string: string; string = esprima.version; program = esprima.parse('code'); program = esprima.parse('code', {range: true}); +program = esprima.parse('import * as code from "code"', {sourceType: 'module'}) token = esprima.tokenize('code')[0]; token = esprima.tokenize('code', {range: true})[0]; diff --git a/esprima/esprima.d.ts b/esprima/esprima.d.ts index 30fe9512bf..64a9333fa3 100644 --- a/esprima/esprima.d.ts +++ b/esprima/esprima.d.ts @@ -30,6 +30,7 @@ declare namespace esprima { attachComment?: boolean; tolerant?: boolean; source?: boolean; + sourceType?: 'script' | 'module'; } const Syntax: { diff --git a/eventemitter2/eventemitter2.d.ts b/eventemitter2/eventemitter2.d.ts index 39a349c6b6..de1be0d064 100644 --- a/eventemitter2/eventemitter2.d.ts +++ b/eventemitter2/eventemitter2.d.ts @@ -43,7 +43,7 @@ declare class EventEmitter2 { * @param event * @param listener */ - on(event: string, listener: Function): EventEmitter2; + on(event: string | string[], listener: Function): EventEmitter2; /** * Adds a listener that will be fired when any event is emitted. @@ -128,7 +128,7 @@ declare class EventEmitter2 { * @param event * @param args */ - emit(event: string, ...args: any[]): boolean; + emit(event: string | string[], ...args: any[]): boolean; /** * Execute each of the listeners that may be listening for the specified event name in order with the list of arguments. @@ -156,7 +156,7 @@ declare module "eventemitter2" { * @param event * @param listener */ - on(event: string, listener: Function): EventEmitter2; + on(event: string | string[], listener: Function): EventEmitter2; /** * Adds a listener that will be fired when any event is emitted. @@ -241,7 +241,7 @@ declare module "eventemitter2" { * @param event * @param args */ - emit(event: string, ...args: any[]): boolean; + emit(event: string | string[], ...args: any[]): boolean; /** * Execute each of the listeners that may be listening for the specified event name in order with the list of arguments. diff --git a/express-serve-static-core/express-serve-static-core.d.ts b/express-serve-static-core/express-serve-static-core.d.ts index de91c521cc..93551ffece 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -22,7 +22,7 @@ declare module "express-serve-static-core" { } interface RequestHandler { - (req: Request, res: Response, next: NextFunction): any; + (req: Request, res: Response, next?: NextFunction): any; } interface ErrorRequestHandler { @@ -117,11 +117,11 @@ declare module "express-serve-static-core" { interface CookieOptions { maxAge?: number; signed?: boolean; - expires?: Date; + expires?: Date | boolean; httpOnly?: boolean; path?: string; domain?: string; - secure?: boolean; + secure?: boolean | 'auto'; } interface Errback { (err: Error): void; } @@ -199,7 +199,7 @@ declare module "express-serve-static-core" { /** * Returns the first accepted charset of the specified character sets, - * based on the request’s Accept-Charset HTTP header field. + * based on the request's Accept-Charset HTTP header field. * If none of the specified charsets is accepted, returns false. * * For more information, or if you have issues or concerns, see accepts. @@ -212,7 +212,7 @@ declare module "express-serve-static-core" { /** * Returns the first accepted encoding of the specified encodings, - * based on the request’s Accept-Encoding HTTP header field. + * based on the request's Accept-Encoding HTTP header field. * If none of the specified encodings is accepted, returns false. * * For more information, or if you have issues or concerns, see accepts. @@ -225,7 +225,7 @@ declare module "express-serve-static-core" { /** * Returns the first accepted language of the specified languages, - * based on the request’s Accept-Language HTTP header field. + * based on the request's Accept-Language HTTP header field. * If none of the specified languages is accepted, returns false. * * For more information, or if you have issues or concerns, see accepts. diff --git a/express-session/express-session-tests.ts b/express-session/express-session-tests.ts index 1e1f909b14..0b8460214f 100644 --- a/express-session/express-session-tests.ts +++ b/express-session/express-session-tests.ts @@ -6,7 +6,8 @@ import session = require('express-session'); var app = express(); app.use(session({ - secret: 'keyboard cat' + secret: 'keyboard cat', + cookie: { secure: 'auto' } })); app.use(session({ secret: 'keyboard cat', diff --git a/express-session/express-session.d.ts b/express-session/express-session.d.ts index 156e9404fc..90e1ed07cc 100644 --- a/express-session/express-session.d.ts +++ b/express-session/express-session.d.ts @@ -30,7 +30,7 @@ declare namespace Express { secure?: boolean; httpOnly: boolean; domain?: string; - expires: Date; + expires: Date | boolean; serialize: (name: string, value: string) => string; } } diff --git a/express-validator/express-validator-tests.ts b/express-validator/express-validator-tests.ts index 74bd277e46..ebd61d6cfc 100644 --- a/express-validator/express-validator-tests.ts +++ b/express-validator/express-validator-tests.ts @@ -15,19 +15,23 @@ app.post('/:urlparam', function(req: express.Request, res: express.Response) { // Similarly checkParams only checks in req.params (URL params) and // checkQuery only checks req.query (GET params). req.checkBody('postparam', 'Invalid postparam').notEmpty().isInt(); - req.checkParams('urlparam', 'Invalid urlparam').isAlpha(); + req.checkParams('urlparam', 'Invalid urlparam').isAlpha().matches(/test?/i).matches('test?', 'i'); req.checkQuery('getparam', 'Invalid getparam').isInt(); - req.checkHeader('testHeader', 'Invalid testHeader').isLowercase().isUppercase(); - req.checkFiles('testFiles', 'Invalid testFiles').isUrl(); - + req.checkHeaders('testHeader', 'Invalid testHeader').isLowercase().isUppercase(); + req.checkFiles('testFiles', 'Invalid testFiles').isURL(); // OR assert can be used to check on all 3 types of params. // req.assert('postparam', 'Invalid postparam').notEmpty().isInt(); // req.assert('urlparam', 'Invalid urlparam').isAlpha(); // req.assert('getparam', 'Invalid getparam').isInt(); - req.sanitize('postparam').toBoolean(); req.filter('postparam').toBoolean(); + req.sanitize('postparam').blacklist('t').blacklist(['']).whitelist('hello').whitelist(['h', 'e', 'l']); + req.sanitizeBody('postvar').trim().stripLow().escape(); + req.sanitizeQuery('queryvar').toDate(); + req.sanitizeParams('urlparam').toFloat().toInt().toInt(10); + req.sanitizeHeaders('header').normalizeEmail(); + var errors = req.validationErrors(); var mappedErrors = req.validationErrors(true); diff --git a/express-validator/express-validator.d.ts b/express-validator/express-validator.d.ts index 52792a391f..3599b9b79b 100644 --- a/express-validator/express-validator.d.ts +++ b/express-validator/express-validator.d.ts @@ -1,9 +1,10 @@ -// Type definitions for express-validator 2.9.0 +// Type definitions for express-validator 2.20.4 // Project: https://github.com/ctavan/express-validator -// Definitions by: Nathan Ridley , Jonathan Häberle +// Definitions by: Nathan Ridley , Jonathan Häberle , Peter Harris // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +/// // Add RequestValidation Interface on to Express's Request Interface. declare namespace Express { @@ -31,25 +32,33 @@ declare namespace ExpressValidator { param: string; } - interface ValidatorFunction { (item: string, message: string): Validator; } + interface ValidatorFunction { (item: string | {}, message?: string): Validator; } + interface ValidatorExtraFunction extends ValidatorFunction { (matchIndex: number, message?: string): Validator; } interface SanitizerFunction { (item: string): Sanitizer; } interface Dictionary { [key: string]: T; } export interface RequestValidation { - assert: ValidatorFunction; - check: ValidatorFunction; + assert: ValidatorExtraFunction; + validate: ValidatorExtraFunction; + check: ValidatorExtraFunction; checkBody: ValidatorFunction; checkFiles: ValidatorFunction; - checkHeader: ValidatorFunction; + checkHeaders: ValidatorFunction; checkParams: ValidatorFunction; checkQuery: ValidatorFunction; - validate: ValidatorFunction; - + filter: SanitizerFunction; sanitize: SanitizerFunction; - + sanitizeBody: SanitizerFunction; + sanitizeQuery: SanitizerFunction; + sanitizeParams: SanitizerFunction; + sanitizeHeaders: SanitizerFunction; + onValidationError(errback: (msg: string) => void): void; - validationErrors(mapped?: boolean): Dictionary | any[]; + validationErrors(mapped?: boolean): Dictionary | MappedError[]; + validationErrors(mapped?: boolean): Dictionary | T[]; + asyncValidationErrors(mapped?: boolean): Promise>; + asyncValidationErrors(mapped?: boolean): Promise>; } export interface Validator { @@ -61,12 +70,13 @@ declare namespace ExpressValidator { * Alias for notRegex() */ not(): Validator; - isEmail(): Validator; + isEmail(options?:{}): Validator; /** * Accepts http, https, ftp */ - isUrl(): Validator; - + isURL(): Validator; + isFQDN(options?: MinMaxOptions): Validator; + /** * Combines isIPv4 and isIPv6 */ @@ -74,8 +84,21 @@ declare namespace ExpressValidator { isIPv4(): Validator; isIPv6(): Validator; isMACAddress(): Validator; - isAlpha(): Validator; - isAlphanumeric(): Validator; + isISBN(version?: number): Validator; + isISIN(): Validator; + isISO8601(): Validator; + isMobilePhone(locale: string): Validator; + isMongoId(): Validator; + isMultibyte(): Validator; + isAlpha(locale?: string): Validator; + isAlphanumeric(locale?: string): Validator; + isAscii(): Validator; + isBase64(): Validator; + isBoolean(): Validator; + isByteLength(options: MinMaxOptions): Validator; + isCurrency(options: {}): Validator; + isDataURI(): Validator; + isDivisibleBy(num: number): Validator; isNumeric(): Validator; isHexadecimal(): Validator; /** @@ -85,7 +108,7 @@ declare namespace ExpressValidator { /** * isNumeric accepts zero padded numbers, e.g. '001', isInt doesn't */ - isInt(): Validator; + isInt(options?: MinMaxOptions): Validator; isLowercase(): Validator; isUppercase(): Validator; isDecimal(): Validator; @@ -93,10 +116,12 @@ declare namespace ExpressValidator { * Alias for isDecimal */ isFloat(): Validator; + isFullWidth(): Validator; + isHalfWidth(): Validator; + isVariableWidth(): Validator; /** * Check if length is 0 */ - notNull(): Validator; isNull(): Validator; /** * Not just whitespace (input.trim().length !== 0) @@ -104,12 +129,13 @@ declare namespace ExpressValidator { notEmpty(): Validator; equals(equals:any): Validator; contains(str:string): Validator; - notContains(str:string): Validator; + /** - * Usage: regex(/[a-z]/i) or regex('[a-z]','i') + * Usage: matches(/[a-z]/i) or matches('[a-z]','i') */ - regex(pattern:string, modifiers:string): Validator; - notRegex(pattern:string, modifiers:string): Validator; + matches(pattern:string, modifiers?:string): Validator; + matches(pattern: RegExp): Validator; + /** * max is optional */ @@ -117,7 +143,7 @@ declare namespace ExpressValidator { /** * Version can be 3, 4 or 5 or empty, see http://en.wikipedia.org/wiki/Universally_unique_identifier */ - isUUID(version:number): Validator; + isUUID(version?:number): Validator; /** * Alias for isUUID(3) */ @@ -137,17 +163,20 @@ declare namespace ExpressValidator { /** * Argument is optional and defaults to today. Comparison is non-inclusive */ - isAfter(date:Date): Validator; + isAfter(date?:Date): Validator; /** * Argument is optional and defaults to today. Comparison is non-inclusive */ - isBefore(date:Date): Validator; + isBefore(date?:Date): Validator; isIn(options:string): Validator; isIn(options:string[]): Validator; notIn(options:string): Validator; notIn(options:string[]): Validator; max(val:string): Validator; min(val:string): Validator; + isJSON(): Validator; + isLength(options: MinMaxOptions): Validator; + isWhitelisted(chars: string): Validator; /** * Will work against Visa, MasterCard, American Express, Discover, Diners Club, and JCB card numbering formats */ @@ -155,7 +184,10 @@ declare namespace ExpressValidator { /** * Check an input only when the input exists */ - optional(): Validator; + isSurrogatePar(): Validator; + + optional(options?: { checkFalsy?: boolean }): Validator; + withMessage(message: string): Validator; } interface Sanitizer { @@ -165,40 +197,49 @@ declare namespace ExpressValidator { trim(...chars:string[]): Sanitizer; ltrim(...chars:string[]): Sanitizer; rtrim(...chars:string[]): Sanitizer; - ifNull(replace:any): Sanitizer; + stripLow(keep_new_lines?: boolean): Sanitizer; toFloat(): Sanitizer; - toInt(): Sanitizer; + toInt(radix?: number): Sanitizer; /** - * True unless str = '0', 'false', or str.length == 0 - */ - toBoolean(): Sanitizer; - /** - * False unless str = '1' or 'true' - */ - toBooleanStrict(): Sanitizer; - /** - * Decode HTML entities + * True unless str = '0', 'false', or str.length == 0. In strict mode only '1' and 'true' return true. */ + toBoolean(strict?: boolean): Sanitizer; /** - * Convert the input string to a date, or null if the input is not a date. - */ - toDate(): Sanitizer; - - entityDecode(): Sanitizer; - entityEncode(): Sanitizer; + * Convert the input string to a date, or null if the input is not a date. + */ + toDate(): Sanitizer; + /** * Escape &, <, >, and " */ escape(): Sanitizer; + /** - * Remove common XSS attack vectors from user-supplied HTML + * Replaces HTML encoded entities with <, >, &, ', " and /. */ - xss(): Sanitizer; + unescape(): Sanitizer; + + blacklist(chars: string): Sanitizer; + blacklist(chars: string[]): Sanitizer; + whitelist(chars: string): Sanitizer; + whitelist(chars: string[]): Sanitizer; + + normalizeEmail(options?: { lowercase?: boolean; remove_dots?: boolean; remove_extensions?: boolean }): Sanitizer; + /** - * Remove common XSS attack vectors from images + * !!! XSS sanitization was removed from the library (see: https://github.com/chriso/validator.js#xss-sanitization) */ - xss(fromImages:boolean): Sanitizer; } - + + interface MappedError { + param: string; + msg: string; + value: string; + } + + interface MinMaxOptions { + min?: number; + max?: number; + } } diff --git a/express/express-tests.ts b/express/express-tests.ts index ed9265b66a..439ef95012 100644 --- a/express/express-tests.ts +++ b/express/express-tests.ts @@ -1,4 +1,5 @@ /// +/// import * as express from 'express'; var app = express(); @@ -91,3 +92,10 @@ app.listen(3000); const next: express.NextFunction = () => {}; const nextWithArgument: express.NextFunction = (err: any) => {}; + +/** + * The express.Application is compatible with http.createServer + */ + +import * as http from 'http'; +http.createServer(app); diff --git a/fetch-mock/fetch-mock-tests.ts b/fetch-mock/fetch-mock-tests.ts index defefa25a1..b630668e18 100644 --- a/fetch-mock/fetch-mock-tests.ts +++ b/fetch-mock/fetch-mock-tests.ts @@ -30,3 +30,15 @@ fetchMock.called("http://test.com"); (fetchMock.lastCall()[1] as RequestInit).body; fetchMock.lastUrl(); fetchMock.lastOptions(); + +fetchMock.get("http://test.com", 200) +fetchMock.post("http://test.com", 200) +fetchMock.put("http://test.com", 200) +fetchMock.delete("http://test.com", 200) +fetchMock.head("http://test.com", 200) + +fetchMock.get("http://test.com", 200, {method: "GET"}) +fetchMock.post("http://test.com", 200, {method: "POST"}) +fetchMock.put("http://test.com", 200, {method: "PUT"}) +fetchMock.delete("http://test.com", 200, {method: "DELETE"}) +fetchMock.head("http://test.com", 200, {method: "HEAD"}) diff --git a/fetch-mock/fetch-mock.d.ts b/fetch-mock/fetch-mock.d.ts index 490b4c7dfd..47c31e4c64 100644 --- a/fetch-mock/fetch-mock.d.ts +++ b/fetch-mock/fetch-mock.d.ts @@ -114,6 +114,26 @@ declare module "fetch-mock" { unmatched: Array; } + interface MockOptionsMethodGet extends MockOptions { + method: 'GET' + } + + interface MockOptionsMethodPost extends MockOptions { + method: 'POST' + } + + interface MockOptionsMethodPut extends MockOptions { + method: 'PUT' + } + + interface MockOptionsMethodDelete extends MockOptions { + method: 'DELETE' + } + + interface MockOptionsMethodHead extends MockOptions { + method: 'HEAD' + } + interface FetchMockStatic { /** * Replaces fetch() with a stub which records its calls, grouped by @@ -139,6 +159,56 @@ declare module "fetch-mock" { * @param options The route to mock */ mock(options: MockOptions): this; + /** + * Replaces fetch() with a stub which records its calls, grouped by + route, and optionally returns a mocked Response object or passes the + call through to fetch(). Shorthand for mock() restricted to the GET + method. Calls to .mock() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + get(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodGet): this; + /** + * Replaces fetch() with a stub which records its calls, grouped by + route, and optionally returns a mocked Response object or passes the + call through to fetch(). Shorthand for mock() restricted to the POST + method. Calls to .mock() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + post(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodPost): this; + /** + * Replaces fetch() with a stub which records its calls, grouped by + route, and optionally returns a mocked Response object or passes the + call through to fetch(). Shorthand for mock() restricted to the PUT + method. Calls to .mock() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + put(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodPut): this; + /** + * Replaces fetch() with a stub which records its calls, grouped by + route, and optionally returns a mocked Response object or passes the + call through to fetch(). Shorthand for mock() restricted to the + DELETE method. Calls to .mock() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + delete(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodDelete): this; + /** + * Replaces fetch() with a stub which records its calls, grouped by + route, and optionally returns a mocked Response object or passes the + call through to fetch(). Shorthand for mock() restricted to the HEAD + method. Calls to .mock() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + head(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodHead): this; /** * Chainable method that restores fetch() to its unstubbed state and clears all data recorded for its calls. diff --git a/file-type/file-type-tests.ts b/file-type/file-type-tests.ts new file mode 100644 index 0000000000..ebbee83783 --- /dev/null +++ b/file-type/file-type-tests.ts @@ -0,0 +1,7 @@ +/// + +"use strict"; + +import fileType = require("file-type") + +fileType(new Buffer([0xFF, 0xD8, 0xFF])) diff --git a/file-type/file-type.d.ts b/file-type/file-type.d.ts new file mode 100644 index 0000000000..58c449ca3c --- /dev/null +++ b/file-type/file-type.d.ts @@ -0,0 +1,17 @@ +// Type definitions for file-type +// Project: https://github.com/sindresorhus/file-type +// Definitions by: KIM Jaesuck a.k.a. gim tcaesvk +// Definitions: https://github.com/DefinitelyType/DefinitelyTyped + +/// + +declare module "file-type" { + interface FileTypeResult { + ext: string + mime: string + } + + function FileType(buf: Buffer): FileTypeResult + + export = FileType +} diff --git a/fill-pdf/fill-pdf-tests.ts b/fill-pdf/fill-pdf-tests.ts new file mode 100644 index 0000000000..e5b34cd943 --- /dev/null +++ b/fill-pdf/fill-pdf-tests.ts @@ -0,0 +1,17 @@ +/// + +import * as fillPdf from 'fill-pdf'; + +var formData: fillPdf.FormData = { FieldName: 'Text to put into form field' }; +var pdfTemplatePath = 'templates.pdf'; +var extendArgs: string[] = []; + +fillPdf.generatePdf(formData, pdfTemplatePath, extendArgs, (err: Error, output: Buffer) => { + if ( !err ) { + console.log('Success!'); + // output is a buffer + } +}); + +var result = fillPdf.generateFdf(formData); +// result is a buffer diff --git a/fill-pdf/fill-pdf.d.ts b/fill-pdf/fill-pdf.d.ts new file mode 100644 index 0000000000..d35057f934 --- /dev/null +++ b/fill-pdf/fill-pdf.d.ts @@ -0,0 +1,16 @@ +// Type definitions for fill-pdf v0.5.0 +// Project: https://github.com/dommmel/fill-pdf +// Definitions by: Seth Westphal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'fill-pdf' { + + export interface FormData { + [name: string]: string; + } + + export function generatePdf(data: FormData, templatePath: string, extendArgs: string[], callback?: (err: Error, output: Buffer) => void): void; + export function generateFdf(data: FormData): Buffer; +} diff --git a/fluent-ffmpeg/fluent-ffmpeg-tests.ts b/fluent-ffmpeg/fluent-ffmpeg-tests.ts new file mode 100644 index 0000000000..8b1031ff58 --- /dev/null +++ b/fluent-ffmpeg/fluent-ffmpeg-tests.ts @@ -0,0 +1,7 @@ +/// + +import ffmpeg = require("fluent-ffmpeg") + +let source: string, format: string, output: string + +ffmpeg({ source: source }).format(format).save(output) diff --git a/fluent-ffmpeg/fluent-ffmpeg.d.ts b/fluent-ffmpeg/fluent-ffmpeg.d.ts new file mode 100644 index 0000000000..92e1a33891 --- /dev/null +++ b/fluent-ffmpeg/fluent-ffmpeg.d.ts @@ -0,0 +1,315 @@ +// Type definitions for node-fluent-ffmpeg +// Project: https://github.com/fluent-ffmpeg/node-fluent-ffmpeg +// Definitions by: KIM Jaesuck a.k.a. gim tcaesvk +// Definitions: https://github.com/DefinitelyType/DefinitelyTyped + +/// + +declare module "fluent-ffmpeg" { + import * as events from "events" + import * as stream from "stream" + + interface FfmpegCommandLogger { + error(...data: any[]): void + warning(...data: any[]): void + info(...data: any[]): void + debug(...data: any[]): void + } + + interface FfmpegCommandOptions { + logger?: FfmpegCommandLogger + niceness?: number + priority?: number + presets?: string + preset?: string + stdoutLines?: number + timeout?: number + source?: string | stream.Readable + } + + interface FilterSpecification { + filter: string + inputs: string | string[] + outputs: string | string[] + options?: Object | string | any[] + } + + interface GetPreset { + (command: FfmpegCommand): string + } + + interface Filter { + description: string + input: string + multipleInputs: boolean + output: string + multipleOutputs: boolean + } + interface Filters { + [key: string]: Filter + } + interface FiltersCallback { + (err: Error, filters: Filters): void + } + + interface Codec { + type: string + description: string + canDecode: boolean + canEncode: boolean + drawHorizBand?: boolean + directRendering?: boolean + weirdFrameTruncation?: boolean + intraFrameOnly?: boolean + isLossy?: boolean + isLossless?: boolean + } + interface Codecs { + [key: string]: Codec + } + interface CodecsCallback { + (err: Error, codecs: Codecs): void + } + + interface Encoder { + type: string + description: string + frameMT: boolean + sliceMT: boolean + experimental: boolean + drawHorizBand: boolean + directRendering: boolean + } + interface Encoders { + [key: string]: Encoder + } + interface EncodersCallback { + (err: Error, encoders: Encoders): void + } + + interface Format { + description: string + canDemux: boolean + canMux: boolean + } + interface Formats { + [key: string]: Format + } + interface FormatsCallback { + (err: Error, formats: Formats): void + } + + interface FfprobeData { + stream: any[] + format: any + chapters: any[] + } + + interface ScreenshotsConfig { + count?: number + folder?: string + filename?: string + timemarks?: number[] | string[] + timestamps?: number[] | string[] + fastSeek?: boolean + size?: string + } + + interface FfmpegCommand extends events.EventEmitter { + constructor(): FfmpegCommand + constructor(options: FfmpegCommandOptions): FfmpegCommand + constructor(input: string | stream.Readable, options: FfmpegCommandOptions): FfmpegCommand + + // options/inputs + mergeAdd(source: string | stream.Readable): FfmpegCommand + addInput(source: string | stream.Readable): FfmpegCommand + input(source: string | stream.Readable): FfmpegCommand + withInputFormat(format: string): FfmpegCommand + inputFormat(format: string): FfmpegCommand + fromFormat(format: string): FfmpegCommand + withInputFps(fps: number): FfmpegCommand + withInputFPS(fps: number): FfmpegCommand + withFpsInput(fps: number): FfmpegCommand + withFPSInput(fps: number): FfmpegCommand + inputFPS(fps: number): FfmpegCommand + inputFps(fps: number): FfmpegCommand + fpsInput(fps: number): FfmpegCommand + FPSInput(fps: number): FfmpegCommand + nativeFramerate(): FfmpegCommand + withNativeFramerate(): FfmpegCommand + native(): FfmpegCommand + setStartTime(seek: string | number): FfmpegCommand + seekInput(seek: string | number): FfmpegCommand + loop(duration: string | number): FfmpegCommand + + // options/audio + withNoAudio(): FfmpegCommand + noAudio(): FfmpegCommand + withAudioCodec(codec: string): FfmpegCommand + audioCodec(codec: string): FfmpegCommand + withAudioBitrate(bitrate: string | number): FfmpegCommand + audioBitrate(bitrate: string | number): FfmpegCommand + withAudioChannels(channels: number): FfmpegCommand + audioChannels(channels: number): FfmpegCommand + withAudioFrequency(freq: number): FfmpegCommand + audioFrequency(freq: number): FfmpegCommand + withAudioQuality(quality: number): FfmpegCommand + audioQuality(quality: number): FfmpegCommand + withAudioFilter(filters: { filter: string, options: any }): FfmpegCommand + withAudioFilters(filters: { filter: string, options: any }): FfmpegCommand + audioFilter(filters: { filter: string, options: any }): FfmpegCommand + audioFilters(filters: { filter: string, options: any }): FfmpegCommand + + // options/video + withNoVideo(): FfmpegCommand + noVideo(): FfmpegCommand + withVideoCodec(codec: string): FfmpegCommand + videoCodec(codec: string): FfmpegCommand + withVideoBitrate(bitrate: string | number): FfmpegCommand + videoBitrate(bitrate: string | number): FfmpegCommand + withVideoFilter(filters: { filter: string, options: any }): FfmpegCommand + withVideoFilters(filters: { filter: string, options: any }): FfmpegCommand + videoFilter(filters: { filter: string, options: any }): FfmpegCommand + videoFilters(filters: { filter: string, options: any }): FfmpegCommand + withOutputFps(fps: number): FfmpegCommand + withOutputFPS(fps: number): FfmpegCommand + withFpsOutput(fps: number): FfmpegCommand + withFPSOutput(fps: number): FfmpegCommand + withFps(fps: number): FfmpegCommand + withFPS(fps: number): FfmpegCommand + outputFPS(fps: number): FfmpegCommand + outputFps(fps: number): FfmpegCommand + fpsOutput(fps: number): FfmpegCommand + FPSOutput(fps: number): FfmpegCommand + fps(fps: number): FfmpegCommand + FPS(fps: number): FfmpegCommand + takeFrames(frames: number): FfmpegCommand + withFrames(frames: number): FfmpegCommand + frames(frames: number): FfmpegCommand + + // options/videosize + keepPixelAspect(): FfmpegCommand + keepDisplayAspect(): FfmpegCommand + keepDisplayAspectRatio(): FfmpegCommand + keepDAR(): FfmpegCommand + withSize(size: string): FfmpegCommand + setSize(size: string): FfmpegCommand + size(size: string): FfmpegCommand + withAspect(aspect: string | number): FfmpegCommand + withAspectRatio(aspect: string | number): FfmpegCommand + setAspect(aspect: string | number): FfmpegCommand + setAspectRatio(aspect: string | number): FfmpegCommand + aspect(aspect: string | number): FfmpegCommand + aspectRatio(aspect: string | number): FfmpegCommand + applyAutopadding(pad: boolean, color: string): FfmpegCommand + applyAutoPadding(pad: boolean, color: string): FfmpegCommand + applyAutopad(pad: boolean, color: string): FfmpegCommand + applyAutoPad(pad: boolean, color: string): FfmpegCommand + withAutopadding(pad: boolean, color: string): FfmpegCommand + withAutoPadding(pad: boolean, color: string): FfmpegCommand + withAutopad(pad: boolean, color: string): FfmpegCommand + withAutoPad(pad: boolean, color: string): FfmpegCommand + autoPad(pad: boolean, color: string): FfmpegCommand + autopad(pad: boolean, color: string): FfmpegCommand + + // options/output + addOutput(target: string | stream.Writable, pipeopts?: { end?: boolean }): FfmpegCommand + output(target: string | stream.Writable, pipeopts?: { end?: boolean }): FfmpegCommand + seekOutput(seek: string | number): FfmpegCommand + seek(seek: string | number): FfmpegCommand + withDuration(duration: string | number): FfmpegCommand + setDuration(duration: string | number): FfmpegCommand + duration(duration: string | number): FfmpegCommand + toFormat(format: string): FfmpegCommand + withOutputFormat(format: string): FfmpegCommand + outputFormat(format: string): FfmpegCommand + format(format: string): FfmpegCommand + map(spec: string): FfmpegCommand + updateFlvMetadata(): FfmpegCommand + flvmeta(): FfmpegCommand + + // options/custom + addInputOption(options: string[]): FfmpegCommand + addInputOption(...options: string[]): FfmpegCommand + addInputOptions(options: string[]): FfmpegCommand + addInputOptions(...options: string[]): FfmpegCommand + withInputOption(options: string[]): FfmpegCommand + withInputOption(...options: string[]): FfmpegCommand + withInputOptions(options: string[]): FfmpegCommand + withInputOptions(...options: string[]): FfmpegCommand + inputOption(options: string[]): FfmpegCommand + inputOption(...options: string[]): FfmpegCommand + inputOptions(options: string[]): FfmpegCommand + inputOptions(...options: string[]): FfmpegCommand + addOutputOption(options: string[]): FfmpegCommand + addOutputOption(...options: string[]): FfmpegCommand + addOutputOptions(options: string[]): FfmpegCommand + addOutputOptions(...options: string[]): FfmpegCommand + addOption(options: string[]): FfmpegCommand + addOption(...options: string[]): FfmpegCommand + addOptions(options: string[]): FfmpegCommand + addOptions(...options: string[]): FfmpegCommand + withOutputOption(options: string[]): FfmpegCommand + withOutputOption(...options: string[]): FfmpegCommand + withOutputOptions(options: string[]): FfmpegCommand + withOutputOptions(...options: string[]): FfmpegCommand + withOption(options: string[]): FfmpegCommand + withOption(...options: string[]): FfmpegCommand + withOptions(options: string[]): FfmpegCommand + withOptions(...options: string[]): FfmpegCommand + outputOption(options: string[]): FfmpegCommand + outputOption(...options: string[]): FfmpegCommand + outputOptions(options: string[]): FfmpegCommand + outputOptions(...options: string[]): FfmpegCommand + filterGraph(spec: string | FilterSpecification[], map: string[]): FfmpegCommand + complexFilter(spec: string | FilterSpecification[], map: string[]): FfmpegCommand + + // options/misc + usingPreset(proset: string | GetPreset): FfmpegCommand + pnreset(proset: string | GetPreset): FfmpegCommand + + // processor + renice(niceness: number): FfmpegCommand + kill(signal: string): FfmpegCommand + + // capabilities + setFfmpegPath(path: string): FfmpegCommand + setFfprobePath(path: string): FfmpegCommand + setFlvtoolPath(path: string): FfmpegCommand + availableFilters(callback: FiltersCallback): void + getAvailableFilters(callback: FiltersCallback): void + availableCodecs(callback: CodecsCallback): void + getAvailableCodecs(callback: CodecsCallback): void + availableEncoders(callback: EncodersCallback): void + getAvailableEncoders(callback: EncodersCallback): void + availableFormats(callback: FormatsCallback): void + getAvailableFormats(callback: FormatsCallback): void + + // ffprobe + ffprobe(callback: (err: any, data: FfprobeData) => void): (err: any, data: FfprobeData) => void + ffprobe(index: number, callback: (err: any, data: FfprobeData) => void): (err: any, data: FfprobeData) => void + ffprobe(options: string[], callback: (err: any, data: FfprobeData) => void): (err: any, data: FfprobeData) => void + ffprobe(index: number, options: string[], callback: (err: any, data: FfprobeData) => void): (err: any, data: FfprobeData) => void + + // recipes + saveToFile(output: string): FfmpegCommand + save(output: string): FfmpegCommand + writeToStream(stream: stream.Writable, options?: { end?: boolean }): stream.Writable + pipe(stream: stream.Writable, options?: { end?: boolean }): stream.Writable + stream(stream: stream.Writable, options?: { end?: boolean }): stream.Writable + takeScreenshots(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand + thumbnail(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand + thumbnails(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand + screenshot(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand + screenshots(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand + mergeToFile(target: string | stream.Writable, options?: { end?: boolean }): FfmpegCommand + concatenate(target: string | stream.Writable, options?: { end?: boolean }): FfmpegCommand + concat(target: string | stream.Writable, options?: { end?: boolean }): FfmpegCommand + } + + function Ffmpeg(): FfmpegCommand + function Ffmpeg(options: FfmpegCommandOptions): FfmpegCommand + function Ffmpeg(input: string | stream.Readable, options: FfmpegCommandOptions): FfmpegCommand + + export = Ffmpeg +} diff --git a/fs-extra-promise/fs-extra-promise.d.ts b/fs-extra-promise/fs-extra-promise.d.ts index 2243a4d1c5..bdf8360b77 100644 --- a/fs-extra-promise/fs-extra-promise.d.ts +++ b/fs-extra-promise/fs-extra-promise.d.ts @@ -6,7 +6,7 @@ // Imported from: https://github.com/soywiz/typescript-node-definitions/fs-extra.d.ts via TSD fs-extra definition /// -/// +/// declare module "fs-extra-promise" { import stream = require("stream"); diff --git a/fullCalendar/fullCalendar.d.ts b/fullCalendar/fullCalendar.d.ts index 65df012185..fd43e51c5f 100644 --- a/fullCalendar/fullCalendar.d.ts +++ b/fullCalendar/fullCalendar.d.ts @@ -318,7 +318,7 @@ interface JQuery { /** * Moves the calendar to an arbitrary date. */ - fullCalendar(method: 'gotoDate', date: Date | string): void; + fullCalendar(method: 'gotoDate', date: moment.Moment | Date | string): void; /** * Moves the calendar forward/backward an arbitrary amount of time. @@ -403,4 +403,4 @@ interface JQuery { interface JQueryStatic { fullCalendar: FullCalendar.Calendar; -} \ No newline at end of file +} diff --git a/github-electron/electron-prebuilt-tests.ts b/github-electron/electron-tests.ts similarity index 56% rename from github-electron/electron-prebuilt-tests.ts rename to github-electron/electron-tests.ts index 771fd06016..00b34d60b1 100644 --- a/github-electron/electron-prebuilt-tests.ts +++ b/github-electron/electron-tests.ts @@ -1,7 +1,7 @@ -/// +/// /// -import electron = require('electron-prebuilt'); +import electron = require('electron'); import child_process = require('child_process'); child_process.spawn(electron); diff --git a/github-electron/electron-prebuilt.d.ts b/github-electron/electron.d.ts similarity index 53% rename from github-electron/electron-prebuilt.d.ts rename to github-electron/electron.d.ts index d6b6dffc0e..5e331b3e47 100644 --- a/github-electron/electron-prebuilt.d.ts +++ b/github-electron/electron.d.ts @@ -1,9 +1,9 @@ -// Type definitions for electron-prebuilt 0.30.1 -// Project: https://github.com/mafintosh/electron-prebuilt +// Type definitions for electron 1.3.3 +// Project: https://github.com/electron-userland/electron-prebuilt // Definitions by: rhysd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'electron-prebuilt' { +declare module 'electron' { var electron: string; export = electron; } diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 7b246966ab..7d10fce465 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Electron v1.3.3 +// Type definitions for Electron v1.3.4 // Project: http://electron.atom.io/ // Definitions by: jedmao , rhysd , Milan Burda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,7 +7,7 @@ declare namespace Electron { - class EventEmitter implements NodeJS.EventEmitter { + class EventEmitter extends NodeJS.EventEmitter { addListener(event: string, listener: Function): this; on(event: string, listener: Function): this; once(event: string, listener: Function): this; @@ -296,22 +296,37 @@ declare namespace Electron { * Once registered, all links with your-protocol:// will be opened with the current executable. * The whole link, including protocol, will be passed to your application as a parameter. * + * On Windows you can provide optional parameters path, the path to your executable, + * and args, an array of arguments to be passed to your executable when it launches. + * + * @param protocol The name of your protocol, without ://. + * @param path Defaults to process.execPath. + * @param args Defaults to an empty array. + * * Note: This is only implemented on macOS and Windows. * On macOS, you can only register protocols that have been added to your app's info.plist. */ - setAsDefaultProtocolClient(protocol: string): boolean; + setAsDefaultProtocolClient(protocol: string, path?: string, args?: string[]): boolean; /** * Removes the current executable as the default handler for a protocol (aka URI scheme). * + * @param protocol The name of your protocol, without ://. + * @param path Defaults to process.execPath. + * @param args Defaults to an empty array. + * * Note: This is only implemented on macOS and Windows. */ - removeAsDefaultProtocolClient(protocol: string): boolean; + removeAsDefaultProtocolClient(protocol: string, path?: string, args?: string[]): boolean; /** + * @param protocol The name of your protocol, without ://. + * @param path Defaults to process.execPath. + * @param args Defaults to an empty array. + * * @returns Whether the current executable is the default handler for a protocol (aka URI scheme). * * Note: This is only implemented on macOS and Windows. */ - isDefaultProtocolClient(protocol: string): boolean; + isDefaultProtocolClient(protocol: string, path?: string, args?: string[]): boolean; /** * Adds tasks to the Tasks category of JumpList on Windows. * @@ -630,7 +645,7 @@ declare namespace Electron { * Emitted when the document changed its title, * calling event.preventDefault() would prevent the native window’s title to change. */ - on(event: 'page-title-updated', listener: (event: Event) => void): this; + on(event: 'page-title-updated', listener: (event: Event, title: string) => void): this; /** * Emitted when the window is going to be closed. It’s emitted before the beforeunload * and unload event of the DOM. Calling event.preventDefault() will cancel the close. @@ -2947,18 +2962,22 @@ declare namespace Electron { interface NetworkEmulationOptions { /** * Whether to emulate network outage. + * Default: false. */ offline?: boolean; /** * RTT in ms. + * Default: 0, which will disable latency throttling. */ latency?: number; /** * Download rate in Bps. + * Default: 0, which will disable download throttling. */ downloadThroughput?: number; /** * Upload rate in Bps. + * Default: 0, which will disable upload throttling. */ uploadThroughput?: number; } @@ -3687,7 +3706,7 @@ declare namespace Electron { * navigation outside of the page. Examples of this occurring are when anchor links * are clicked or when the DOM hashchange event is triggered. */ - on(event: 'did-navigate-in-page', listener: (event: Event, url: string) => void): this; + on(event: 'did-navigate-in-page', listener: (event: Event, url: string, isMainFrame: boolean) => void): this; /** * Emitted when the renderer process has crashed. */ @@ -4382,7 +4401,7 @@ declare namespace Electron { /** * PEM encoded data. */ - data: Buffer; + data: string; /** * Issuer's Common Name. */ @@ -4766,6 +4785,10 @@ declare namespace Electron { * @returns Whether the web page is destroyed. */ isDestroyed(): boolean; + /** + * @returns Whether the web page is focused. + */ + isFocused(): boolean; /** * @returns Whether guest page is still loading resources. */ @@ -5043,14 +5066,14 @@ declare namespace Electron { * * Calling event.preventDefault() does NOT have any effect. */ - addEventListener(type: 'will-navigate', listener: (event: WebViewElement.NavigateEvent) => void, useCapture?: boolean): void; + addEventListener(type: 'will-navigate', listener: (event: WebViewElement.WillNavigateEvent) => void, useCapture?: boolean): void; /** * Emitted when a navigation is done. * * This event is not emitted for in-page navigations, such as clicking anchor links * or updating the window.location.hash. Use did-navigate-in-page event for this purpose. */ - addEventListener(type: 'did-navigate', listener: (event: WebViewElement.NavigateEvent) => void, useCapture?: boolean): void; + addEventListener(type: 'did-navigate', listener: (event: WebViewElement.DidNavigateEvent) => void, useCapture?: boolean): void; /** * Emitted when an in-page navigation happened. * @@ -5058,7 +5081,7 @@ declare namespace Electron { * navigation outside of the page. Examples of this occurring are when anchor links * are clicked or when the DOM hashchange event is triggered. */ - addEventListener(type: 'did-navigate-in-page', listener: (event: WebViewElement.NavigateEvent) => void, useCapture?: boolean): void; + addEventListener(type: 'did-navigate-in-page', listener: (event: WebViewElement.DidNavigateInPageEvent) => void, useCapture?: boolean): void; /** * Fired when the guest page attempts to close itself. */ @@ -5182,10 +5205,19 @@ declare namespace Electron { options: BrowserWindowOptions; } - interface NavigateEvent extends Event { + interface WillNavigateEvent extends Event { url: string; } + interface DidNavigateEvent extends Event { + url: string; + } + + interface DidNavigateInPageEvent extends Event { + url: string; + isMainFrame: boolean; + } + interface IpcMessageEvent extends Event { channel: string; args: any[]; diff --git a/google-earth/google-earth-tests.ts b/google-earth/google-earth-tests.ts new file mode 100644 index 0000000000..6c9d4df1bf --- /dev/null +++ b/google-earth/google-earth-tests.ts @@ -0,0 +1,131 @@ +/// + +google.load("earth", "1", {"other_params":"sensor=true_or_false"}); + +google.earth.createInstance("map3d", initCB, failureCB); + +function failureCB(error: any) {} + +function initCB(ge: google.earth.GEPlugin) { + + ge.getWindow().setVisibility(true); + + + // Create the placemark. + var placemark = ge.createPlacemark(''); + placemark.setName("placemark"); + + // Set the placemark's location. + var point = ge.createPoint(''); + point.setLatitude(12.345); + point.setLongitude(54.321); + placemark.setGeometry(point); + + // Create a style map. + var styleMap = ge.createStyleMap(''); + + // Create normal style for style map. + var normalStyle = ge.createStyle(''); + var normalIcon = ge.createIcon(''); + normalIcon.setHref('http://maps.google.com/mapfiles/kml/paddle/red-circle.png'); + normalStyle.getIconStyle().setIcon(normalIcon); + + // Create highlight style for style map. + var highlightStyle = ge.createStyle(''); + var highlightIcon = ge.createIcon(''); + highlightIcon.setHref('http://google-maps-icons.googlecode.com/files/girlfriend.png'); + highlightStyle.getIconStyle().setIcon(highlightIcon); + highlightStyle.getIconStyle().setScale(5.0); + + styleMap.setNormalStyle(normalStyle); + styleMap.setHighlightStyle(highlightStyle); + + // Apply stylemap to a placemark. + placemark.setStyleSelector(styleMap); + + //Add the placemark to Earth. + ge.getFeatures().appendChild(placemark); + + + // balloons + var balloon = ge.createHtmlDivBalloon(''); + balloon.setFeature(placemark); + var div = document.createElement('DIV'); + div.innerHTML = 'Any HTML, CSS, or JavaScript goes here.'; + balloon.setContentDiv(div); + ge.setBalloon(balloon); + + // Create the ScreenOverlay + var screenOverlay = ge.createScreenOverlay(''); + + // Specify a path to the image and set as the icon + var icon = ge.createIcon(''); + icon.setHref('http://www.google.com/intl/en_ALL/images/logo.gif'); + screenOverlay.setIcon(icon); + + // Set the ScreenOverlay's position in the window + screenOverlay.getOverlayXY().setXUnits(ge.UNITS_PIXELS); + screenOverlay.getOverlayXY().setYUnits(ge.UNITS_PIXELS); + screenOverlay.getOverlayXY().setX(200); + screenOverlay.getOverlayXY().setY(200); + + // Set the overlay's size in pixels + screenOverlay.getSize().setXUnits(ge.UNITS_PIXELS); + screenOverlay.getSize().setYUnits(ge.UNITS_PIXELS); + screenOverlay.getSize().setX(250); + screenOverlay.getSize().setY(75); + + // Specify the point in the image around which to rotate + screenOverlay.getRotationXY().setXUnits(ge.UNITS_FRACTION); + screenOverlay.getRotationXY().setYUnits(ge.UNITS_FRACTION); + screenOverlay.getRotationXY().setX(0.5); + screenOverlay.getRotationXY().setY(0.5); + + // Rotate the overlay + screenOverlay.setRotation(25); + + // Add the ScreenOverlay to Earth + ge.getFeatures().appendChild(screenOverlay); + + + // network link + var link = ge.createLink(''); + var href = 'http://code.google.com/' + + 'apis/earth/documentation/samples/kml_example.kml' + link.setHref(href); + + var networkLink = ge.createNetworkLink(''); + networkLink.set(link, true, true); // Sets the link, refreshVisibility, and flyToView + + ge.getFeatures().appendChild(networkLink); + + // Get the current view. + var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND); + + // Set new latitude and longitude values. + lookAt.setLatitude(36.584207); + lookAt.setLongitude(-121.754322); + + // Update the view in Google Earth. + ge.getView().setAbstractView(lookAt); + + // time + ge.getTime().getControl().setVisibility(ge.VISIBILITY_SHOW); + ge.getTime().setHistoricalImageryEnabled(true); + var extents = ge.getTime().getControl().getExtents(); + var begin = extents.getBegin().get(); + var end = extents.getEnd().get(); + + // tour + ge.getTourPlayer().play(); + + + // controls + ge.getNavigationControl().getScreenXY().setXUnits(ge.UNITS_INSET_PIXELS); + ge.getNavigationControl().getScreenXY().setYUnits(ge.UNITS_PIXELS); + + + // sky + ge.getOptions().setMapType(ge.MAP_TYPE_SKY); + ge.getOptions().setMapType(ge.MAP_TYPE_EARTH); +} diff --git a/google-earth/google-earth.d.ts b/google-earth/google-earth.d.ts new file mode 100644 index 0000000000..d0adc8c04e --- /dev/null +++ b/google-earth/google-earth.d.ts @@ -0,0 +1,3978 @@ +// Type definitions for Google Earth Plugin +// Project: https://developers.google.com/earth/ +// Definitions by: Ilia Choly +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace google { + + export function load( + moduleName: string, + moduleVersion: string, + optionalSettings?: any + ): void; +} + +declare namespace google.earth { + + /** + * Specifies the current stage of the flow of events. + */ + export type GEEventPhaseEnum = any; + + /** + * Specifies how a feature should be displayed in a list view. + */ + export type KmlListItemTypeEnum = any; + + /** + * Specifies which color mode effect to apply to the base color. + */ + export type KmlColorModeEnum = any; + + /* + * Specifies how the altitude property is interpreted. + */ + export type KmlAltitudeModeEnum = any; + + /** + * Specifies how the link is refreshed. + */ + export type KmlRefreshModeEnum = any; + + /** + * Specifies how the link is refreshed when the viewport changes. + */ + export type KmlViewRefreshModeEnum = any; + + /** + * Specifies which units a value is specified in. + */ + type KmlUnitsEnum = any; + + /** + * Specifies if the map type is Earth or sky mode. + */ + type GEMapTypeEnum = any; + + /** + * Specifies if a control is always visible, always hidden, + * or visible only when the user intends to use the control. + */ + type GEVisibilityEnum = any; + + /** + * Specifies what to sample when performing a hit test. + */ + type GEHitTestModeEnum = any; + + /** + * Specifies the size of the navigation control. + */ + type GENavigationControlEnum = any; + + /** + * Specifies the state of viewer options, including sunlight, + * Street View, and historical imagery. + */ + type GEViewerOptionsValueEnum = any; + + /* + * Specifies the viewer option types. + */ + type GEViewerOptionsTypeEnum = any; + + /** + * Whether or not the Google Earth Browser Plug-in and API are supported on the current browser and operating system. + */ + export function isSupported(): boolean; + + /** + * Whether or not the Google Earth Browser Plug-in is currently installed on the user's machine. + * + * Note: if the plug-in is not installed, the user will be presented with a 'download' link upon calls to google.earth.createInstance(). + */ + export function isInstalled(): boolean; + + /** + * Attempts to create an instance of the plugin under the given web browser HTML DOM node. + * Upon success, calls the function passed in as the initCallback argument. + * Upon failure, calls the function passed in as the failureCallback argument and displays an error message to the user in place of the plug-in object. + * + * Note: + * + * The HTML DOM must be loaded before this function can be called. + * Common usage is to call this function upon the 's load event, or to use google.setOnLoadCallback. + */ + export function createInstance( + domNode: string|Element, + initCallback: (plugin: GEPlugin) => void, + failureCallback: (error: any) => void, + options?: any + ): void; + + /** + * Attaches a listener to a given object for a specific event; when the event occurs on the object, the given callback is invoked. + */ + export function addEventListener( + targetObject: any, + eventID: string, + listenerCallback: (event: KmlEvent) => void, + useCapture?: boolean + ): void; + + /** + * Removes an event listener previously added using google.earth.addEventListener() from the event chain. + * + * Note: + * + * You must pass in the exact same function object as was passed to addEventListener. + * If you are using an anonymous function callback, it will need to be refactored into its own variable. + */ + export function removeEventListener( + targetObject: any, + eventID: string, + listenerCallback: (event: KmlEvent) => void, + useCapture?: boolean + ): void; + + /** + * Retrieves and parses a KML or KMZ file at the given URL and returns an instance of a KmlFeature-derived class representing the parsed KML object model. + * + * Note: This function does not display the feature on the Earth. See below for more information. + */ + export function fetchKml( + pluginInstance: GEPlugin, + url: string, + completionCallback: (feature: KmlFeature) => void + ): void; + + /** + * Efficiently executes an arbitrary, user-defined function (the batch function), minimizing the amount of overhead incurred during cross-process communication between the web browser and Google Earth Plugin. + * This method is useful for batching together a large set of calls to the Earth API, for example, a large number of consecutive calls to KmlCoordArray.pushLatLngAlt. + */ + export function executeBatch(pluginInstance: GEPlugin, batchFunction: Function): void; + + /** + * Sets the language to be used for new instances of the plugin. + * Needs to be called before google.earth.createInstance(). + * Affects road and border labels, the error message displayed when the plugin fails to load, as well as the language of the Terms of Use page linked from the plugin. + */ + export function setLanguage(languageCode: string): void; + + /** + * This interface enables programmatic and user-driven interaction with photo overlays in the Google Earth Plugin. + * + * Note: This interface is still under development. + */ + export class GEPhotoOverlayViewer { + + /** + * Enters the given photo overlay object, exiting any other currently active photo overlay. + * If the argument is null, then any currently active photo overlay is exited and normal global navigation is enabled. + */ + setPhotoOverlay(photoOverlay: KmlPhotoOverlay): void; + } + + /** + * Used to manipulate the navigation controls in Google Earth. + */ + export class GENavigationControl { + + /** + * Whether the control is always visible, always hidden, or visible only when the user intends to use the control. + * + * See also: + * + * * GEPlugin.VISIBILITY_SHOW + * * GEPlugin.VISIBILITY_HIDE + * * GEPlugin.VISIBILITY_AUTO + */ + getVisibility(): GEVisibilityEnum; + + /** + * Whether the control is always visible, always hidden, or visible only when the user intends to use the control. + * + * See also: + * + * * GEPlugin.VISIBILITY_SHOW + * * GEPlugin.VISIBILITY_HIDE + * * GEPlugin.VISIBILITY_AUTO + */ + setVisibility(visibility: GEVisibilityEnum): void; + + /** + * Specifies the size of the navigation control. + * + * See also: + * + * * GEPlugin.NAVIGATION_CONTROL_LARGE + * * GEPlugin.NAVIGATION_CONTROL_SMALL + */ + getControlType(): GENavigationControlEnum; + + /** + * Specifies the size of the navigation control. + * + * See also: + * + * * GEPlugin.NAVIGATION_CONTROL_LARGE + * * GEPlugin.NAVIGATION_CONTROL_SMALL + */ + setControlType(controlType: GENavigationControlEnum): void; + + /** + * The position of the navigation controls in Google Earth + */ + getScreenXY(): KmlVec2; + + /** + * Enables or disables user-initiated entry to Street View imagery. + * When true, the Pegman icon is present in the navigation controls, allowing a user to drag the Pegman onto a street to initiate Street View. + * Users can also zoom down to ground level to enter Street View when this is set to true. + */ + setStreetViewEnabled(streetViewEnabled: boolean): void; + + /** + * Whether Street View is enabled in the navigation controls. + */ + getStreetViewEnabled(): boolean; + } + + /** + * Defines a tour, which is a playlist of scripted camera and update events. + * + * Note: This interface is still under development. + */ + export class KmlTour extends KmlFeature {} + + /** + * This interface enables programmatic and user-driven interaction with KML tours in the Google Earth Plugin. + * + * Note: This interface is still under development. + */ + export class GETourPlayer { + + /** + * Enters the given tour object, exiting any other currently active tour. + * This method does not automatically begin playing the tour. + * If the argument is null, then any currently active tour is exited and normal globe navigation is enabled. + */ + setTour(tour: KmlTour): void; + + /** + * Plays the currently active tour. + */ + play(): void; + + /** + * Pauses the currently active tour. + */ + pause(): void; + + /** + * Resets the currently active tour, stopping playback and rewinding to the start of the tour. + */ + reset(): void; + + /** + * The current elapsed playing time of the active tour, in seconds. + */ + getCurrentTime(): number; + + /** + * The current elapsed playing time of the active tour, in seconds. + */ + setCurrentTime(currentTime: number): void; + + /** + * The total duration of the active tour, in seconds. If no tour is loaded, the behavior of this method is undefined. + */ + getDuration(): number; + } + + /** + * This interface contains result information obtained by calling GEView's hitTest method. + * + * See also: + * + * * GEView.hitTest + */ + export class GEHitTestResult { + + /** + * Latitude of sampled point. + */ + getLatitude(): number; + + /** + * Latitude of sampled point. + */ + setLatitude(latitude: number): void; + + /** + * Longitude of sampled point. + */ + getLongitude(): number; + + /** + * Longitude of sampled point. + */ + setLongitude(longitude: number): void; + + /** + * Altitude of sampled point. + */ + getAltitude(): number; + + /** + * Altitude of sampled point. + */ + setAltitude(altitude: number): void; + } + + /** + * Maps between two different icon styles. + * Typically this interface is used to provide separate normal and highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon. + */ + export class KmlStyleMap extends KmlStyleSelector { + + /** + * Sets both URLs for the placemark style. + */ + setUrl(normalStyleUrl: string, highlightStyleUrl: string): void; + + /** + * Sets both placemark styles. + */ + setStyle(normalStyle: KmlStyle, highlightStyle: KmlStyle): void; + + /** + * Defines a normal style for a placemark. + */ + getNormalStyleUrl(): string; + + /** + * Defines a normal style for a placemark. + */ + setNormalStyleUrl(normalStyleUrl: string): void; + + /** + * Defines highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. + */ + getHighlightStyleUrl(): string; + + /** + * Defines highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. + */ + setHighlightStyleUrl(highlightStyleUrl: string): void; + + /** + * Defines a normal style for a placemark. + */ + getNormalStyle(): KmlStyle; + + /** + * Defines a normal style for a placemark. + */ + setNormalStyle(normalStyle: KmlStyle): void; + + /** + * Defines highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. + */ + getHighlightStyle(): KmlStyle; + + /** + * Defines highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. + */ + setHighlightStyle(highlightStyle: KmlStyle): void; + } + + /** + * References a KML file or KMZ archive on a remote network. + * Use the Link property to specify the location of the KML file. + * Within that property, you can define the refresh options for updating the file, based on time and camera change. + * NetworkLinks can be used in combination with Regions to handle very large datasets efficiently. + */ + export class KmlNetworkLink extends KmlFeature { + + /** + * Sets the link, refreshVisibility, and flyToView for the network link. + */ + set(link: KmlLink, refreshVisibility: boolean, flyToView: boolean): void; + + /** + * Specifies the location of any of the following: + * + * * KML files fetched by network links + * * Image files used by icons in icon styles, ground overlays, and screen overlays + * * Model files used in the Model object + */ + getLink(): KmlLink; + + /** + * Specifies the location of any of the following: + * + * * KML files fetched by network links + * * Image files used by icons in icon styles, ground overlays, and screen overlays + * * Model files used in the Model object + */ + setLink(link: KmlLink): void; + + /** + * A value of 0 leaves the visibility of features within the control of the Google Earth user. + * Set the value to 1 to reset the visibility of features each time the NetworkLink is refreshed. + * For example, suppose a Placemark within the linked KML file has visibility set to 1 and the NetworkLink has refreshVisibility set to 1. + * When the file is first loaded into Google Earth, the user can clear the check box next to the item to turn off display in the 3D viewer. + * However, when the NetworkLink is refreshed, the Placemark will be made visible again, since its original visibility state was TRUE. + */ + getRefreshVisibility(): boolean; + + /** + * A value of 0 leaves the visibility of features within the control of the Google Earth user. + * Set the value to 1 to reset the visibility of features each time the NetworkLink is refreshed. + * For example, suppose a Placemark within the linked KML file has visibility set to 1 and the NetworkLink has refreshVisibility set to 1. + * When the file is first loaded into Google Earth, the user can clear the check box next to the item to turn off display in the 3D viewer. + * However, when the NetworkLink is refreshed, the Placemark will be made visible again, since its original visibility state was TRUE. + */ + setRefreshVisibility(refreshVisibility: boolean): void; + + /** + * A value of 1 causes Google Earth to fly to the view of the LookAt or Camera in the NetworkLinkControl (if it exists). + */ + getFlyToView(): boolean; + + /** + * A value of 1 causes Google Earth to fly to the view of the LookAt or Camera in the NetworkLinkControl (if it exists). + */ + setFlyToView(flyToView: boolean): void; + } + + /** + * Draws an image overlay fixed to the screen. + * Sample uses for ScreenOverlays are compasses, logos, and heads-up displays. + * ScreenOverlay sizing is determined by the size element. + * Positioning of the overlay is handled by mapping a point in the image specified by screenXY to a point on the screen specified by overlayXY. + * Then the image is rotated by rotation degrees about a point relative to the screen specified by rotationXY. + * + * Note: + * + * screenXY and overlayXY behave opposite to their corresponding behaviors in KML. + * This is due to a bug in the Earth API that will intentionally remain unfixed until a major version change. + */ + export class KmlScreenOverlay extends KmlOverlay { + + /** + * Specifies a point on (or outside of) the overlay image that is mapped to the screen coordinate. + * It requires x and y values, and the units for those values. + * + * Note: + * + * screenXY and overlayXY behave opposite to their corresponding behaviors in KML. + * This is due to a bug in the Earth API that will intentionally remain unfixed until a major version change. + */ + getScreenXY(): KmlVec2; + + /** + * Specifies a point relative to the screen origin that the overlay image is mapped to. + * The x and y values can be specified in three different ways: as pixels ("pixels"), as fractions of the screen ("fraction"), or as inset pixels ("insetPixels"), which is an offset in pixels from the upper right corner of the screen. + * The x and y positions can be specified in different ways - for example, x can be in pixels and y can be a fraction. + * The origin of the coordinate system is in the lower left corner of the screen. + * + * Note: + * + * screenXY and overlayXY behave opposite to their corresponding behaviors in KML. + * This is due to a bug in the Earth API that will intentionally remain unfixed until a major version change. + */ + getOverlayXY(): KmlVec2; + + /** + * Point relative to the screen about which the screen overlay is rotated. + */ + getRotationXY(): KmlVec2; + + /** + * Specifies the size of the image for the screen overlay, as follows: + * + * * A value of -1 indicates to use the native dimension + * * A value of 0 indicates to maintain the aspect ratio + * * A value of n sets the value of the dimension + */ + getSize(): KmlVec2; + + /** + * Adjusts how the image is placed inside the field of view. + * This element is useful if your image has been rotated and deviates slightly from a desired horizontal view. + */ + getRotation(): number; + + /** + * Adjusts how the image is placed inside the field of view. + * This element is useful if your image has been rotated and deviates slightly from a desired horizontal view. + */ + setRotation(rotation: number): void; + } + + /** + * Defines a photo overlay, which is a geographically located photograph of the Earth. + * Photo overlays can be drawn onto 2D rectangles in three dimensional space, or in the case of panoramic photos, onto partial or full cylinders, or even spheres. + * + * Note: This interface is still under development. + */ + export class KmlPhotoOverlay extends KmlOverlay {} + + /** + * Draws an image overlay draped onto the terrain. + * The href child of Icon specifies the image to be used as the overlay. + * If this object is omitted or contains no href, a rectangle is drawn using the color defined by the overlay. + */ + export class KmlGroundOverlay extends KmlOverlay { + + /** + * Specifies the distance above the earth's surface. + */ + getAltitude(): number; + + /** + * Specifies the distance above the earth's surface. + */ + setAltitude(altitude: number): void; + + /** + * Specifies how the altitude property is interpreted. + * + * See also: + * + * * GEPlugin.ALTITUDE_CLAMP_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_CLAMP_TO_SEA_FLOOR + */ + getAltitudeMode(): KmlAltitudeModeEnum; + + /** + * Specifies how the altitude property is interpreted. + * + * See also: + * + * * GEPlugin.ALTITUDE_CLAMP_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_CLAMP_TO_SEA_FLOOR + */ + setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): void; + + /** + * The bounding box of the ground overlay. + */ + getLatLonBox(): KmlLatLonBox; + + /** + * The bounding box of the ground overlay. + */ + setLatLonBox(latLonBox: KmlLatLonBox): void; + } + + /** + * The KmlOverlay object is an abstract object and cannot be used directly in a KML file. + * Overlay is the base type for image overlays drawn on the planet surface or on the screen. + * Icon specifies the image to use and can be configured to reload images based on a timer or by camera changes. + * This object also includes specifications for stacking order of multiple overlays and for adding color and transparency values to the base image. + */ + export class KmlOverlay extends KmlFeature { + + /** + * Specifies the color values. + */ + getColor(): KmlColor; + + /** + * Defines the stacking order for the images in overlapping overlays. + * Overlays with higher drawOrder values are drawn on top of overlays with lower drawOrder values. + */ + getDrawOrder(): number; + + /** + * Defines the stacking order for the images in overlapping overlays. + * Overlays with higher drawOrder values are drawn on top of overlays with lower drawOrder values. + */ + setDrawOrder(drawOrder: number): void; + + /** + * Defines the image associated with the Overlay. + */ + getIcon(): KmlIcon; + + /** + * Defines the image associated with the Overlay. + */ + setIcon(icon: KmlIcon): void; + } + + /** + * This class controls the display of sunlight, historical imagery, and Street View panoramas in the plugin. + * The KmlViewerOptions object is passed to KmlAbstractView.setViewerOptions() + */ + export class KmlViewerOptions extends KmlObject { + + /** + * Returns the current state of the specified viewer option type. + * + * See also: + * + * * GEPlugin.OPTION_STREET_VIEW + * * GEPlugin.OPTION_SUNLIGHT + * * GEPlugin.OPTION_HISTORICAL_IMAGERY + * * GEPlugin.OPTION_STATE_DEFAULT + * * GEPlugin.OPTION_STATE_ENABLED + * * GEPlugin.OPTION_STATE_DISABLED + */ + setOption(type: GEViewerOptionsTypeEnum, state: GEViewerOptionsValueEnum): void; + + /** + * Set the state of viewer options, including sunlight, Street View, and historical imagery. + * + * See also: + * + * * GEPlugin.OPTION_STREET_VIEW + * * GEPlugin.OPTION_SUNLIGHT + * * GEPlugin.OPTION_HISTORICAL_IMAGERY + * * GEPlugin.OPTION_STATE_DEFAULT + * * GEPlugin.OPTION_STATE_ENABLED + * * GEPlugin.OPTION_STATE_DISABLED + */ + getOption(type: GEViewerOptionsValueEnum): GEViewerOptionsValueEnum; + } + + /** + * Describes rotation of a 3D model's coordinate system to position the object in Google Earth. + */ + export class KmlOrientation extends KmlObject { + + /** + * Sets the heading, tilt, and roll of a model. + */ + set(heading: number, tilt: number, roll: number): void; + + /** + * Rotation about the z axis (normal to the Earth's surface). + * A value of 0 (the default) equals North. + * A positive rotation is clockwise around the z axis and specified in degrees from 0 to 360. + */ + getHeading(): number; + + /** + * Rotation about the z axis (normal to the Earth's surface). + * A value of 0 (the default) equals North. + * A positive rotation is clockwise around the z axis and specified in degrees from 0 to 360. + */ + setHeading(heading: number): void; + + /** + * Rotation about the x axis. + * A positive rotation is clockwise around the x axis and specified in degrees from 0 to 360. + */ + getTilt(): number; + + /** + * Rotation about the x axis. + * A positive rotation is clockwise around the x axis and specified in degrees from 0 to 360. + */ + setTilt(tilt: number): void; + + /** + * Rotation about the y axis. + * A positive rotation is clockwise around the y axis and specified in degrees from 0 to 360. + */ + getRoll(): number; + + /** + * Rotation about the y axis. + * A positive rotation is clockwise around the y axis and specified in degrees from 0 to 360. + */ + setRoll(roll: number): void; + } + + /** + * Specifies the exact coordinates of the Model's origin in latitude, longitude, and altitude. + * Latitude and longitude measurements are standard lat-lon projection with WGS84 datum. + * Altitude is distance above the earth's surface, in meters, and is interpreted according to altitudeMode. + */ + export class KmlLocation extends KmlObject { + + /** + * Sets the latitude, longitude, and altitude of the Model. + */ + setLatLngAlt(lat: number, lng: number, alt: number): void; + + /** + * Longitude of the Model's location. + * Angular distance in degrees, relative to the Prime Meridian. + * Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + getLongitude(): number; + + /** + * Longitude of the Model's location. + * Angular distance in degrees, relative to the Prime Meridian. + * Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + setLongitude(longitude: number): void; + + /** + * Latitude of the camera location. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + getLatitude(): number; + + /** + * Latitude of the camera location. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + setLatitude(latitude: number): void; + + /** + * Specifies the distance above the earth's surface. + */ + getAltitude(): number; + + /** + * Specifies the distance above the earth's surface. + */ + setAltitude(altitude: number): void; + } + + /** + * Scales a model along the x, y, and z axes in the model's coordinate space. + */ + export class KmlScale extends KmlObject { + + /** + * Sets the x, y, and z coordinates for a model. + */ + set(x: number, y: number, z: number): void; + + /** + * Indicates the x coordinate. + */ + getX(): number; + + /** + * Indicates the x coordinate. + */ + setX(x: number): void; + + /** + * Indicates the y coordinate. + */ + getY(): number; + + /** + * Indicates the y coordinate. + */ + setY(y: number): void; + + /** + * Indicates the z coordinate. + */ + getZ(): number; + + /** + * Indicates the z coordinate. + */ + setZ(z: number): void; + } + + /** + * A single tuple consisting of floating point values for longitude, latitude, and altitude (in that order). + * Longitude and latitude values are in degrees. + * + * * longitude = -180 and <= 180 + * * latitude = -90 and = 90 + * * altitude values (optional) are in meters above sea level + */ + export class KmlCoord { + + /** + * Sets the latitude, longitude, altitude. + */ + setLatLngAlt(latitude: number, longitude: number, altitude: number): void; + + /** + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + getLatitude(): number; + + /** + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + setLatitude(latitude: number): void; + + /** + * Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + getLongitude(): number; + + /** + * Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + setLongitude(longitude: number): void; + + /** + * Distance from the earth's surface. + */ + getAltitude(): number; + + /** + * Distance from the earth's surface. + */ + setAltitude(altitude: number): void; + } + + /** + * The KmlCoordArray object defines an array of coordinates. + */ + export class KmlCoordArray { + + /** + * Returns the coordinates at the given index. + */ + get(index: number): KmlCoord; + + /** + * Sets the coordinates at the given index.. + */ + set(index: number, coord: KmlCoord): void; + + /** + * Sets the latitude, longitude, and altitude. + */ + setLatLngAlt( + index: number, + latitude: number, + longitude: number, + altitude: number + ): void; + + /** + * Appends one or more new elements to the end of an array and returns the new length of the array. + */ + pushLatLngAlt( + latitude: number, + longitude: number, + altitude: number + ): void; + + /** + * Appends one or more new elements to the end of an array and returns the new length of the array. + */ + push(coordOrList: KmlCoord): void; + + /** + * Deletes the last element of an array, decrements the array length, and returns the value that is removed. + */ + pop(): KmlCoord; + + /** + * Adds an element or elements to the beginning of an array. + */ + unshift(coordOrList: KmlCoord): number; + + /** + * Adds an element or elements to the beginning of an array. + */ + unshiftLatLngAlt( + latitude: number, + longitude: number, + altitude: number + ): void; + + /** + * Removes and returns the first element of the array. + */ + shift(): KmlCoord; + + /** + * Reverses the order of the elements in the array. + */ + reverse(): void; + + /** + * Clears all of the elements in the array + */ + clear(): void; + + /** + * Specifies the length of the index array. + */ + getLength(): number; + } + + /** + * The object corresponding to the retangular region in which Google Earth is displayed. + */ + export class GEWindow extends GEEventEmitter { + + /** + * Gives the Google Earth object focus. + */ + focus(): void; + + /** + * Removes focus from the Google Earth object. + */ + blur(): void; + + /** + * Toggles the overall visibility of Google Earth inside the browser. + */ + getVisibility(): boolean; + + /** + * Toggles the overall visibility of Google Earth inside the browser. + */ + setVisibility(visibility: boolean): void; + } + + /** + * The GEGlobe class encapsulates the Google Earth globe to determine access and event behavior. + */ + export class GEGlobe extends KmlObject { + + /** + * Returns the altitude for a given location on the globe. + * If the altitude data for the location has not yet been loaded, the return value is 0. + */ + getGroundAltitude(lat: number, lon: number): number; + + /** + * The top-level features currently in the Earth instance. + */ + getFeatures(): GEFeatureContainer; + } + + /** + * Controls the behavior of the camera that views the scene in Google Earth. + */ + export class GEView { + + /** + * Returns the screen x,y coordinates of a given point on the globe. + * + * Tip: project() is the inverse of hitTest(). + * + * See also: + * + * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR + */ + project( + lat: number, + lng: number, + alt: number, + altitudeMode: KmlAltitudeModeEnum + ): KmlVec2; + + /** + * Sets the camera that views the scene in Google Earth. + */ + setAbstractView(view: KmlAbstractView): void; + + /** + * Creates and returns a new KmlLookAt object, initialized to the current camera position and orientation. + * Use 'altitudeMode' to specify the altitude mode of the looked-at point. + * + * See also: + * + * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR + */ + copyAsLookAt(altitudeMode: KmlAltitudeModeEnum): KmlLookAt; + + /** + * Creates and returns a new KmlCamera object, initialized to the current camera position and orientation. + * Use 'altitudeMode' to specify the altitude mode of the new camera. + * + * See also: + * + * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR + */ + copyAsCamera(altitudeMode: KmlAltitudeModeEnum): KmlCamera; + + /** + * Returns a bounding box that completely contains the region of the globe that is currently visible. + * The returned box will be larger than what is strictly visible, if that is necessary to include everything that is visible. + */ + getViewportGlobeBounds(): KmlLatLonBox; + + /** + * Given a point on the screen in pixel coordinates, returns a GEHitTestResult with information about the geographic location corresponding to the point on the screen. + * Tip: hitTest() is the inverse of project(). + * + * See also: + * + * * GEPlugin.UNITS_PIXELS + * * GEPlugin.UNITS_INSET_PIXELS + * * GEPlugin.UNITS_FRACTION + * * GEPlugin.HIT_TEST_GLOBE + * * GEPlugin.HIT_TEST_TERRAIN + * * GEPlugin.HIT_TEST_BUILDINGS + */ + hitTest( + x: number, + xUnits: KmlUnitsEnum, + y: number, + yUnits: KmlUnitsEnum, + mode: GEHitTestModeEnum + ): GEHitTestResult; + } + + /** + * Defines an image associated with an Icon style or overlay. + */ + export class KmlIcon extends KmlLink { + + /** + * Gets the offset from the left (), in pixels, of the icon. + */ + getX(): number; + + /** + * Specifies the icon's offset (), in pixels from the left side of its icon palette, if a palette has been specified in the element. + */ + setX(x: number): number; + + /** + * Gets the offset from the bottom (), in pixels, of the icon. + */ + getY(): number; + + /** + * Specifies the offset (), in pixels from the bottom of its icon palette, if a palette has been specified in the element. + */ + setY(y: number): void; + + /** + * Gets the width (), in pixels, of the icon. + */ + getW(): number; + + /** + * Specifies the width (), in pixels, of the icon to use. + */ + setW(w: number): void; + + /** + * Gets the height (), in pixels, of the icon. + */ + getH(): number; + + /** + * Specifies the height (), in pixels, of the icon to use. + */ + setH(h: number): void; + } + + /** + * Specifies the location of any KML files fetched by network links, image files used by icons in icon styles, ground overlays, and screen overlays, or model files used in the Model object. + */ + export class KmlLink extends KmlObject { + + /** + * A URL (either an HTTP address or a local file specification). + * When the parent of Link is a NetworkLink, href is a KML file. + * When the parent of Link is a Model, href is a COLLADA file. + * When the parent of Link is an Overlay, href is an image. + */ + getHref(): string; + + /** + * A URL (either an HTTP address or a local file specification). + * When the parent of Link is a NetworkLink, href is a KML file. + * When the parent of Link is a Model, href is a COLLADA file. + * When the parent of Link is an Overlay, href is an image. + */ + setHref(href: string): void; + + /** + * Specifies to use a time-based refresh mode. + * + * See also: + * + * * GEPlugin.REFRESH_ON_CHANGE + * * GEPlugin.REFRESH_ON_INTERVAL + * * GEPlugin.REFRESH_ON_EXPIRE + */ + getRefreshMode(): KmlRefreshModeEnum; + + /** + * Specifies to use a time-based refresh mode. + * + * See also: + * + * * GEPlugin.REFRESH_ON_CHANGE + * * GEPlugin.REFRESH_ON_INTERVAL + * * GEPlugin.REFRESH_ON_EXPIRE + */ + setRefreshMode(refreshMode: KmlRefreshModeEnum): void; + + /** + * Indicates to refresh the file every n seconds. + */ + getRefreshInterval(): number; + + /** + * Indicates to refresh the file every n seconds. + */ + setRefreshInterval(refreshInterval: number): void; + + /** + * Specifies how the link is refreshed when the viewport changes. + * + * See also: + * + * * GEPlugin.VIEW_REFRESH_NEVER + * * GEPlugin.VIEW_REFRESH_ON_STOP + * * GEPlugin.VIEW_REFRESH_ON_REGION + */ + getViewRefreshMode(): KmlViewRefreshModeEnum; + + /** + * Specifies how the link is refreshed when the viewport changes. + * + * See also: + * + * * GEPlugin.VIEW_REFRESH_NEVER + * * GEPlugin.VIEW_REFRESH_ON_STOP + * * GEPlugin.VIEW_REFRESH_ON_REGION + */ + setViewRefreshMode(viewRefreshMode: KmlViewRefreshModeEnum): void; + + /** + * Specifies how the link is refreshed when the camera changes. + */ + getViewRefreshTime(): number; + + /** + * Specifies how the link is refreshed when the camera changes. + */ + setViewRefreshTime(viewRefreshTime: number): void; + + /** + * Scales the BBOX parameters before sending them to the server. + * A value less than 1 specifies to use less than the full view (screen). + * A value greater than 1 specifies to fetch an area that extends beyond the edges of the current view. + */ + getViewBoundScale(): number; + + /** + * Scales the BBOX parameters before sending them to the server. + * A value less than 1 specifies to use less than the full view (screen). + * A value greater than 1 specifies to fetch an area that extends beyond the edges of the current view. + */ + setViewBoundScale(viewBoundScale: number): void; + + /** + * Specifies the format of the query string that is appended to the Link's href before the file is fetched. + * (If the href specifies a local file, this element is ignored.) + */ + getViewFormat(): string; + + /** + * Specifies the format of the query string that is appended to the Link's href before the file is fetched. + * (If the href specifies a local file, this element is ignored.) + */ + setViewFormat(viewFormat: string): void; + } + + /** + * Controls time in the plugin. + */ + export class GETime { + + /** + * Set the plugin's clock rate. + * A value of 1 corresponds with real time; to pass one year in the plugin for every real second, set the rate to 31536000 (60 times 60 times 24 times 365). + */ + setRate(rate: number): void; + + /** + * Get the current plugin clock rate. + */ + getRate(): number; + + /** + * Returns the current computer clock time as a KmlTimeStamp object. + */ + getSystemTime(): KmlTimeStamp; + + /** + * Returns the GETimeControl object; this is the time slider. + */ + getControl(): GETimeControl; + + /** + * Whether or not historical imagery is enabled. + */ + getHistoricalImageryEnabled(): boolean; + + /** + * Turn historical imagery on or off. + * For more information, read the Time chapter of the Developer's Guide. + */ + setHistoricalImageryEnabled(historicalImageryEnabled: boolean): void; + + /** + * Get the current plugin time as a KmlTimeStamp or KmlTimeSpan. + */ + getTimePrimitive(): KmlTimePrimitive; + + /** + * Sets the current plugin time. + */ + setTimePrimitive(timePrimitive: KmlTimePrimitive): void; + } + + /** + * Used to manipulate the behavior of the Google Earth options such as, navigation, flyToSpeed, scroll wheel speed and so on. + */ + export class GEOptions { + + /** + * Sets the map type to Earth or sky mode. + */ + setMapType(type: GEMapTypeEnum): void; + + /** + * Speed of zoom when user rolls the mouse wheel. Default is 1. + * Set to a negative number to reverse the zoom direction. + */ + getScrollWheelZoomSpeed(): number; + + /** + * Speed of zoom when user rolls the mouse wheel. Default is 1. + * Set to a negative number to reverse the zoom direction. + */ + setScrollWheelZoomSpeed(scrollWheelZoomSpeed: number): void; + + /** + * Specifies the speed at which the camera moves (0 to 5.0). + * Set to SPEED_TELEPORT to immediately appear at selected destination. + * + * See also: + * + * * GEPlugin.SPEED_TELEPORT + */ + getFlyToSpeed(): number; + + /** + * Specifies the speed at which the camera moves (0 to 5.0). + * Set to SPEED_TELEPORT to immediately appear at selected destination. + * + * See also: + * + * * GEPlugin.SPEED_TELEPORT + */ + setFlyToSpeed(flyToSpeed: number): void; + + /** + * Show or hide the status bar. Disabled by default. + */ + getStatusBarVisibility(): boolean; + + /** + * Show or hide the status bar. Disabled by default. + */ + setStatusBarVisibility(statusBarVisibility: boolean): void; + + /** + * Show or hide the grid. Disabled by default. + */ + getGridVisibility(): boolean; + + /** + * Show or hide the grid. Disabled by default. + */ + setGridVisibility(gridVisibility: boolean): void; + + /** + * Show or hide the overview map. Disabled by default. + */ + getOverviewMapVisibility(): boolean; + + /** + * Show or hide the overview map. Disabled by default. + */ + setOverviewMapVisibility(overviewMapVisibility: boolean): void; + + /** + * Show or hide the scale legend. Disabled by default. + */ + getScaleLegendVisibility(): boolean; + + /** + * Show or hide the scale legend. Disabled by default. + */ + setScaleLegendVisibility(scaleLegendVisibility: boolean): void; + + /** + * Show or hide the blue atmosphere that appears around the perimeter of the Earth. + * On by default. + */ + getAtmosphereVisibility(): boolean; + + /** + * Show or hide the blue atmosphere that appears around the perimeter of the Earth. + * On by default. + */ + setAtmosphereVisibility(atmosphereVisibility: boolean): void; + + /** + * Enable or disable user panning and zooming of the map. Enabled by default. + * + * Note: This also enables and disables keyboard navigation (arrow keys, page-up/page-down, etc). + */ + getMouseNavigationEnabled(): boolean; + + /** + * Enable or disable user panning and zooming of the map. Enabled by default. + * + * Note: This also enables and disables keyboard navigation (arrow keys, page-up/page-down, etc). + */ + setMouseNavigationEnabled(mouseNavigationEnabled: boolean): void; + + /** + * Returns true if the animation of features as they are added or removed from the globe has been enabled. + */ + getFadeInOutEnabled(): boolean; + + /** + * Enable or disable the animation of a feature when it is added or removed from the Google Earth plugin. + * The animation consists of a slight change of scale. Default is true. + */ + setFadeInOutEnabled(fadeInOutEnabled: boolean): void; + + /** + * Returns true if display units are set to imperial units (feet and miles). + * False denotes metric units (meters and kilometers). + */ + getUnitsFeetMiles(): boolean; + + /** + * Set display units to imperial (feet and miles) or metric (meters and kilometers). + * This setting affects only the values displayed in the status bar and the scale bar. + * The values passed and returned with an object's getters and setters are always metric. + */ + setUnitsFeetMiles(unitsFeetMiles: boolean): void; + + /** + * Enables or disables building selection. + * If enabled, clicking a building will pop a feature balloon containing information from the Google 3D Warehouse database. + */ + setBuildingSelectionEnabled(buildingSelectionEnabled: boolean): void; + + /** + * Whether or not building selection is enabled. + */ + getBuildingSelectionEnabled(): boolean; + + /** + * Returns true if building highlighting is enabled. + */ + getBuildingHighlightingEnabled(): boolean; + + /** + * Enables or disables building highlighting. + * When enabled, buildings will be highlighted when they are moused over. + */ + setBuildingHighlightingEnabled(buildingHighlightingEnabled: boolean): void; + + /** + * Returns the terrain exaggeration value. Valid values are in the range of 1.0 through 3.0. + */ + getTerrainExaggeration(): number; + + /** + * Set the terrain exaggeration value. Valid values are in the range of 1.0 through 3.0. + * Attempting to set outside of this range will result in the value being clamped. + */ + setTerrainExaggeration(terrainExaggeration: number): void; + + /** + * When enabled, the view will change to 'ground level view' when the camera reaches ground level. + * This view provides pan and lookAt controls, but no zoom slider. + * The tilt will be set to 90, or parallel with level ground. + */ + setAutoGroundLevelViewEnabled(autoGroundLevelViewEnabled: boolean): void; + + /** + * Whether automatic ground level view is enabled. + */ + getAutoGroundLevelViewEnabled(): boolean; + } + + /** + * Adds a node to the end of the list of children of a specified feature. + * Returns the appended object. + */ + export class GESchemaObjectContainer { + + /** + * Adds a node to the end of the list of children of a specified feature. + * Returns the appended object. + */ + appendChild(object: T): void; + + /** + * Removes a node from the list of children of a specified object. + */ + removeChild(oldChild: T): void; + + /** + * Inserts a child before the referenced child in the list of objects. + */ + insertBefore(newChild: T, refChild: T): void; + + /** + * Replaces existing child in the list of features. + * Returns the old child. + */ + replaceChild(newChild: T, oldChild: T): void; + + /** + * Returns true if the container is not empty. + */ + hasChildNodes(): boolean; + + /** + * First child in the list of objects. + */ + getFirstChild(): T; + + /** + * Last child in the list of objects. + */ + getLastChild(): T; + + /** + * List of features (for KmlContainer), or list of features, styles, and schemas (for KmlDocument). + * Returns true if there are any child nodes. + */ + getChildNodes(): KmlObjectList; + } + + /** + * A container class that holds one or more features and allows the creation of nested hierarchies. + */ + export class GEFeatureContainer extends GESchemaObjectContainer {} + + /** + * A container object that contains an array of geometries, typically the children of a multi-geometry. + */ + export class GEGeometryContainer extends GESchemaObjectContainer {} + + /** + * A container object that contains an array of closed line strings, typically the outer boundary of a Polygon. + * Optionally, a LinearRing can also be used as the inner boundary of a Polygon to create holes in the Polygon. + * A Polygon can contain multiple LinearRing objects used as inner boundaries. + */ + export class GELinearRingContainer extends GESchemaObjectContainer {} + + /** + * A container that holds a collection of KmlStyle and KmlStyleMap objects. + * The KmlStyleMap object selects a style based on the current mode of the Placemark. + * An object derived from KmlStyleSelector is uniquely identified by its ID and its URL. + */ + export class GEStyleSelectorContainer extends GESchemaObjectContainer {} + + /** + * Defines the x and y coordinates of a 2D vector. + */ + export class KmlVec2 { + + /** + * Sets the coordinates of the vector. + */ + set( + x: number, + xUnits: KmlUnitsEnum, + y: number, + yUnits: KmlUnitsEnum + ): void; + + /** + * Indicates the x coordinate. + */ + getX(): number; + + /** + * Indicates the x coordinate. + */ + setX(x: number): void; + + /** + * Indicates the y coordinate. + */ + getY(): number; + + /** + * Indicates the y coordinate. + */ + setY(y: number): void; + + /** + * Units in which the x value is specified. + * + * See also: + * + * * GEPlugin.UNITS_FRACTION + * * GEPlugin.UNITS_PIXELS + * * GEPlugin.UNITS_INSET_PIXELS + */ + getXUnits(): KmlUnitsEnum; + + /** + * Units in which the x value is specified. + * + * See also: + * + * * GEPlugin.UNITS_FRACTION + * * GEPlugin.UNITS_PIXELS + * * GEPlugin.UNITS_INSET_PIXELS + */ + setXUnits(xUnits: KmlUnitsEnum): void; + + /** + * Units in which the y value is specified. + * + * See also: + * + * * GEPlugin.UNITS_FRACTION + * * GEPlugin.UNITS_PIyELS + * * GEPlugin.UNITS_INSET_PIyELS + */ + getYUnits(): KmlUnitsEnum; + + /** + * Units in which the y value is specified. + * + * See also: + * + * * GEPlugin.UNITS_FRACTION + * * GEPlugin.UNITS_PIyELS + * * GEPlugin.UNITS_INSET_PIyELS + */ + setYUnits(xUnits: KmlUnitsEnum): void; + } + + /** + * The GESun class controls the dawn to dusk views. + */ + export class GESun { + + /** + * Specifies whether the feature is drawn in the 3D viewer when it is initially loaded. + * In order for a feature to be visible, the visibility property and all of its ancestors must also be set to 1. + */ + getVisibility(): boolean; + + /** + * Specifies whether the feature is drawn in the 3D viewer when it is initially loaded. + * In order for a feature to be visible, the visibility property and all of its ancestors must also be set to 1. + */ + setVisibility(visibility: boolean): void; + } + + /** + * The KmlColor object values are expressed in hexadecimal notation. + * The range of values for any one color component is 0 to 255 (00 to ff). + * For alpha, 00 is fully transparent and ff is fully opaque. + * The order of expression is aabbggrr, where aa=alpha (00 to ff); bb=blue (00 to ff); gg=green (00 to ff); rr=red (00 to ff). + * For example, if you want to apply a blue color with 50 percent opacity to an overlay, + * you would specify the following when setting color value: 7fff0000, where alpha=0x7f, blue=0xff, green=0x00, and red=0x00. + */ + export class KmlColor { + + /** + * Set the color of an object. + */ + set(color: string): void; + + /** + * Returns the color of an object. + */ + get(): string; + + /** + * red numerical value + */ + getR(): number; + + /** + * red numerical value + */ + setR(r: number): void; + + /** + * green numerical value + */ + getG(): number; + + /** + * green numerical value + */ + setG(g: number): void; + + /** + * blue numerical value + */ + getB(): number; + + /** + * blue numerical value + */ + setB(b: number): void; + + /** + * opacity value + */ + getA(): number; + + /** + * opacity value + */ + setA(a: number): void; + } + + /** + * The event object used with all KMLObjects. + * For more information about events, see the Document Object Model Events specification at http: + */ + export class KmlEvent { + + /** + * Cancels the default action of the event. + * For example, calling this method in a placemark click handler prevents the placemark's default balloon from popping up. + */ + preventDefault(): void; + + /** + * Prevents event propagation. + * For example, if click event handlers are set up on both the GEGlobe and GEWindow objects, + * and stopPropagation is called in the GEGlobe click event handler, the GEWindow event handler will not be triggered when the globe is clicked. + */ + stopPropagation(): void; + + /** + * The object to which the KMLEvent was originally dispatched. + */ + getTarget(): GEEventEmitter; + + /** + * The target whose event listeners are currently being processed. + */ + getCurrentTarget: GEEventEmitter; + + /** + * The current stage of the flow of events. + */ + getEventPhase(): GEEventPhaseEnum; + + /** + * Indicates whether or not an event is a bubbling event. + */ + getBubbles(): boolean; + + /** + * Indicates whether the event can be cancelled. + * + * Note: Currently, cancelable has no effect. + */ + getCancelable(): boolean; + } + + /** + * Represents a mouse input event. + */ + export class KmlMouseEvent extends KmlEvent { + + /** + * The button on the mouse was pressed. + * Possible values include 0, 1, 2, where 0 is left, 1 is middle, and 2 is right mouse key. + */ + getButton(): number; + + /** + * The x coordinate at which the event occurred, measured in pixels from the left edge of the plug-in window. + */ + getClientX(): number; + + /** + * The y coordinate at which the event occurred, measured in pixels from the top edge of the plug-in window. + */ + getClientY(): number; + + /** + * The x coordinate at which the event occurred, measured in pixels from the left edge of the computer screen. + */ + getScreenX(): number; + + /** + * The y coordinate at which the event occurred, measured in pixels from the top edge of the computer screen. + */ + getScreenY(): number; + + /** + * The latitude at which the event occurred, in decimal degrees. + */ + getLatitude(): number; + + /** + * The longitude at which the event occurred, in decimal degrees. + */ + getLongitude(): number; + + /** + * The altitude at which the event occurred, in meters. + */ + getAltitude(): number; + + /** + * Indicates whether a mouse action occurred while on the Google Earth globe. + */ + getDidHitGlobe(): boolean; + + /** + * Indicates whether the ALT key was held down when an event occurred. + */ + getAltKey(): boolean; + + /** + * Indicates whether the CTRL key was held down when an event occurred. + */ + getCtrlKey(): boolean; + + /** + * Indicates whether the SHIFT key was held down when an event occurred. + */ + getShiftKey(): boolean; + + /** + * Used with the mouseover and mouseout events to specify a secondary target. + * For mouseover, it specifies the object that the mouse was over. + * For mouseout, it specifies the new object that the mouse is over. + */ + getRelatedTarget(): GEEventEmitter; + + /** + * Returns the timestamp of the event, in Unix time. + */ + getTimeStamp(): number; + } + + /** + * Defines when and how an event gets passed in and triggered from the Google Earth Plug-in. + */ + export class GEEventEmitter { + + /** + * Triggers an event when the user clicks a location in Google Earth with the mouse. + */ + click(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user double clicks a location in Google Earth with the mouse. + */ + dblclick(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user moves the mouse pointer over a location in Google Earth. + */ + mouseover(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user presses the mouse button over a location in Google Earth. + */ + mousedown(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user releases the mouse button over a location in Google Earth. + */ + mouseup(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user moves the mouse off of the object in Google Earth. + */ + mouseout(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user moves the mouse inside Google Earth. + */ + mousemove(event: KmlMouseEvent): void; + } + + /** + * The base class for all the other objects in the Google Earth Plug-in. + * The methods and behavior of KMLObject are inherited by all other objects. + * This is an abstract base class and cannot be used directly. + * It provides the id attribute, which allows unique identification of an object. + */ + export class KmlObject extends GEEventEmitter { + + /** + * The interface name (i.e. 'KmlPlacemark') of the object. + */ + getType(): string; + + /** + * Test whether this object is the same as another object. + * Useful for Chrome and Safari, where the comparison a==b sometimes fails for plugin objects. + */ + equals(compareTo: KmlObject): boolean; + + /** + * The unique ID of the KML object. + */ + getId(): string; + + /** + * The unique URL of the KML object. + * This is the base address joined with the ID using the # character. + * + * For example: http://www.google.com/bar.kml#atlantis + */ + getUrl(): string; + + /** + * The parent node of the KML object. + */ + getParentNode(): KmlObject; + + /** + * The document that owns the KML object. + */ + getOwnerDocument(): KmlDocument; + + /** + * Permanently deletes an object, allowing its ID to be reused. + * Attempting to access the object once it is released will result in an error. + */ + release(): void; + } + + /** + * A collection of KmlObjects. + */ + export class KmlObjectList { + + /** + * Gets an item from the object list. For example, list.item(0) returns the first object in the list. + */ + item(index: number): T; + + /** + * Number of objects in collection. + */ + getLength(): number; + } + + /** + * The base class for KmlStyle and KmlStyleMap. + */ + export class KmlStyleSelector extends KmlObject {} + + /** + * Defines the icon, label, line, list, polygon, and balloon styles. + */ + export class KmlStyle extends KmlStyleSelector { + + /** + * Specifies how icons for point placemarks are drawn in Google Earth. + */ + getIconStyle(): KmlIconStyle; + + /** + * Specifies how the name of a feature is drawn in the 3D viewer. + * A custom color, color mode, and scale for the label (name) can be specified. + */ + getLabelStyle(): KmlLabelStyle; + + /** + * Specifies the drawing style (color, color mode, and line width) for line geometry. + * Line geometry includes the outlines of outlined polygons and the extruded tether of Placemark icons (if extrusion is enabled). + */ + getLineStyle(): KmlLineStyle; + + /** + * Specifies the style for list geometry. + */ + getListStyle(): KmlListStyle; + + /** + * Specifies the drawing style for polygons, including polygon extrusions (which look like the walls of buildings) and line extrusions (which look like solid fences). + */ + getPolyStyle(): KmlPolyStyle; + + /** + * Specifies the drawing style for balloons. + */ + getBalloonStyle(): KmlBalloonStyle; + } + + /** + * The KmlColorStyle object is an abstract object. + * It specifies the color and color mode of extended style types. + */ + export class KmlColorStyle extends KmlObject { + + /** + * Color and opacity (alpha) values. + */ + getColor(): KmlColor; + + /** + * Specifies which color mode effect to apply to the base color. + * + * See also: + * + * * GEPlugin.COLOR_NORMAL + * * GEPlugin.COLOR_INHERIT + * * GEPlugin.COLOR_RANDOM + */ + getColorMode(): KmlColorModeEnum; + + /** + * Specifies which color mode effect to apply to the base color. + * + * See also: + * + * * GEPlugin.COLOR_NORMAL + * * GEPlugin.COLOR_INHERIT + * * GEPlugin.COLOR_RANDOM + */ + setColorMode(colorMode: KmlColorModeEnum): void; + } + + /** + * Specifies how icons for point placemarks are drawn in Google Earth. + * The icon property specifies the icon image. + * The scale property specifies the x, y scaling of the icon. + * The color specified in the color property of KmlIconStyle is blended with the color of the Icon. + */ + export class KmlIconStyle extends KmlColorStyle { + + /** + * Resizes the icon. + */ + getScale(): number; + + /** + * Resizes the icon. + */ + setScale(scale: number): void; + + /** + * The direction that icons are set to point, clockwise, and in degrees. + */ + getHeading(): number; + + /** + * The direction that icons are set to point, clockwise, and in degrees. + */ + setHeading(heading: number): void; + + /** + * A custom Icon. In KmlIconStyle, the only child element of KmlIcon is href and href is an HTTP address or a local file specification used to load an icon. + */ + getIcon(): KmlIcon; + + /** + * A custom Icon. In KmlIconStyle, the only child element of KmlIcon is href and href is an HTTP address or a local file specification used to load an icon. + */ + setIcon(icon: KmlIcon): void; + + /** + * Specifies the position within the Icon that is anchored to the point specified in the placemark. + * The x and y values can be specified in three different ways: as pixels, as fractions of the icon, or as inset pixels, which is an offset in pixels from the upper right corner of the icon. + * The x and y positions can be specified in different ways. + * For example, x can be in pixels and y can be a fraction. + * The origin of the coordinate system is in the lower left corner of the icon. + */ + getHotSpot(): KmlVec2; + } + + /** + * Specifies how the name of a feature is drawn in the 3D viewer. + * A custom color, color mode, and scale for the label (name) can be specified. + */ + export class KmlLabelStyle extends KmlColorStyle { + + /** + * Resizes the label. + */ + getScale(): number; + + /** + * Resizes the label. + */ + setScale(scale: number): void; + } + + /** + * The KmlLineStyle object specifies the drawing style (color, color mode, and line width) for all line geometry. + * Line geometry includes the outlines of outlined polygons and the extruded "tether" of Placemark icons (if extrusion is enabled). + */ + export class KmlLineStyle extends KmlColorStyle { + + /** + * Width of the line, in pixels. + */ + getWidth(): number; + + /** + * Width of the line, in pixels. + */ + setWidth(width: number): void; + } + + /** + * Specifies the drawing style for all polygons, including polygon extrusions (which look like the walls of buildings) and line extrusions (which look like solid fences). + */ + export class KmlPolyStyle extends KmlColorStyle { + + /** + * Specifies whether or not to fill the polygon. Possible values 1 (fill) and 0 (no fill). + */ + getFill(): boolean; + + /** + * Specifies whether or not to fill the polygon. Possible values 1 (fill) and 0 (no fill). + */ + setFill(fill: boolean): void; + + /** + * Specifies whether to outline the polygon. Polygon outlines use the current KmlLineStyle. + */ + getOutline(): boolean; + + /** + * Specifies whether to outline the polygon. Polygon outlines use the current KmlLineStyle. + */ + setOutline(outline: boolean): void; + } + + /** + * Specifies how a feature is displayed in the list view. + */ + export class KmlListStyle extends KmlObject { + + /** + * Background color for the Snippet. + */ + getBgColor(): KmlColor; + + /** + * Maximum number of lines of text for the Snippet. + */ + getMaxSnippetLines(): number; + + /** + * Maximum number of lines of text for the Snippet. + */ + setMaxSnippetLines(maxSnippetLines: number): void; + + /** + * Specifies how a feature should be displayed in a list view. + */ + getListItemType(): KmlListItemTypeEnum; + } + + /** + * Specifies how the description balloon for placemarks is drawn. + */ + export class KmlBalloonStyle extends KmlObject { + + /** + * Background color of the balloon (optional). + */ + getBgColor(): KmlColor; + + /** + * Foreground color for text. The default is black (ff000000). + */ + getTextColor(): KmlColor; + + /** + * The text contained in the balloon. + */ + getText(): string; + + /** + * The text contained in the balloon. + */ + setText(text: string): void; + } + + /** + * Specifies the top, bottom, right, and left sides of a bounding box on the Earth's surface. + */ + export class KmlLatLonBox extends KmlObject { + + /** + * Sets the north, south, east, and west edges of the bounding box, as well as the rotation of the overlay. + */ + setBox( + north: number, + south: number, + east: number, + west: number, + rotation: number + ): void; + + /** + * Specifies the latitude of the north edge of the bounding box, in decimal degrees from -90 to 90. + */ + getNorth(): number; + + /** + * Specifies the latitude of the north edge of the bounding box, in decimal degrees from -90 to 90. + */ + setNorth(north: number): void; + + /** + * Specifies the latitude of the south edge of the bounding box, in decimal degrees from -90 to 90. + */ + getSouth(): number; + + /** + * Specifies the latitude of the south edge of the bounding box, in decimal degrees from -90 to 90. + */ + setSouth(south: number): void; + + /** + * Specifies the longitude of the east edge of the bounding box, in decimal degrees from -180 to 180. + * (For overlays that overlap the meridian of 180 degrees longitude, values can extend beyond that range.) + */ + getEast(): number; + + /** + * Specifies the longitude of the east edge of the bounding box, in decimal degrees from -180 to 180. + * (For overlays that overlap the meridian of 180 degrees longitude, values can extend beyond that range.) + */ + setEast(east: number): void; + + /** + * Specifies the longitude of the west edge of the bounding box, in decimal degrees from -180 to 180. + * (For overlays that overlap the meridian of 180 degrees longitude, values can extend beyond that range.) + */ + getWest(): number; + + /** + * Specifies the longitude of the west edge of the bounding box, in decimal degrees from -180 to 180. + * (For overlays that overlap the meridian of 180 degrees longitude, values can extend beyond that range.) + */ + setWest(west: number): void; + + /** + * Specifies a rotation of the overlay about its center, in degrees. + * Values can be +/-180. The default is 0 (north). + * Rotations are specified in a counterclockwise direction. + */ + getRotation(): number; + + /** + * Specifies a rotation of the overlay about its center, in degrees. + * Values can be +/-180. The default is 0 (north). + * Rotations are specified in a counterclockwise direction. + */ + setRotation(rotation: number): void; + } + + /** + * Specifies a bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + export class KmlLatLonAltBox extends KmlLatLonBox { + + /** + * Sets the north, south, east, west, rotation, minAltitude, maxAltitude, and altitudeMode of bounding box. + */ + setAltBox( + north: number, + south: number, + east: number, + west: number, + rotation: number, + minAltitude: number, + maxAltitude: number, + altitudeMode: KmlAltitudeModeEnum + ): void; + + /** + * Minimum altitude, specified in meters above sea level. + */ + getMinAltitude(): number; + + /** + * Minimum altitude, specified in meters above sea level. + */ + setMinAltitude(minAltitude: number): void; + + /** + * Maximim altitude, specified in meters above sea level. + */ + getMaxAltitude(): number; + + /** + * Maximim altitude, specified in meters above sea level. + */ + setMaxAltitude(maxAltitude: number): void; + + /** + * Specifies how the altitude property is interpreted. + * + * See also: + * + * * GEPlugin.ALTITUDE_CLAMP_TO_GROUND + * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_CLAMP_TO_SEA_FLOOR + * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR + */ + getAltitudeMode(): KmlAltitudeModeEnum; + + /** + * Specifies how the altitude property is interpreted. + * + * See also: + * + * * GEPlugin.ALTITUDE_CLAMP_TO_GROUND + * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_CLAMP_TO_SEA_FLOOR + * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR + */ + setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): number; + } + + /** + * The KmlLod or level of detail, describes the size of the projected region on the screen that is required in order for the region to be considered active. + * Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent). + */ + export class KmlLod extends KmlObject { + + /** + * Sets the minLodPixels, maxLodPixels, minFadeExtent, and maxFadeExtent for the projected region on the screen. + */ + set( + minLodPixels: number, + maxLodPixels: number, + minFadeExtent: number, + maxFadeExtent: number + ): void; + + /** + * Specifies measurement in screen pixels that represents the minimum limit of the visibility range for a given Region. + * Google Earth calculates the size of the region when projected onto screen space. + * Then it computes the square root of the region's area (if, for example, the Region is square and the viewpoint is directly above the Region, and the Region is not tilted, this measurement is equal to the width of the projected Region). + * If this measurement falls within the limits defined by minLodPixels and maxLodPixels (and if the LatLonAltBox is in view), the region is active. + * If this limit is not reached, the associated geometry is considered to be too far from the user's viewpoint to be drawn. + */ + getMinLodPixels(): number; + + /** + * Specifies measurement in screen pixels that represents the minimum limit of the visibility range for a given Region. + * Google Earth calculates the size of the region when projected onto screen space. + * Then it computes the square root of the region's area (if, for example, the Region is square and the viewpoint is directly above the Region, and the Region is not tilted, this measurement is equal to the width of the projected Region). + * If this measurement falls within the limits defined by minLodPixels and maxLodPixels (and if the LatLonAltBox is in view), the region is active. + * If this limit is not reached, the associated geometry is considered to be too far from the user's viewpoint to be drawn. + */ + setMinLodPixels(minLodPixels: number): void; + + /** + * Measurement in screen pixels that represents the maximum limit of the visibility range for a given Region. + * A value of -1, the default, indicates "active to infinite size." + */ + getMaxLodPixels(): number; + + /** + * Measurement in screen pixels that represents the maximum limit of the visibility range for a given Region. + * A value of -1, the default, indicates "active to infinite size." + */ + setMaxLodPixels(maxLogPixels: number): void; + + /** + * Distance over which the geometry fades, from fully opaque to fully transparent. + * This ramp value, expressed in screen pixels, is applied at the minimum end of the LOD (visibility) limits. + */ + getMinFadeExtent(): number; + + /** + * Distance over which the geometry fades, from fully opaque to fully transparent. + * This ramp value, expressed in screen pixels, is applied at the minimum end of the LOD (visibility) limits. + */ + setMinFadeExtent(minFadeExtent: number): void; + + /** + * Distance over which the geometry fades, from fully transparent to fully opaque. + * This ramp value, expressed in screen pixels, is applied at the maximum end of the LOD (visibility) limits. + */ + getMaxFadeExtent(): number; + + /** + * Distance over which the geometry fades, from fully transparent to fully opaque. + * This ramp value, expressed in screen pixels, is applied at the maximum end of the LOD (visibility) limits. + */ + setMaxFadeExtent(maxFadeExtent: number): void; + } + + /** + * The KmlRegion object is used to set region objects and their properties. + * A region contains a bounding box (LatLonAltBox) that describes an area of interest defined by geographic coordinates and altitudes. + * In addition, a Region contains an LOD (level of detail) extent that defines a validity range of the associated Region in terms of projected screen size. + * A Region is said to be "active" when the bounding box is within the user's view and the LOD requirements are met. + * Objects associated with a Region are drawn only when the Region is active. + * When the viewRefreshMode is onRegion, the Link or Icon is loaded only when the Region is active. + */ + export class KmlRegion extends KmlObject { + + /** + * Sets the latLonAltBox and lod for the region. + */ + set(latLonAltBox: KmlLatLonAltBox, lod: KmlLod): void; + + /** + * A bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + getLatLonAltBox(): KmlLatLonAltBox; + + /** + * A bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + setLatLonAltBox(latLonAltBox: KmlLatLonAltBox): void; + + /** + * LOD is an abbreviation for Level of Detail. + * Lod describes the size of the projected region on the screen that is required in order for the region to be considered "active. + * " Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent). + */ + getLod(): KmlLod; + + /** + * LOD is an abbreviation for Level of Detail. + * Lod describes the size of the projected region on the screen that is required in order for the region to be considered "active. + * " Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent). + */ + setLod(lod: KmlLod): void; + } + + /** + * Represents a specific point in time. + * The plugin accepts time in this format only; it does not accept JavaScript date or time objects. + */ + export class KmlDateTime { + + /** + * Set the date. Accepts only XML Schema time (see XML Schema Part 2: Datatypes Second Edition). + * The value can be expressed as yyyy-mm-ddThh:mm:sszzzzzz, where T is the separator between the date and the time, + * and the time zone is either Z(for UTC) or zzzzzz, which represents +/-hh:mm in relation to UTC. + * Additionally, the value can be expressed as a date only. + */ + set(date: string): void; + + /** + * Returns the date and time in XML Schema time format. + */ + get(): string; + } + + /** + * An abstract object and cannot be used directly in a JavaScript file. + * This element is extended by the TimeSpan and TimeStamp objects. + */ + export class KmlTimePrimitive extends KmlObject {} + + /** + * Represents a single moment in time. + * This is a simple element and contains no children. + * Its value is a dateTime, specified in XML time. + * The precision of the TimeStamp is dictated by the dateTime value in the when property. + */ + export class KmlTimeStamp extends KmlTimePrimitive { + + /** + * Represents a single moment in time. + * This is a simple element and contains no children. + * Its value is a dateTime, specified in XML time. + * The precision of the TimeStamp is dictated by the dateTime value in the when property. + * + * * dateTime gives second resolution + * * date gives day resolution + * * gYearMonth gives month resolution + * * gYear gives year resolution + */ + getWhen(): KmlDateTime; + } + + /** + * Represents an extent in time bounded by begin and end dateTimes. + */ + export class KmlTimeSpan extends KmlTimePrimitive { + + /** + * Describes the beginning instant of a time period. + * If absent, the beginning of the period is unbounded. + */ + getBegin(): KmlDateTime; + + /** + * Describes the ending instant of a time period. + * If absent, the end of the period is unbounded. + */ + getEnd(): KmlDateTime; + } + + /** + * This is an abstract class and cannot be created directly. + * This class is extended by KmlCamera and KmlLookAt. + */ + export class KmlAbstractView extends KmlObject { + + /** + * Creates a new KmlLookAt object that matches as closely as possible this KmlAbstractView. + * KmlLookAt is unable to represent roll, so roll values in the current view will not be passed to the new KmlLookAt object. + * + * If this view is already a KmlLookAt, this function returns a new KmlLookAt representing the same view. + */ + copyAsLookAt(): KmlLookAt; + + /** + * Creates a new KmlCamera object that matches this KmlAbstractView. + * + * If this view is already a KmlCamera, this function returns a new KmlCamera representing the same view. + */ + copyAsCamera(): KmlCamera; + + /** + * Returns the KmlTimeStamp or KmlTimeSpan object associated with this view. + */ + getTimePrimitive(): KmlTimePrimitive; + + /** + * Associate a KmlTimeStamp or KmlTimeSpan object with this view. + */ + setTimePrimitive(timePrimitive: KmlTimePrimitive): void; + + /** + * Returns the viewer options on the current view. + * + * See also: + * + * * GEPlugin.OPTION_STREET_VIEW + * * GEPlugin.OPTION_SUNLIGHT + * * GEPlugin.OPTION_HISTORICAL_IMAGERY + */ + getViewerOptions(): KmlViewerOptions; + + /** + * Sets the viewer options on the current view. + * + * See also: + * + * * GEPlugin.OPTION_STREET_VIEW + * * GEPlugin.OPTION_SUNLIGHT + * * GEPlugin.OPTION_HISTORICAL_IMAGERY + */ + setViewerOptions(viewerOptions: KmlViewerOptions): void; + } + + /** + * Defines a camera that is associated with anything derived from feature. + * The LookAt element positions the "camera" in relation to the object that is being viewed. + * This class either positions the relative to a feature, or you can manually change the view, using ge.getView().setAbstractView(). + */ + export class KmlLookAt extends KmlAbstractView { + + /** + * Sets the latitude, longitude, altitude, altitudeMode, heading, tilt, and range for the camera. + */ + set ( + latitude: number, + longitude: number, + altitude: number, + altitudeMode: KmlAltitudeModeEnum, + heading: number, + tilt: number, + range: number + ): void; + + /** + * Latitude of the point the camera is looking at. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + getLatitude(): number; + + /** + * Latitude of the point the camera is looking at. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + setLatitude(latitude: number): void; + + /** + * Latitude of the point the camera is looking at. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + getLongitude(): number; + + /** + * Latitude of the point the camera is looking at. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + setLongitude(longitude: number): void; + + /** + * The distance in meters from the point specified by longitude, latitude, and altitude for the LookAt position. + */ + getRange(): number; + + /** + * The distance in meters from the point specified by longitude, latitude, and altitude for the LookAt position. + */ + setRange(range: number): void; + + /** + * Angle between the direction of the LookAt position and the normal to the surface of the earth. + * Values range from 0 to 90 degrees. Values for tilt cannot be negative. + * A tilt value of 0 degrees indicates viewing from directly above. + * A tilt value of 90 degrees indicates viewing along the horizon. + */ + getTilt(): number; + + /** + * Angle between the direction of the LookAt position and the normal to the surface of the earth. + * Values range from 0 to 90 degrees. Values for tilt cannot be negative. + * A tilt value of 0 degrees indicates viewing from directly above. + * A tilt value of 90 degrees indicates viewing along the horizon. + */ + setTilt(tilt: number): void; + + /** + * Direction (that is, North, South, East, West), in degrees. Default=0 (North). Values range from 0 to 360 degrees. + */ + getHeading(): number; + + /** + * Direction (that is, North, South, East, West), in degrees. Default=0 (North). Values range from 0 to 360 degrees. + */ + setHeading(heading: number): void; + + /** + * Distance from the earth's surface, in meters. + */ + getAltitude(): number; + + /** + * Distance from the earth's surface, in meters. + */ + setAltitude(altitude: number): void; + + /** + * Specifies how altitude components in the coordinates element are interpreted. + */ + getAltitudeMode(): KmlAltitudeModeEnum; + + /** + * Specifies how altitude components in the coordinates element are interpreted. + */ + setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): void; + } + + /** + * Defines the camera that views the scene. + * This element defines the position of the camera relative to the Earth's surface as well as the viewing direction of the camera. + * The camera position is defined by longitude, latitude, altitude, and altitudeMode. + * The viewing direction of the camera is defined by heading, tilt, and roll. + * Camera can be a child element of any feature. + */ + export class KmlCamera extends KmlAbstractView { + + /** + * Sets the latitude, longitude, altitude, alitudeMode, heading, tilt, and roll values. + */ + set( + latitude: number, + longitude: number, + altitude: number, + altitudeMode: KmlAltitudeModeEnum, + heading: number, + tilt: number, + roll: number + ): void; + + /** + * Latitude of the camera location. Degrees north or south of the Equator (0 degrees). Values range from -90 degrees to 90 degrees. + */ + getLatitude(): number; + + /** + * Latitude of the camera location. Degrees north or south of the Equator (0 degrees). Values range from -90 degrees to 90 degrees. + */ + setLatitude(latitude: number): void; + + /** + * Longitude of the camera location. Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + getLongitude(): number; + + /** + * Longitude of the camera location. Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + setLongitude(longitude: number): void; + + /** + * Distance from the earth's surface. + */ + getAltitude(): number; + + /** + * Distance from the earth's surface. + */ + setAltitude(altitude: number): void; + + /** + * Direction (that is, North, South, East, West), in degrees. Default=0 (North). Values range from 0 to 360 degrees. + */ + getHeading(): number; + + /** + * Direction (that is, North, South, East, West), in degrees. Default=0 (North). Values range from 0 to 360 degrees. + */ + setHeading(heading: number): void; + + /** + * Angle between the direction of the camera position and the normal to the surface of the earth. Values range from 0 to 360 degrees. + * A tilt value of 0 degrees indicates viewing from directly above, 90 degrees indicates viewing along the horizon, and 180 degrees indicates viewing straight up at the sky. + */ + getTilt(): number; + + /** + * Angle between the direction of the camera position and the normal to the surface of the earth. Values range from 0 to 360 degrees. + * A tilt value of 0 degrees indicates viewing from directly above, 90 degrees indicates viewing along the horizon, and 180 degrees indicates viewing straight up at the sky. + */ + setTilt(tilt: number): void; + + /** + * Rotation, in degrees, of the camera around the Z axis. Values range from -180 to +180 degrees. + */ + getRoll(): number; + + /** + * Rotation, in degrees, of the camera around the Z axis. Values range from -180 to +180 degrees. + */ + setRoll(roll: number): void; + + /** + * Specifies how altitude components in the coordinates are interpreted. + */ + getAltitudeMode(): KmlAltitudeModeEnum; + + /** + * Specifies how altitude components in the coordinates are interpreted. + */ + setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): void; + } + + /** + * The KmlGeometry object is an abstract object and cannot be used directly. + * It provides a placeholder object for all derived Geometry objects. + */ + export class KmlGeometry extends KmlObject {} + + /** + * Specifies an AltitudeMode for derived classes. + */ + export class KmlAltitudeGeometry extends KmlGeometry { + + /** + * Specifies how altitude components in the geometry coordinates are interpreted. + */ + getAltitudeMode(): KmlAltitudeModeEnum; + + /** + * Specifies how altitude components in the geometry coordinates are interpreted. + */ + setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): void; + } + + /** + * A 3D object described in a referenced COLLADA file. + * COLLADA files have a .dae file extension. + * Models are created in their own coordinate space and then located, positioned, and scaled in Google Earth. + * Google Earth supports the COLLADA common profile, with the following exceptions: + * + * * Google Earth supports only triangles and lines as primitive types. The maximum number of triangles allowed is 21845. + * * Google Earth does not support animation or skinning. + * * Google Earth does not support external geometry references. + */ + export class KmlModel extends KmlAltitudeGeometry { + + /** + * Specifies the exact coordinates of the Model's origin in latitude, longitude, and altitude. + * Latitude and longitude measurements are standard lat-lon projection with WGS84 datum. + * Altitude is distance above the earth's surface, in meters, and is interpreted according to altitudeMode. + */ + getLocation(): KmlLocation; + + /** + * Specifies the exact coordinates of the Model's origin in latitude, longitude, and altitude. + * Latitude and longitude measurements are standard lat-lon projection with WGS84 datum. + * Altitude is distance above the earth's surface, in meters, and is interpreted according to altitudeMode. + */ + setLocation(location: KmlLocation): void; + + /** + * Describes rotation of a 3D model's coordinate system to position the object in Google Earth. + */ + getOrientation(): KmlOrientation; + + /** + * Describes rotation of a 3D model's coordinate system to position the object in Google Earth. + */ + setOrientation(orientation: KmlOrientation): void; + + /** + * Scales a model along the x, y, and z axes in the model's coordinate space + */ + getScale(): KmlScale; + + /** + * Scales a model along the x, y, and z axes in the model's coordinate space + */ + setScale(scale: KmlScale): void; + + /** + * Returns the link of the collada model. + */ + getLink(): KmlLink; + + /** + * Sets the link of the collada model. + */ + setLink(link: KmlLink): void; + } + + /** + * A container for zero or more geometry primitives associated with the same feature. + */ + export class KmlMultiGeometry extends KmlGeometry { + + /** + * The collection of geometries that are children of this multi-geometry. + */ + getGeometries(): GEGeometryContainer; + } + + /** + * Specifies the behavior of the object's geometry. + */ + export class KmlExtrudableGeometry extends KmlAltitudeGeometry { + + /** + * Specifies whether to connect the geometry to the ground. + */ + getExtrude(): boolean; + + /** + * Specifies whether to connect the geometry to the ground. + */ + setExtrude(extrude: boolean): void; + + /** + * Specifies whether to allow the geometry to follow the terrain elevation. + */ + getTessellate(): boolean; + + /** + * Specifies whether to allow the geometry to follow the terrain elevation. + */ + setTessellate(tessellate: boolean): void; + } + + /** + * A Polygon is defined by an outer boundary and 0 or more inner boundaries. + * The boundaries, in turn, are defined by LinearRings. + * When a Polygon is extruded, its boundaries are connected to the ground to form additional polygons, which gives the appearance of a building or a box. + * Extruded Polygons use PolyStyle for their color, color mode, and fill. + */ + export class KmlPolygon extends KmlExtrudableGeometry { + + /** + * Contains a LinearRing element. + */ + getOuterBoundary(): KmlLinearRing; + + /** + * Contains a LinearRing element. + */ + setOuterBoundary(outerBoundary: KmlLinearRing): void; + + /** + * Contains a LinearRing element. + * You can specify multiple innerBoundary properties, which create multiple cut-outs inside the Polygon. + */ + getInnerBoundaries(): GELinearRingContainer; + } + + /** + * A geographic location defined by longitude, latitude, and (optional) altitude. + * When a Point is contained by a Placemark, the point itself determines the position of the Placemark's name and icon. + * When a Point is extruded, it is connected to the ground with a line. This tether uses the current LineStyle. + */ + export class KmlPoint extends KmlExtrudableGeometry { + + /** + * Sets altitudeMode, extrude, tessellate, latitude, longitude, and altitude values. + */ + set( + latitude: number, + longitude: number, + altitude: number, + altitudeMode: KmlAltitudeModeEnum, + extrude: boolean, + tessellate: boolean + ): void; + + /** + * Sets the latitude and longitude. + */ + setLatLng(latitude: number, longitude: number): void; + + /** + * Sets the latitude, longitude, and altitide. + */ + setLatLngAlt(latitude: number, longitude: number, altitude: number): void; + + /** + * The point's latitude, in degrees. + */ + getLatitude(): number; + + /** + * The point's latitude, in degrees. + */ + setLatitude(latitude: number): void; + + /** + * The point's longitude, in degrees. + */ + getLongitude(): number; + + /** + * The point's longitude, in degrees. + */ + setLongitude(longitude: number): void; + + /** + * The point's altitude, in meters. + */ + getAltitude(): number; + + /** + * The point's altitude, in meters. + */ + setAltitude(altitude: number): void; + } + + /** + * Defines a connected set of line segments. + * Use KmlLineStyle to specify the color, color mode, and width of the line. + * When a LineString is extruded, the line is extended to the ground, forming a polygon that looks somewhat like a wall or fence. + * For extruded LineStrings, the line itself uses the current LineStyle, and the extrusion uses the current PolyStyle. + */ + export class KmlLineString extends KmlExtrudableGeometry { + + /** + * Two or more coordinate tuples, each consisting of floating point values for longitude, latitude, and altitude. + * The altitude component is optional. + */ + getCoordinates(): KmlCoordArray; + + /** + * Added to the altitude values for all points on the line string. + * Adjusts the altitude of the feature as a whole, without the need to update each coordinate set. + */ + setAltitudeOffset(altitudeOffset: number): void; + + /** + * Returns the altitudeOffset, or 0 if not set. + */ + getAltitudeOffset(): number; + } + + /** + * Defines a closed line string, typically the outer boundary of a Polygon. + * Optionally, a LinearRing can also be used as the inner boundary of a Polygon to create holes in the Polygon. + * A Polygon can contain multiple LinearRing elements used as inner boundaries. + * You do not need to connect the first and last points. + */ + export class KmlLinearRing extends KmlLineString {} + + + /** + * The KmlFeature object is an abstract object and is the base for all feature types (for example Placemarks, Overlays, and NetworkLinks). + */ + export class KmlFeature extends KmlObject { + + /** + * Retrieves the contents of the feature's element. + * The retrieved contents are scrubbed to remove JavaScript; CSS; and iframe, embed, and object tags. + * + * It should be safe to insert the resulting HTML into your page without concern for malicious content embedded in the feature data; + * however any feature depending on CSS or Javascript will not work. + */ + getBalloonHtml(): string; + + /** + * Retrieves the contents of the feature's element. The contents are not scrubbed. + * Use this method only if you trust the source of the feature data. + */ + getBalloonHtmlUnsafe(): string; + + /** + * User-defined text displayed in the plugin as the label for the object (for example, for a Placemark). + */ + getName(): string; + + /** + * User-defined text displayed in the plugin as the label for the object (for example, for a Placemark). + */ + setName(name: string): void; + + /** + * Specifies whether the feature is drawn in the plugin. + * In order for a feature to be visible, the visibility of all its ancestors must also be set to true. + * In the Google Earth List View, each feature has a checkbox that allows the user to control visibility of the feature. + */ + getVisibility(): boolean; + + /** + * Specifies whether the feature is drawn in the plugin. + * In order for a feature to be visible, the visibility of all its ancestors must also be set to true. + * In the Google Earth List View, each feature has a checkbox that allows the user to control visibility of the feature. + */ + setVisibility(visibility: boolean): void; + + /** + * Default state of left panel. + */ + getOpen(): boolean; + + /** + * Default state of left panel. + */ + setOpen(open: boolean): void; + + /** + * Specifies a value representing an unstructured address written as a standard street, city, state address, and/or as a postal code. + */ + getAddress(): string; + + /** + * Specifies a value representing an unstructured address written as a standard street, city, state address, and/or as a postal code. + */ + setAddress(address: string): void; + + /** + * Specifies a short description of the feature. + */ + getSnippet(): string; + + /** + * Specifies a short description of the feature. + */ + setSnippet(snippet: string): void; + + /** + * User-supplied text that appears in the description balloon. + */ + getDescription(): string; + + /** + * User-supplied text that appears in the description balloon. + */ + setDescription(description: string): void; + + /** + * Stores either the lookAt or camera view. + */ + getAbstractView(): KmlAbstractView; + + /** + * Stores either the lookAt or camera view. + */ + setAbstractView(abstractView: KmlAbstractView): void; + + /** + * URI of a Style or StyleMap defined in a Document. + * It refers to a Plug-in intitiated object. + */ + getStyleUrl(): string; + + /** + * URI of a Style or StyleMap defined in a Document. + * It refers to a Plug-in intitiated object. + */ + setStyleUrl(styleUrl: string): void; + + /** + * The style based on the current mode of the Placemark. + */ + getStyleSelector(): KmlStyleSelector; + + /** + * The style based on the current mode of the Placemark. + */ + setStyleSelector(styleSelector: KmlStyleSelector): void; + + /** + * Specifies region objects and their properties. + * A region contains a bounding box (LatLonAltBox) that describes an area of interest defined by geographic coordinates and altitudes. + */ + getRegion(): KmlRegion; + + /** + * Specifies region objects and their properties. + * A region contains a bounding box (LatLonAltBox) that describes an area of interest defined by geographic coordinates and altitudes. + */ + setRegion(region: KmlRegion): void; + + /** + * Returns the KML for a feature. + */ + getKml(): string; + + /** + * Returns previous sibling node within the container. + */ + getPreviousSibling(): KmlFeature; + + /** + * Returns the next sibling node within the container. + */ + getNextSibling(): KmlFeature; + + /** + * Returns the KmlTimeStamp or KmlTimeSpan object associated with this feature. + */ + getTimePrimitive(): KmlTimePrimitive; + + /** + * Attach a KmlTimeStamp or KmlTimeSpan object to this feature. + */ + setTimePrimitive(timePrimitive: KmlTimePrimitive): void; + + /** + * Returns the computed style of a feature, merging any inline styles with styles imported from setHref() or a StyleUrl. + * + * Note: Modifying the returned KmlStyle object is undefined and not recommended. + */ + getComputedStyle(): KmlStyle; + + /** + * Experimental Feature — this is an experimental feature and can change (or even be removed) at any time. + * The opacity of a feature, ranging from 0 (completely transparent) to 1 (complete opaque). + * The opacity of a folder or document will influence the opacity of child features. + * Thus, if a folder has an opacity of 0.5 and a child ground overlay in the folder also has an opacity of 0.5, the overlay will be drawn with an opacity of 0.25. + */ + getOpacity(): number; + + /** + * Experimental Feature — this is an experimental feature and can change (or even be removed) at any time. + * The opacity of a feature, ranging from 0 (completely transparent) to 1 (complete opaque). + * The opacity of a folder or document will influence the opacity of child features. + * Thus, if a folder has an opacity of 0.5 and a child ground overlay in the folder also has an opacity of 0.5, the overlay will be drawn with an opacity of 0.25. + */ + setOpacity(opacity: number): void; + } + + /** + * An abstract object and cannot be used directly. + * A KmlContainer object holds one or more features and allows the creation of nested hierarchies. + */ + export class KmlContainer extends KmlFeature { + + /** + * Get an element by ID. + * This is functionally equivalent to getElementByUrl with an unspecified base URL. + * + * For example: getElementByUrl('#foo'). + * + * Usage is when finding objects created with JavaScript, which have unspecified base URLs. + * The object must be a descendant of the container before it can be found. + */ + getElementById(id: string): KmlObject; + + /** + * Get an element by URL. A URL consists of the base address and ID, joined with the # character. + * + * For example: http://www.google.com/bar.kml#here_be_monsters + * + * This applies to objects that are fetched. + * In the case of plugin created objects, the URL is simply #foo. + * The object must be a descendant of the container before it can be found. + */ + getElementByUrl(url: string): KmlObject; + + /** + * Get an element by type. + */ + getElementsByType(type: string): KmlObjectList; + + /** + * A collection of features, such as name, description, and so on. + */ + getFeatures(): GEFeatureContainer; + } + + /** + * A Folder is used to arrange other features hierarchically (Folders, Placemarks, NetworkLinks, or Overlays). + * A feature is visible only if it and all of its ancestors are visible. + */ + export class KmlFolder extends KmlContainer {} + + /** + * A layer displayed in Google Earth. + */ + export class KmlLayer extends KmlFolder {} + + /** + * A container for the various layers displayed with the Google Earth Plug-in. + * It contains the same layers as Google Earth. + */ + export class KmlLayerRoot extends KmlFolder { + + /** + * Returns the layer based on the layer's ID. + */ + getLayerById(id: string): KmlLayer; + + /** + * Enables a layer based on its ID. + */ + enableLayerById(id: string, visibility: boolean): void; + + /** + * Returns the drawing order for this database. + */ + getDrawOrder(): number; + + /** + * Defines the drawing order for databases. + * Drawing order is lowest to highest. + * Google Earth Enterprise customers can add a side database and set the drawOrder to be either before or after that of the main database. + * Side databases default to a drawing order of 0. + */ + setDrawOrder(drawOrder: number): void; + } + + /** + * A KmlDocument has containers that holds features and styles. + * This container is required if you use shared styles. + * It is recommended that you use shared styles, which require the following. + * + * 1. Define all Styles in a Document. Assign a unique ID to each Style. + * 2. Within a given feature or StyleMap, reference the Style's ID using a styleUrl element. + * + * Note: Shared styles are not inherited by the features in the Document. + */ + export class KmlDocument extends KmlContainer { + + /** + * Returns a list of elements using a particular style URL. + */ + getElementsByStyleUrl(styleUrl: string): KmlObjectList; + + /** + * Returns an array containing the style selectors present in the KML document. + */ + getStyleSelectors(): GEStyleSelectorContainer; + } + + /** + * The KmlPlacemark is a feature with associated Geometry. + */ + export class KmlPlacemark extends KmlFeature { + + /** + * The geometry associated with the placemark. + */ + getGeometry(): KmlGeometry; + + /** + * The geometry associated with the placemark. + */ + setGeometry(geometry: KmlGeometry): void; + } + + /** + * The base class for the three types of balloon windows that can overlay the 3D window. + */ + export class GEAbstractBalloon { + + /** + * The ID of the balloon. + */ + getId(): string; + + /** + * The ID of the balloon. + */ + setId(id: string): void; + + /** + * Determines what the balloon is attached to. + */ + getFeature(): KmlFeature; + + /** + * Determines what the balloon is attached to. + */ + setFeature(feature: KmlFeature): void; + + /** + * Minimum width of the balloon. + */ + getMinWidth(): number; + + /** + * Minimum width of the balloon. + */ + setMinWidth(minWidth: number): void; + + /** + * Minimum height of the balloon. + */ + getMinHeight(): number; + + /** + * Minimum height of the balloon. + */ + setMinHeight(minHeight: number): void; + + /** + * Maximum width of the balloon. + */ + getMaxWidth(): number; + + /** + * Maximum width of the balloon. + */ + setMaxWidth(maxWidth: number): void; + + /** + * Maximum height of the balloon. + */ + getMaxHeight(): number; + + /** + * Maximum height of the balloon. + */ + setMaxHeight(maxHeight: number): void; + + /** + * When true, the balloon frame is displayed with a button that the user + * can click to close the balloon. When false, the balloon frame is just + * a plain frame. + * + * Default is true. + */ + getCloseButtonEnabled(): boolean; + + /** + * When true, the balloon frame is displayed with a button that the user + * can click to close the balloon. When false, the balloon frame is just + * a plain frame. + * + * Default is true. + */ + setCloseButtonEnabled(closeButtonEnabled: boolean): void; + } + + /** + * Base class for GEHtmlStringBalloon and GEHtmlDivBalloon. + */ + export class GEFeatureBalloon extends GEAbstractBalloon {} + + /** + * Creates a balloon that contains HTML. + */ + export class GEHtmlBalloon extends GEAbstractBalloon { + + /** + * The color of the text in the balloon. + * This must be set using the HTML hex format #RRGGBB. + * If not set, it is interpreted as #000000. + */ + getForegroundColor(): string; + + /** + * The color of the text in the balloon. + * This must be set using the HTML hex format #RRGGBB. + * If not set, it is interpreted as #000000. + */ + setForegroundColor(foregroundColor: string): void; + + /** + * The background color of the balloon. + * This must be set using the HTML hex format #RRGGBB. + * If not set, the default is interpreted as #FFFFFF. + */ + getBackgroundColor(): string; + + /** + * The background color of the balloon. + * This must be set using the HTML hex format #RRGGBB. + * If not set, the default is interpreted as #FFFFFF. + */ + setBackgroundColor(backgroundColor: string): void; + } + + /** + * The GEHtmlDivBalloon object creates a balloon based on the contentDiv property. + */ + export class GEHtmlDivBalloon extends GEHtmlBalloon { + + /** + * An HTMLDivElement to be used as the contents of the balloon. + * When the balloon is shown, the HTMLDivElement is attached to the balloon element in the web page. + * You can manipulate this balloon using ordinary HTML DOM techniques. + */ + getContentDiv(): HTMLDivElement; + + /** + * An HTMLDivElement to be used as the contents of the balloon. + * When the balloon is shown, the HTMLDivElement is attached to the balloon element in the web page. + * You can manipulate this balloon using ordinary HTML DOM techniques. + */ + setContentDiv(contentDiv: HTMLElement): void; + } + + /** + * The GEHtmlStringBalloon class represents a balloon based on the contentString. + */ + export class GEHtmlStringBalloon extends GEHtmlBalloon { + + /** + * You can include any HTML using the contentString property. + * When the balloon is visible, the content specified in contentString property, + * is inserted directly into the balloon element in the web page. + */ + getContentString(): string; + + /** + * You can include any HTML using the contentString property. + * When the balloon is visible, the content specified in contentString property, + * is inserted directly into the balloon element in the web page. + */ + setContentString(contentString: string): void; + } + + /** + * The base class for GETimeControl. + */ + export class GEControl {} + + /** + * Represents the time slider object. + */ + export class GETimeControl extends GEControl { + + /** + * Whether the time slider is visible or not. + */ + getVisibility(): GEVisibilityEnum; + + /** + * Specifies whether the control is visible or hidden. + */ + setVisibility(visibility: GEVisibilityEnum): void; + + /** + * Returns the clock rate that the plugin would use, if the play button on the time slider UI was pressed. + * This rate is calculated by the plugin based on the time range currently present in the slider. + */ + getCalculatedRate(): number; + + /** + * Returns a KmlTimeSpan object encompassing the earliest and latest times present in the time slider. + * For more information, refer to the Time chapter of the Developer's Guide. + */ + getExtents(): KmlTimeSpan; + + /** + * Returns an array containing the KmlTimeStamp objects associated with the historical imagery available in this view. + */ + getAvailableImageDates(): KmlObjectList; + + } + + /** + * The GEPlugin is the Google Earth Plugin's main object, and this is the object that is returned to the JavaScript application when you first create a plug-in instance. + * GEPlugin provides factory methods for ructing other objects (placemarks, and so on), and is also used to retrieve the root document objects. + */ + export class GEPlugin { + + /** + * A Specifies that altitudes are at ground level. For Ground overlays, this means that the image will be draped over the terrain. + */ + ALTITUDE_CLAMP_TO_GROUND: KmlAltitudeModeEnum; + + /** + * Specifies that altitudes are to be interpreted as meters above or below ground level (i.e. the elevation of the terrain at the location). + */ + ALTITUDE_RELATIVE_TO_GROUND: KmlAltitudeModeEnum; + + /** + * Specifies that altitudes are to be interpreted as meters above or below sea level, regardless of the actual elevation of the terrain beneath the object. + * For example, if you set the altitude of an object to 10 meters with an absolute altitude mode, the object will appear to be at ground level if the terrain beneath is also 10 meters above sea level. + * If the terrain is 3 meters above sea level, the object will appear elevated above the terrain by 7 meters. + * If, on the other hand, the terrain is 15 meters above sea level, the object may be completely invisible. + */ + ALTITUDE_ABSOLUTE: KmlAltitudeModeEnum; + + /** + * Specifies that altitudes are at sea floor level. + */ + ALTITUDE_CLAMP_TO_SEA_FLOOR: KmlAltitudeModeEnum; + + /** + * Specifies that altitudes are to be interpreted as meters above sea floor (i.e. the elevation of the sea floor at the location). + */ + ALTITUDE_RELATIVE_TO_SEA_FLOOR: KmlAltitudeModeEnum; + + /** + * Refresh when the file is loaded and whenever the Link parameters change. This refresh mode is the default. + */ + REFRESH_ON_CHANGE: KmlRefreshModeEnum; + + /** + * Refresh every n seconds (specified in refreshInterval). + */ + REFRESH_ON_INTERVAL: KmlRefreshModeEnum; + + /** + * Refresh when the expiration time is reached. + * If a fetched file has a NetworkLinkControl, the expires time takes precedence over expiration times specified in HTTP headers. + * If no expires time is specified, the HTTP max-age header is used (if present). + * If max-age is not present, the Expires HTTP header is used (if present). + */ + REFRESH_ON_EXPIRE: KmlRefreshModeEnum; + + /** + * Ignore changes in the view. Also ignore viewFormat parameters, if any. + * This view refresh mode is the default. + */ + VIEW_REFRESH_NEVER: KmlViewRefreshModeEnum; + + /** + * Refresh the file only when the user explicitly requests it. + */ + VIEW_REFRESH_ON_REQUEST: KmlViewRefreshModeEnum; + + /** + * Refresh n seconds after movement stops, where n is specified in viewRefreshTime. + */ + VIEW_REFRESH_ON_STOP: KmlViewRefreshModeEnum; + + /** + * Refresh only when the feature's Region becomes active. + */ + VIEW_REFRESH_ON_REGION: KmlViewRefreshModeEnum; + + /** + * Screen coordinates are to be interpreted as a fraction of an item, like an image or Google Earth window. + */ + UNITS_FRACTION: KmlUnitsEnum; + + /** + * Screen coordinates are to be interpreted as pixels from the left or bottom edge. + */ + UNITS_PIXELS: KmlUnitsEnum; + + /** + * Screen coordinates are to be interpreted as pixels from the top or right edge. + */ + UNITS_INSET_PIXELS: KmlUnitsEnum; + + /** + * Apply no color mode effect, i.e. use the base color as is. + */ + COLOR_NORMAL: KmlColorModeEnum; + + /** + * Apply a random linear scale to the base color. See the KML documentation for more details. + */ + COLOR_RANDOM: KmlColorModeEnum; + + /** + * Inherit the color mode from ancestor styles. + */ + COLOR_INHERIT: KmlColorModeEnum; + + /** + * The Earth map type, used with GEOptions' setMapType. + */ + MAP_TYPE_EARTH: GEMapTypeEnum; + + /** + * The Sky map type, used with GEOptions' setMapType. + */ + MAP_TYPE_SKY: GEMapTypeEnum; + + /** + * Hide the UI element. + */ + VISIBILITY_HIDE: GEVisibilityEnum; + + /** + * Show the UI element always. + */ + VISIBILITY_SHOW: GEVisibilityEnum; + + /** + * Automatically show or hide the UI element depending on user interaction. + */ + VISIBILITY_AUTO: GEVisibilityEnum; + + /** + * Specifies that fly-to should happen immediately, without a smooth transition. + */ + SPEED_TELEPORT: number; + + /** + * The Layer ID of the terrain layer. Use as an argument to getLayerById() or enableLayerById(). + */ + LAYER_TERRAIN: string; + + /** + * The Layer ID of the roads layer. Use as an argument to getLayerById() or enableLayerById(). + */ + LAYER_ROADS: string; + + /** + * The Layer ID of the photorealistic buildings layer. Use as an argument to getLayerById() or enableLayerById(). + */ + LAYER_BUILDINGS: string; + + /** + * The Layer ID of the low resolution (gray) buildings layer. + * Use as an argument to getLayerById() or enableLayerById(). + * Note that as photorealistic buildings continue to be created and added to the LAYER_BUILDINGS layer, the low-resolution version of those buildings will be removed from this layer. + * This layer will therefore change over time. + */ + LAYER_BUILDINGS_LOW_RESOLUTION: string; + + /** + * The Layer ID of the borders layer. Use as an argument to getLayerById() or enableLayerById(). + */ + LAYER_BORDERS: string; + + /** + * The Layer ID of the trees layer. Use as an argument to getLayerById() or enableLayerById(). + */ + LAYER_TREES: string; + + /** + * When using the GEView.hitTest method, this mode samples the globe (the earth's sphere at altitude 0, without terrain or buildings). + */ + HIT_TEST_GLOBE: GEHitTestModeEnum; + + /** + * When using the GEView.hitTest method, this mode samples the earth's terrain (the ground surface, including variations in altitude). + */ + HIT_TEST_TERRAIN: GEHitTestModeEnum; + + /** + * When using the GEView.hitTest method, this mode samples 3D buildings. + */ + HIT_TEST_BUILDINGS: GEHitTestModeEnum; + + /** + * Sets the render state to its default value. Currently, sunlight, Street View, and historical imagery all default to a disabled state. + */ + OPTION_STATE_DEFAULT: GEViewerOptionsValueEnum; + + /** + * Set the render state to on. Passed to the KmlViewerOptions.setOption method. + */ + OPTION_STATE_ENABLED: GEViewerOptionsValueEnum; + + /** + * Set the render state to off. Passed to the KmlViewerOptions.setOption method. + */ + OPTION_STATE_DISABLED: GEViewerOptionsValueEnum; + + /** + * Passed to the KmlViewerOptions.setOption method, along with a GEViewerOptionsValueEnum, to specify whether the Sun option should be visible. + * Sun can also be enabled/disabled with GEPlugin.getSun. + */ + OPTION_SUNLIGHT: GEViewerOptionsTypeEnum; + + /** + * Passed to the KmlViewerOptions.setOption method, along with a GEViewerOptionsValueEnum, to specify whether historical imagery should be enabled. + */ + OPTION_HISTORICAL_IMAGERY: GEViewerOptionsTypeEnum; + + /** + * Passed to the KmlViewerOptions.setOption method, along with a GEViewerOptionsValueEnum, to specify whether Street View should be enabled when the view reaches ground level. + * Note that this applies only to programmatic movement, such as fly-tos; to control whether the user can enter Street View using manual navigation controls, call ge.getPlugin().streetViewEnabled(true). + */ + OPTION_STREET_VIEW: GEViewerOptionsTypeEnum; + + /** + * The feature's visibility is tied to its list item's checkbox state. + */ + LIST_ITEM_CHECK: KmlListItemTypeEnum; + + /** + * When specified for a folder, document or network link, prevents all items from being made visible at once—that is, the user can turn all children off but cannot turn them all on at the same time. + * This setting is useful for containers or network links containing large amounts of data. + */ + LIST_ITEM_CHECK_OFF_ONLY: KmlListItemTypeEnum; + + /** + * Use a normal checkbox for visibility but do not display children in a list view. + * The item's checkbox should allows the user to toggle visibility of the child objects in the viewport. + */ + LIST_ITEM_CHECK_HIDE_CHILDREN: KmlListItemTypeEnum; + + /** + * When specified for a container (a folder or a document), only one of the container's items should be visible at a time. + */ + LIST_ITEM_RADIO_FOLDER: KmlListItemTypeEnum; + + /** + * The large navigation control type, used with GENavigationControl.setControlType(). + */ + NAVIGATION_CONTROL_LARGE: GENavigationControlEnum; + + /** + * The small navigation control type, used with GENavigationControl.setControlType(). + */ + NAVIGATION_CONTROL_SMALL: GENavigationControlEnum; + + /** + * Parse a string of KML and return a handle to the root of the KML object structure that was created. + */ + parseKml(kml: string): KmlObject; + + /** + * Get an element by ID. This is functionally equivalent to getElementByUrl with an unspecified base URL. + * + * For example: getElementByUrl('#foo'). + * + * Usage is when finding objects created with JavaScript, which have unspecified base URLs. + * The object must be a descendant of the DOM before it can be found. + */ + getElementById(id: string): KmlObject; + + /** + * Get an element by URL. A URL consists of the base address and the ID, joined with the # character. + * + * For example: http://www.google.com/bar.kml#here_be_monsters + * + * This applies to objects that are fetched. + * In the case of plugin created objects, the URL is simply #foo. + * The object must be a descendant of the DOM before it can be found. + */ + getElementByUrl(url: string): KmlObject; + + /** + * Get a list of elements by type. + */ + getElementsByType(): KmlObjectList; + + /** + * Creates a placemark on the globe. + * A Placemark is a feature with associated Geometry. + * A Placemark with a Point has an icon associated with it that marks a point on the Earth in the 3D viewer. + * (In the Google Earth 3D viewer, a Point Placemark is the only object you can click or roll over. + * Other Geometry objects do not have an icon in the 3D viewer. + * To allow the user to click in the 3D viewer, you would need to create a MultiGeometry object that contains both a Point and the other Geometry object.) + */ + createPlacemark(id: string): KmlPlacemark; + + /** + * Creates a point on the globe. Specifies the geographic location defined by longitude, latitude, and (optional) altitude. + */ + createPoint(id: string): KmlPoint; + + /** + * Creates a line string on Google Earth. + */ + createLineString(id: string): KmlLineString; + + /** + * Creates a folder. + * A KMLFolder is used to arrange other features hierarchically (Folders, Placemarks, NetworkLinks, or Overlays). + * A feature is visible only if it and all its ancestors are visible. + */ + createFolder(id: string): KmlFolder; + + /** + * Creates level of detail (LOD). + * LOD describes the size of the projected region on the screen that is required in order for the region to be considered active. + * Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent). + */ + createLod(id: string): KmlLod; + + /** + * Creates a LatLonBox, a bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + createLatLonBox(id: string): KmlLatLonBox; + + /** + * Creates a LatLonAltBox, a bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + createLatLonAltBox(id: string): KmlLatLonAltBox; + + /** + * Creates a Document. A Document is a container for features and styles. + */ + createDocument(id: string): KmlDocument; + + /** + * Creates a Region in Google Earth. + * A Region contains a bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + createRegion(id: string): KmlRegion; + + /** + * Specifies the exact coordinates of the Model's origin in latitude, longitude, and altitude. + * Latitude and longitude measurements are standard lat-lon projection with WGS84 datum. + * Altitude is distance above the earth's surface, in meters, and is interpreted according to altitudeMode. + */ + createLocation(id: string): KmlLocation; + + /** + * Sets the rotation of a 3D model's coordinate system to position the object in Google Earth. + */ + createOrientation(id: string): KmlOrientation; + + /** + * Sets the scale of a model along the x, y, and z axes in the model's coordinate space. + */ + createScale(id: string): KmlScale; + + /** + * Creates a model. + * A model is a 3D object described in a COLLADA file. + * COLLADA files have a .dae file extension. + * Models are created in their own coordinate space and then located, positioned, and scaled in Google Earth. + */ + createModel(id: string): KmlModel; + + /** + * A Style defines an addressable style group that can be referenced by StyleMaps and features. + */ + createStyle(id: string): KmlStyle; + + /** + * Creates a LinearRing. + * A LinearRing defines a closed line string, typically the outer boundary of a Polygon. + * Optionally, a LinearRing can also be used as the inner boundary of a Polygon to create holes in the Polygon. + */ + createLinearRing(id: string): KmlLinearRing; + + /** + * Creates a Polygon. A Polygon is defined by an outer boundary and 0 or more inner boundaries. + */ + createPolygon(id: string): KmlPolygon; + + /** + * Creates an Icon. An icon defines an image associated with an Icon style or overlay. + */ + createIcon(id: string): KmlIcon; + + /** + * Creates a Link. + * A Link specifies the location of KML files fetched by network links, image files used in any overlay, or model files used with the Model object. + */ + createLink(id: string): KmlLink; + + /** + * Creates a GroundOverlay. + * A GroundOverlay draws an image overlay draped onto the terrain. + */ + createGroundOverlay(id: string): KmlGroundOverlay; + + /** + * Creates a NetworkLink. + * A NetworkLink references a KML file or KMZ archive on a local or remote network. + */ + createNetworkLink(id: string): KmlNetworkLink; + + /** + * Creates a ScreenOverlay. + * A ScreenOverlay draws an image overlay fixed to the screen. + */ + createScreenOverlay(id: string): KmlScreenOverlay; + + /** + * Creates a container for one or more geometry primitives associated with the same feature. + */ + createMultiGeometry(id: string): KmlMultiGeometry; + + /** + * Creates a StyleMap. + * A StyleMap maps between two different icon styles. + * Typically, a StyleMap is used to provide separate normal and highlighted styles for a Placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. + */ + createStyleMap(id: string): KmlStyleMap; + + /** + * Creates a new LookAt. + * A LookAt element positions the camera view in relation to an object that is being viewed. + */ + createLookAt(id: string): KmlLookAt; + + /** + * Creates a new Camera. + * This element positions the camera relative to the Earth's surface and defines the view direction. + */ + createCamera(id: string): KmlCamera; + + /** + * Creates a new viewer options object. + */ + createViewerOptions(id: string): KmlViewerOptions; + + /** + * Create a KmlTimeStamp object. + * For more information, refer to the Time chapter of the Google Earth API developer's guide. + */ + createTimeStamp(id: string): KmlTimeStamp; + + /** + * Create a KmlTimeSpan object. + * For more information, refer to the Time chapter of the Google Earth API developer's guide. + */ + createTimeSpan(id: string): KmlTimeSpan; + + /** + * Creates a Feature balloon. + */ + createFeatureBalloon(id: string): GEFeatureBalloon; + + /** + * Creates an HTML string balloon. + */ + createHtmlStringBalloon(id: string): GEHtmlStringBalloon; + + /** + * Creates an Html Div Balloon. + */ + createHtmlDivBalloon(id: string): GEHtmlDivBalloon; + + /** + * Returns the currently active balloon, or null. + */ + getBalloon(): GEAbstractBalloon; + + /** + * Sets the given balloon as the active balloon, replacing any existing active balloon. + * If the given feature is visible, then the balloon is displayed. Otherwise, the balloon is hidden. + * + * If the argument is null, then any existing active balloon will be hidden. + */ + setBalloon(newActiveBalloon: GEAbstractBalloon): void; + + /** + * Used for debugging purposes; if this value is not equal to the value returned by getPluginVersion then there is a misconfiguration on the end user's system. + * This check is automatically done during plugin instantiation. + */ + getEarthVersion(): string; + + /** + * The version of the Google Earth Plug-in installed on the end user's machine. + */ + getPluginVersion(): string; + + /** + * The options used to manipulate the behavior of the Google Earth plugin. + */ + getOptions(): GEOptions; + + /** + * The time class used to manipulate the behavior of the Google Earth plugin time. + */ + getTime(): GETime; + + /** + * Controls the window options. + */ + getWindow(): GEWindow; + + /** + * Controls the globe behavior. + */ + getGlobe(): GEGlobe; + + /** + * Displays the dawn to dusk views. + */ + getSun(): GESun; + + /** + * Controls built-in layer behavior. + */ + getLayerRoot(): KmlLayerRoot; + + /** + * Controls the plugin viewport. + */ + getView(): GEView; + + /** + * Controls the navigation controls on the globe. + */ + getNavigationControl(): GENavigationControl; + + /** + * The top-level features currently in the Earth object. + */ + getFeatures(): GEFeatureContainer; + + /** + * Exposes functionality for interacting with KML tours. + */ + getTourPlayer(): GETourPlayer; + + /** + * Exposes functionality for interacting with photo overlays. + */ + getPhotoOverlayViewer(): GEPhotoOverlayViewer; + + /** + * Returns a number between 0 and 100 (inclusive) that indicates the progress of the streaming of imagery for the current view. + * + * A value of 100 means that the imagery is completely streamed in. + */ + getStreamingPercent(): number; + } + +} diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 0c551fd712..97d29bbf04 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -427,7 +427,7 @@ declare namespace google.maps { /** * Marker position. Required. */ - position: LatLng; + position: LatLng|LatLngLiteral; /** Image map region definition used for drag/click. */ shape?: MarkerShape; /** Rollover text. */ diff --git a/graphene-pk11/graphene-pk11-tests.ts b/graphene-pk11/graphene-pk11-tests.ts index 624e0c2f1e..137e05385f 100644 --- a/graphene-pk11/graphene-pk11-tests.ts +++ b/graphene-pk11/graphene-pk11-tests.ts @@ -1,8 +1,6 @@ /// import * as graphene from "graphene-pk11"; - -// Example of Hashing from README.MD let Module = graphene.Module; let lib = "/usr/local/lib/softhsm/libsofthsm2.so"; @@ -13,13 +11,44 @@ mod.initialize(); let slot = mod.getSlots(0); if (slot.flags & graphene.SlotFlag.TOKEN_PRESENT) { let session = slot.open(); + session.login("12345"); - let digest = session.createDigest("sha1"); - digest.update("simple text 1"); - digest.update("simple text 2"); - let hash = digest.final(); + // generate EC key + let keys = session.generateKeyPair(graphene.KeyGenMechanism.ECDSA, { + keyType: graphene.KeyType.ECDSA, + token: false, + derive: true, + paramsECDSA: graphene.NamedCurve.getByName("secp192r1").value + }, { + keyType: graphene.KeyType.ECDSA, + token: false, + derive: true + }); - console.log("Hash SHA1:", hash.toString("hex")); // Hash SHA1: e1dc1e52e9779cd69679b3e0af87d2e288190d34 + // derive algorithm + let alg = { + name: "ECDH1_DERIVE", + params: new graphene.EcdhParams( + graphene.EcKdf.SHA1, + null, + keys.publicKey.getAttribute({ pointEC: null }).pointEC) + }; + + // Template for derived key + let template = { + "class": graphene.ObjectClass.SECRET_KEY, + "token": false, + "keyType": graphene.KeyType.AES, + "valueLen": 256 / 8, + "encrypt": true, + "decrypt": true + }; + + // Key derivation + let dKey = session.deriveKey(alg, keys.privateKey, template); + console.log("Derived key handle:", dKey.handle); + + session.logout(); session.close(); } else { diff --git a/graphene-pk11/graphene-pk11.d.ts b/graphene-pk11/graphene-pk11.d.ts index ce3d162f17..b7d26bf94a 100644 --- a/graphene-pk11/graphene-pk11.d.ts +++ b/graphene-pk11/graphene-pk11.d.ts @@ -1,258 +1,423 @@ -// Type definitions for graphene-pk11 v2.0.2 +// Type definitions for graphene-pk11 v2.0.3 // Project: https://github.com/PeculiarVentures/graphene // Definitions by: Stepan Miroshin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// /// /** * A simple layer for interacting with PKCS #11 / PKCS11 / CryptoKI for Node - * v2.0.2 + * v2.0.3 */ +declare module "graphene-pk11" { -declare module "types/graphene-pk11" { - import * as graphene from "graphene-pk11"; - import * as pkcs11 from "pkcs11js"; + import * as pkcs11 from "pkcs11js" - // ========== Core ========== - - /** - * Handle - */ type Handle = Buffer; - /** - * BaseObject - * - * @interface BaseObject - */ - interface BaseObject { + type CryptoData = string | Buffer; + + class Pkcs11Error extends Error { + code: number; + func: string; + constructor(code: number, func: string); } - /** - * HandleObject - * - * @interface HandleObject - * @extends {BaseObject} - */ - interface HandleObject extends BaseObject { + + class BaseObject { + protected lib: pkcs11.PKCS11; + constructor(lib?: pkcs11.PKCS11); + } + + class HandleObject extends BaseObject { /** * handle to pkcs11 object */ handle: Handle; + + constructor(handle: Handle, lib: pkcs11.PKCS11); + + protected getInfo(): void; } - /** - * Collection - * - * @interface Collection - * @extends {BaseObject} - * @template T - */ - interface Collection extends BaseObject { + class Collection extends BaseObject { + + protected items_: Array; + protected classType: any; /** * returns length of collection */ length: number; + constructor(items: Array, lib: pkcs11.PKCS11, classType: any); + /** * returns item from collection by index * @param {number} index of element in collection `[0..n]` */ items(index: number): T; - - } - type SessionObjectCollection = Collection - type MechanismCollection = Collection; - type SlotCollection = Collection; - - // ========== PKCS11 Objects ========== - - /** - * Certificate objects (object class CKO_CERTIFICATE) hold public-key or attribute certificates - */ - interface Certificate extends Storage { - /** - * Type of certificate - */ - type: graphene.CertificateType; - /** - * The certificate can be trusted for the application that it was created. - */ - trusted: boolean; - /** - * Categorization of the certificate - */ - category: graphene.CertificateCategory; - /** - * Checksum - */ - checkValue: Buffer; - /** - * Start date for the certificate (default empty) - */ - startDate: Date; - /** - * End date for the certificate (default empty) - */ - endDate: Date; } - /** - * X.509 certificate objects (certificate type `CKC_X_509`) hold X.509 public key certificates - */ - interface X509Certificate extends Certificate { + function isString(v: any): boolean; + function isNumber(v: any): boolean; + function isBoolean(v: any): boolean; + function isUndefined(v: any): boolean; + function isNull(v: any): boolean; + function isEmpty(v: any): boolean; + function isFunction(v: any): boolean; + function isObject(v: any): boolean; + function isArray(v: any): boolean; + function isFlag(v: any, fv: number): boolean; + function dateFromString(text: string): Date; + + // ========== Crypto ========== + + class Cipher extends BaseObject { + + session: Session; + + constructor(session: Session, alg: MechanismType, key: Key, lib: pkcs11.PKCS11); + + protected init(alg: MechanismType, key: Key): void; + + update(data: CryptoData): Buffer; + final(): Buffer; + once(data: CryptoData, enc: Buffer): Buffer; + once(data: CryptoData, enc: Buffer, cb: (error: Error, data: Buffer) => void): void; + } + + class Decipher extends BaseObject { + + protected session: Session; + protected blockSize: number; + + constructor(session: Session, alg: MechanismType, key: Key, blockSize: number, lib: pkcs11.PKCS11); + + protected init(alg: MechanismType, key: Key): void; + + update(data: Buffer): Buffer; + final(): Buffer; + once(data: Buffer, dec: Buffer): Buffer; + once(data: Buffer, dec: Buffer, cb: (error: Error, data: Buffer) => void): void; + } + + class Digest extends BaseObject { + + session: Session; + + constructor(session: Session, alg: MechanismType, lib: pkcs11.PKCS11); + + protected init(alg: MechanismType): void; + + update(data: CryptoData): void; + final(): Buffer; + once(data: CryptoData): Buffer; + once(data: CryptoData, cb: (error: Error, data: Buffer) => void): void; + } + + class Sign extends BaseObject { + + session: Session; + + constructor(session: Session, alg: MechanismType, key: Key, lib: pkcs11.PKCS11); + + protected init(alg: MechanismType, key: Key): void; + + update(data: CryptoData): void; + final(): Buffer; + once(data: CryptoData): Buffer; + once(data: CryptoData, cb: (error: Error, data: Buffer) => void): void; + } + + class Verify extends BaseObject { + + session: Session; + + constructor(session: Session, alg: MechanismType, key: Key, lib: pkcs11.PKCS11); + + protected init(alg: MechanismType, key: Key): void; + + update(data: CryptoData): void; + final(signature: Buffer): boolean; + once(data: CryptoData, signature: Buffer): boolean; + once(data: CryptoData, signature: Buffer, cb: (error: Error, valid: boolean) => void): void; + } + + // ========== Keys ========== + + interface IParams { + toCKI(): any; + } + + enum MechParams { + AesCBC, + AesCCM, + AesGCM, + RsaOAEP, + RsaPSS, + EcDH, + } + + // AES + + class AesCbcParams implements IParams, pkcs11.AesCBC { /** - * DER-encoding of the certificate subject name - * - Must be specified when the object is created. - * - Must be non-empty if `CKA_URL` is empty. + * initialization vector + * - must have a fixed size of 16 bytes */ - subject: Buffer; + iv: Buffer; /** - * Key identifier for public/private key pair (default empty) + * the data */ - id: Buffer; + data: Buffer; + type: MechParams; + constructor(iv: Buffer, data?: Buffer); + toCKI(): Buffer; + } + + class AesCcmParams implements IParams { /** - * DER-encoding of the certificate issuer name (default empty) + * length of the data where 0 <= dataLength < 2^8L */ - issuer: Buffer; + dataLength: number; /** - * HEX-encoding of the certificate serial number (default empty) + * the nonce */ - serialNumber: string; + nonce: Buffer; /** - * BER-encoding of the certificate - * - Must be specified when the object is created. - * - Must be non-empty if `CKA_URL` is empty. + * the additional authentication data + * - This data is authenticated but not encrypted */ + aad: Buffer; + /** + * length of authentication tag (output following cipher text) in bits. + * - Can be any value between 0 and 128 + */ + macLength: number; + type: MechParams; + constructor(dataLength: number, nonce: Buffer, aad?: Buffer, macLength?: number); + toCKI(): pkcs11.AesCCM; + } + + class AesGcmParams implements IParams { + /** + * initialization vector + * - The length of the initialization vector can be any number between 1 and 256. + * 96-bit (12 byte) IV values can be processed more efficiently, + * so that length is recommended for situations in which efficiency is critical. + */ + iv: Buffer; + /** + * pointer to additional authentication data. + * This data is authenticated but not encrypted. + */ + aad: Buffer; + /** + * length of authentication tag (output following cipher text) in bits. + * Can be any value between 0 and 128. Default 128 + */ + tagBits: number; + type: MechParams; + constructor(iv: Buffer, aad?: Buffer, tagBits?: number); + toCKI(): pkcs11.AesGCM; + } + + // EC + + interface INamedCurve { + name: string; + oid: string; value: Buffer; - /** - * If not empty this attribute gives the URL where the complete certificate - * can be obtained (default empty) - * - Must be non-empty if `CKA_VALUE` is empty - */ - url: string; - /** - * SHA-1 hash of the subject public key (default empty) - * - Can only be empty if `CKA_URL` is empty. - */ - subjetcKeyIdentifier: Buffer; - /** - * SHA-1 hash of the issuer public key (default empty) - * - Can only be empty if `CKA_URL` is empty. - */ - authorityKeyIdentifier: Buffer; - /** - * Java MIDP security domain - */ - java: graphene.JavaMIDP; + size: number; } - /** - * WTLS certificate objects (certificate type `CKC_WTLS`) hold WTLS public key certificates - */ - interface WtlsCertificate extends Certificate { - /** - * WTLS-encoding (Identifier type) of the certificate subject - * - Must be specified when the object is created. - * - Can only be empty if `CKA_VALUE` is empty. - */ - subject: Buffer; - /** - * WTLS-encoding (Identifier type) of the certificate issuer (default empty) - */ - issuer: Buffer; - /** - * Key identifier for public/private key pair (default empty) - */ - id: Buffer; - /** - * WTLS-encoding of the certificate - * - Must be specified when the object is created. - * - Must be non-empty if `CKA_URL` is empty. - */ - value: Buffer; - /** - * If not empty this attribute gives the URL where the complete certificate - * can be obtained (default empty) - * - Must be non-empty if `CKA_VALUE` is empty - */ - url: string; - /** - * DER-encoding of the certificate serial number (default empty) - */ - serialNumber: Buffer; - /** - * SHA-1 hash of the subject public key (default empty) - * - Can only be empty if `CKA_URL` is empty. - */ - subjetcKeyIdentifier: Buffer; - /** - * SHA-1 hash of the issuer public key (default empty) - * - Can only be empty if `CKA_URL` is empty. - */ - authorityKeyIdentifier: Buffer; + class NamedCurve { + static getByName(name: string): INamedCurve; + static getByOid(oid: string): INamedCurve; } - /** - * X.509 attribute certificate objects (certificate type `CKC_X_509_ATTR_CERT`) hold X.509 attribute certificates - */ - interface AttributeCertificate extends Certificate { - /** - * DER-encoding of the attribute certificate's subject field. - * This is distinct from the `CKA_SUBJECT` attribute contained in `CKC_X_509` certificates - * because the `ASN.1` syntax and encoding are different. - * - Must be specified when the object is created - */ - owner: Buffer; - /** - * DER-encoding of the attribute certificate's issuer field. - * This is distinct from the `CKA_ISSUER` attribute contained in `CKC_X_509` certificates - * because the ASN.1 syntax and encoding are different. (default empty) - */ - issuer: Buffer; - /** - * DER-encoding of the certificate serial number (default empty) - */ - serialNumber: Buffer; - /** - * BER-encoding of a sequence of object identifier values corresponding - * to the attribute types contained in the certificate. - * When present, this field offers an opportunity for applications - * to search for a particular attribute certificate without fetching - * and parsing the certificate itself. (default empty) - */ - types: Buffer; - /** - * BER-encoding of the certificate - * - Must be specified when the object is created. - */ - value: Buffer; + enum EcKdf { + NULL, + SHA1, + SHA224, + SHA256, + SHA384, + SHA512, } - interface DomainParameters extends Storage { + class EcdhParams implements IParams, pkcs11.ECDH1 { /** - * Type of key the domain parameters can be used to generate. + * key derivation function used on the shared secret value */ - keyType: graphene.KeyType; + kdf: EcKdf; /** - * `CK_TRUE` only if domain parameters were either * generated locally (i.e., on the token) - * with a `C_GenerateKey` * created with a `C_CopyObject` call as a copy of domain parameters - * which had its `CKA_LOCAL` attribute set to `CK_TRUE` + * some data shared between the two parties */ - local: boolean; + sharedData: Buffer; + /** + * other party's EC public key value + */ + publicData: Buffer; + type: MechParams; + /** + * Creates an instance of EcdhParams. + * + * @param {EcKdf} kdf key derivation function used on the shared secret value + * @param {Buffer} [sharedData=null] some data shared between the two parties + * @param {Buffer} [publicData=null] other party's EC public key value + */ + constructor(kdf: EcKdf, sharedData?: Buffer, publicData?: Buffer); + toCKI(): pkcs11.ECDH1; + } + + // Rsa + + enum RsaMgf { + MGF1_SHA1, + MGF1_SHA224, + MGF1_SHA256, + MGF1_SHA384, + MGF1_SHA512, + } + + class RsaOaepParams implements IParams { + hashAlgorithm: MechanismEnum; + mgf: RsaMgf; + source: number; + sourceData: Buffer; + type: MechParams; + constructor(hashAlg?: MechanismEnum, mgf?: RsaMgf, sourceData?: Buffer); + toCKI(): pkcs11.RsaOAEP; + } + + class RsaPssParams implements IParams { + /** + * hash algorithm used in the PSS encoding; + * - if the signature mechanism does not include message hashing, + * then this value must be the mechanism used by the application to generate + * the message hash; + * - if the signature mechanism includes hashing, + * then this value must match the hash algorithm indicated + * by the signature mechanism + */ + hashAlgorithm: MechanismEnum; + /** + * mask generation function to use on the encoded block + */ + mgf: RsaMgf; + /** + * length, in bytes, of the salt value used in the PSS encoding; + * - typical values are the length of the message hash and zero + */ + saltLength: number; + type: MechParams; + constructor(hashAlg?: MechanismEnum, mgf?: RsaMgf, saltLen?: number); + toCKI(): pkcs11.RsaPSS; + } + + // ========== Objects ========== + + enum ObjectClass { + DATA, + CERTIFICATE, + PUBLIC_KEY, + PRIVATE_KEY, + SECRET_KEY, + HW_FEATURE, + DOMAIN_PARAMETERS, + MECHANISM, + OTP_KEY, + } + + class SessionObject extends HandleObject { + /** + * Session + */ + session: Session; + /** + * gets the size of an object in bytes + * + * @readonly + * @type {number} + */ + size: number; + class: ObjectClass; + + /** + * Creates an instance of SessionObject. + * + * @param {SessionObject} object + */ + constructor(object: SessionObject); + /** + * Creates an instance of SessionObject. + * + * @param {Handle} handle + * @param {Session} session + * @param {pkcs11.PKCS11} lib + */ + constructor(handle: Handle, session: Session, lib: pkcs11.PKCS11); + constructor(handle: SessionObject); + + /** + * copies an object, creating a new object for the copy + * + * @param {ITemplate} template template for the new object + * @returns {SessionObject} + */ + copy(template: ITemplate): SessionObject; + /** + * destroys an object + */ + destroy(): void; + getAttribute(attr: string): ITemplate; + getAttribute(attrs: ITemplate): ITemplate; + setAttribute(attrs: string, value: any): void; + setAttribute(attrs: ITemplate): void; + get(name: string): any; + set(name: string, value: any): void; + toType(): T; + } + + class SessionObjectCollection extends Collection { + session: Session; + + constructor(items: Array, session: Session, lib: pkcs11.PKCS11, classType?: any); + + items(index: number): SessionObject; + } + + class Storage extends SessionObject { + /** + * `true` if object is a token object; + * `false` if object is a session object. Default is `false`. + */ + token: boolean; + /** + * `true` if object is a private object; + * `false` if object is a public object. + * Default value is token-specific, and may depend on the values of other attributes of the object. + */ + private: boolean; + /** + * `true` if object can be modified. Default is `false` + */ + modifiable: boolean; + /** + * Description of the object (default empty) + */ + label: string; } /** * Data objects (object class `CKO_DATA`) hold information defined by an application. * Other than providing access to it, Cryptoki does not attach any special meaning to a data object * - * @ + * @export * @class Data * @extends {Storage} */ - interface Data extends Storage { + class Data extends Storage { /** * Description of the application that manages the object (default empty) * @@ -273,18 +438,101 @@ declare module "types/graphene-pk11" { value: Buffer; } + class DomainParameters extends Storage { + /** + * Type of key the domain parameters can be used to generate. + */ + keyType: KeyType; + /** + * `CK_TRUE` only if domain parameters were either * generated locally (i.e., on the token) + * with a `C_GenerateKey` * created with a `C_CopyObject` call as a copy of domain parameters + * which had its `CKA_LOCAL` attribute set to `CK_TRUE` + */ + local: boolean; + } + + enum KeyType { + RSA, + DSA, + DH, + ECDSA, + EC, + X9_42_DH, + KEA, + GENERIC_SECRET, + RC2, + RC4, + DES, + DES2, + DES3, + CAST, + CAST3, + CAST5, + CAST128, + RC5, + IDEA, + SKIPJACK, + BATON, + JUNIPER, + CDMF, + AES, + GOSTR3410, + GOSTR3411, + GOST28147, + BLOWFISH, + TWOFISH, + SECURID, + HOTP, + ACTI, + CAMELLIA, + ARIA, + } + enum KeyGenMechanism { + AES, + RSA, + RSA_X9_31, + DSA, + DH_PKCS, + DH_X9_42, + GOSTR3410, + GOST28147, + RC2, + RC4, + DES, + DES2, + SECURID, + ACTI, + CAST, + CAST3, + CAST5, + CAST128, + RC5, + IDEA, + GENERIC_SECRET, + SSL3_PRE_MASTER, + CAMELLIA, + ARIA, + SKIPJACK, + KEA, + BATON, + ECDSA, + EC, + JUNIPER, + TWOFISH, + } + /** * Definition for the base key object class * - defines the object class `CKO_PUBLIC_KEY`, `CKO_PRIVATE_KEY` and `CKO_SECRET_KEY` for type `CK_OBJECT_CLASS` * as used in the `CKA_CLASS` attribute of objects */ - interface Key extends Storage { + class Key extends Storage { /** * Type of key * - Must be specified when object is created with `C_CreateObject` * - Must be specified when object is unwrapped with `C_UnwrapKey` */ - type: graphene.KeyType; + type: KeyType; /** * Key identifier for key (default empty) * - May be modified after object is created with a `C_SetAttributeValue` call, @@ -334,14 +582,14 @@ declare module "types/graphene-pk11" { * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. * - Must not be specified when object is unwrapped with `C_UnwrapKey`. */ - mechanism: graphene.KeyGenMechanism; + mechanism: KeyGenMechanism; allowedMechanisms: void; } /** - * Private key objects (object class `CKO_PRIVATE_KEY`) hold private keys - */ - interface PrivateKey extends Key { + * Private key objects (object class `CKO_PRIVATE_KEY`) hold private keys + */ + class PrivateKey extends Key { /** * DER-encoding of the key subject name (default empty) * - May be modified after object is created with a `C_SetAttributeValue` call, @@ -438,7 +686,7 @@ declare module "types/graphene-pk11" { /** * Public key objects (object class CKO_PUBLIC_KEY) hold public keys */ - interface PublicKey extends Key { + class PublicKey extends Key { /** * DER-encoding of the key subject name (default empty) * - May be modified after object is created with a `C_SetAttributeValue` call, @@ -499,7 +747,7 @@ declare module "types/graphene-pk11" { /** * Secret key objects (object class `CKO_SECRET_KEY`) hold secret keys. */ - interface SecretKey extends Key { + class SecretKey extends Key { /** * `CK_TRUE` if key is sensitive * - May be modified after object is created with a `C_SetAttributeValue` call, @@ -616,136 +864,186 @@ declare module "types/graphene-pk11" { unwrapTemplate: void; } - interface Storage extends SessionObject { - /** - * `true` if object is a token object; - * `false` if object is a session object. Default is `false`. - */ - token: boolean; - /** - * `true` if object is a private object; - * `false` if object is a public object. - * Default value is token-specific, and may depend on the values of other attributes of the object. - */ - private: boolean; - /** - * `true` if object can be modified. Default is `false` - */ - modifiable: boolean; - /** - * Description of the object (default empty) - */ - label: string; + enum CertificateType { + X_509, + X_509_ATTR_CERT, + WTLS, } - interface SessionObject extends HandleObject { - /** - * Session - */ - session: Session; - /** - * gets the size of an object in bytes - * - * @readonly - * @type {number} - */ - size: number; - /** - * copies an object, creating a new object for the copy - * - * @param {ITemplate} template template for the new object - * @returns {SessionObject} - */ - copy(template: ITemplate): SessionObject; - /** - * destroys an object - */ - destroy(): void; - getAttribute(attr: string): ITemplate; - getAttribute(attrs: ITemplate): ITemplate; - setAttribute(attrs: string, value: any): void; - setAttribute(attrs: ITemplate): void; - class: graphene.ObjectClass; - toType(): T; + enum CertificateCategory { + Unspecified, + TokenUser, + Authority, + OtherEntity, } - // ========== Crypto ========== - /** - * Type CryptoData + * Certificate objects (object class CKO_CERTIFICATE) hold public-key or attribute certificates */ - type CryptoData = string | Buffer; + class Certificate extends Storage { + /** + * Type of certificate + */ + type: CertificateType; + /** + * The certificate can be trusted for the application that it was created. + */ + trusted: boolean; + /** + * Categorization of the certificate + */ + category: CertificateCategory; + /** + * Checksum + */ + checkValue: Buffer; + /** + * Start date for the certificate (default empty) + */ + startDate: Date; + /** + * End date for the certificate (default empty) + */ + endDate: Date; + } - interface INamedCurve { - name: string; - oid: string; + /** + * X.509 attribute certificate objects (certificate type `CKC_X_509_ATTR_CERT`) hold X.509 attribute certificates + */ + class AttributeCertificate extends Certificate { + /** + * DER-encoding of the attribute certificate's subject field. + * This is distinct from the `CKA_SUBJECT` attribute contained in `CKC_X_509` certificates + * because the `ASN.1` syntax and encoding are different. + * - Must be specified when the object is created + */ + owner: Buffer; + /** + * DER-encoding of the attribute certificate's issuer field. + * This is distinct from the `CKA_ISSUER` attribute contained in `CKC_X_509` certificates + * because the ASN.1 syntax and encoding are different. (default empty) + */ + issuer: Buffer; + /** + * DER-encoding of the certificate serial number (default empty) + */ + serialNumber: Buffer; + /** + * BER-encoding of a sequence of object identifier values corresponding + * to the attribute types contained in the certificate. + * When present, this field offers an opportunity for applications + * to search for a particular attribute certificate without fetching + * and parsing the certificate itself. (default empty) + */ + types: Buffer; + /** + * BER-encoding of the certificate + * - Must be specified when the object is created. + */ value: Buffer; - size: number; } /** - * Cipher - * - * @interface Cipher - * @extends {BaseObject} + * WTLS certificate objects (certificate type `CKC_WTLS`) hold WTLS public key certificates */ - interface Cipher extends BaseObject { - update(data: CryptoData): Buffer; - final(): Buffer; - once(data: CryptoData, enc: Buffer): Buffer; - once(data: CryptoData, enc: Buffer, cb: (error: Error, data: Buffer) => void): void; + class WtlsCertificate extends Certificate { + /** + * WTLS-encoding (Identifier type) of the certificate subject + * - Must be specified when the object is created. + * - Can only be empty if `CKA_VALUE` is empty. + */ + subject: Buffer; + /** + * WTLS-encoding (Identifier type) of the certificate issuer (default empty) + */ + issuer: Buffer; + /** + * Key identifier for public/private key pair (default empty) + */ + id: Buffer; + /** + * WTLS-encoding of the certificate + * - Must be specified when the object is created. + * - Must be non-empty if `CKA_URL` is empty. + */ + value: Buffer; + /** + * If not empty this attribute gives the URL where the complete certificate + * can be obtained (default empty) + * - Must be non-empty if `CKA_VALUE` is empty + */ + url: string; + /** + * DER-encoding of the certificate serial number (default empty) + */ + serialNumber: Buffer; + /** + * SHA-1 hash of the subject public key (default empty) + * - Can only be empty if `CKA_URL` is empty. + */ + subjetcKeyIdentifier: Buffer; + /** + * SHA-1 hash of the issuer public key (default empty) + * - Can only be empty if `CKA_URL` is empty. + */ + authorityKeyIdentifier: Buffer; + } + + enum JavaMIDP { + Unspecified, + Manufacturer, + Operator, + ThirdParty, } /** - * Decipher - * - * @interface Decipher - * @extends {BaseObject} + * X.509 certificate objects (certificate type `CKC_X_509`) hold X.509 public key certificates */ - interface Decipher extends BaseObject { - update(data: Buffer): Buffer; - final(): Buffer; - once(data: Buffer, dec: Buffer): Buffer; - once(data: Buffer, dec: Buffer, cb: (error: Error, data: Buffer) => void): void; - } - - /** - * Digest - * - * @interface Digest - * @extends {BaseObject} - */ - interface Digest extends BaseObject { - update(data: CryptoData): void; - final(): Buffer; - once(data: CryptoData): Buffer; - once(data: CryptoData, cb: (error: Error, data: Buffer) => void): void; - } - - /** - * Sign - * - * @interface Sign - * @extends {BaseObject} - */ - interface Sign extends BaseObject { - update(data: CryptoData): void; - final(): Buffer; - once(data: CryptoData): Buffer; - once(data: CryptoData, cb: (error: Error, data: Buffer) => void): void; - } - - /** - * Verify - * - * @interface Verify - * @extends {BaseObject} - */ - interface Verify extends BaseObject { - update(data: CryptoData): void; - final(signature: Buffer): boolean; - once(data: CryptoData, signature: Buffer): boolean; - once(data: CryptoData, signature: Buffer, cb: (error: Error, valid: boolean) => void): void; + class X509Certificate extends Certificate { + /** + * DER-encoding of the certificate subject name + * - Must be specified when the object is created. + * - Must be non-empty if `CKA_URL` is empty. + */ + subject: Buffer; + /** + * Key identifier for public/private key pair (default empty) + */ + id: Buffer; + /** + * DER-encoding of the certificate issuer name (default empty) + */ + issuer: Buffer; + /** + * HEX-encoding of the certificate serial number (default empty) + */ + serialNumber: string; + /** + * BER-encoding of the certificate + * - Must be specified when the object is created. + * - Must be non-empty if `CKA_URL` is empty. + */ + value: Buffer; + /** + * If not empty this attribute gives the URL where the complete certificate + * can be obtained (default empty) + * - Must be non-empty if `CKA_VALUE` is empty + */ + url: string; + /** + * SHA-1 hash of the subject public key (default empty) + * - Can only be empty if `CKA_URL` is empty. + */ + subjetcKeyIdentifier: Buffer; + /** + * SHA-1 hash of the issuer public key (default empty) + * - Can only be empty if `CKA_URL` is empty. + */ + authorityKeyIdentifier: Buffer; + /** + * Java MIDP security domain + */ + java: JavaMIDP; } interface IAlgorithm { @@ -753,9 +1051,68 @@ declare module "types/graphene-pk11" { params: Buffer | IParams; } - type MechanismType = graphene.MechanismEnum | graphene.KeyGenMechanism | IAlgorithm | string; + type MechanismType = MechanismEnum | KeyGenMechanism | IAlgorithm | string; + + enum MechanismFlag { + /** + * `True` if the mechanism is performed by the device; `false` if the mechanism is performed in software + */ + HW, + /** + * `True` if the mechanism can be used with encrypt function + */ + ENCRYPT, + /** + * `True` if the mechanism can be used with decrypt function + */ + DECRYPT, + /** + * `True` if the mechanism can be used with digest function + */ + DIGEST, + /** + * `True` if the mechanism can be used with sign function + */ + SIGN, + /** + * `True` if the mechanism can be used with sign recover function + */ + SIGN_RECOVER, + /** + * `True` if the mechanism can be used with verify function + */ + VERIFY, + /** + * `True` if the mechanism can be used with verify recover function + */ + VERIFY_RECOVER, + /** + * `True` if the mechanism can be used with geberate function + */ + GENERATE, + /** + * `True` if the mechanism can be used with generate key pair function + */ + GENERATE_KEY_PAIR, + /** + * `True` if the mechanism can be used with wrap function + */ + WRAP, + /** + * `True` if the mechanism can be used with unwrap function + */ + UNWRAP, + /** + * `True` if the mechanism can be used with derive function + */ + DERIVE, + } + + class Mechanism extends BaseObject { + + protected handle: number; + protected slotHandle: Handle; - interface Mechanism extends BaseObject { /** * the minimum size of the key for the mechanism * _whether this is measured in bits or in bytes is mechanism-dependent_ @@ -774,10 +1131,336 @@ declare module "types/graphene-pk11" { * returns string name from MechanismEnum */ name: string; + + constructor(handle: number, slotHandle: Handle, lib: pkcs11.PKCS11); + + protected getInfo(): void; + + static create(alg: MechanismType): pkcs11.Mechanism; + static vendor(jsonFile: string): void; + static vendor(name: string, value: number): void; } - interface IParams { - toCKI(): any; + class MechanismCollection extends Collection { + + protected slotHandle: Handle; + + constructor(items: Array, slotHandle: Handle, lib: pkcs11.PKCS11, classType?: typeof Mechanism); + /** + * returns item from collection by index + * @param {number} index of element in collection `[0..n]` + */ + items(index: number): Mechanism; + } + + enum MechanismEnum { + RSA_PKCS_KEY_PAIR_GEN, + RSA_PKCS, + RSA_9796, + RSA_X_509, + MD2_RSA_PKCS, + MD5_RSA_PKCS, + SHA1_RSA_PKCS, + RIPEMD128_RSA_PKCS, + RIPEMD160_RSA_PKCS, + RSA_PKCS_OAEP, + RSA_X9_31_KEY_PAIR_GEN, + RSA_X9_31, + SHA1_RSA_X9_31, + RSA_PKCS_PSS, + SHA1_RSA_PKCS_PSS, + DSA_KEY_PAIR_GEN, + DSA, + DSA_SHA1, + DSA_SHA224, + DSA_SHA256, + DSA_SHA384, + DSA_SHA512, + DH_PKCS_KEY_PAIR_GEN, + DH_PKCS_DERIVE, + X9_42_DH_KEY_PAIR_GEN, + X9_42_DH_DERIVE, + X9_42_DH_HYBRID_DERIVE, + X9_42_MQV_DERIVE, + SHA256_RSA_PKCS, + SHA384_RSA_PKCS, + SHA512_RSA_PKCS, + SHA256_RSA_PKCS_PSS, + SHA384_RSA_PKCS_PSS, + SHA512_RSA_PKCS_PSS, + SHA224_RSA_PKCS, + SHA224_RSA_PKCS_PSS, + RC2_KEY_GEN, + RC2_ECB, + RC2_CBC, + RC2_MAC, + RC2_MAC_GENERAL, + RC2_CBC_PAD, + RC4_KEY_GEN, + RC4, + DES_KEY_GEN, + DES_ECB, + DES_CBC, + DES_MAC, + DES_MAC_GENERAL, + DES_CBC_PAD, + DES2_KEY_GEN, + DES3_KEY_GEN, + DES3_ECB, + DES3_CBC, + DES3_MAC, + DES3_MAC_GENERAL, + DES3_CBC_PAD, + CDMF_KEY_GEN, + CDMF_ECB, + CDMF_CBC, + CDMF_MAC, + CDMF_MAC_GENERAL, + CDMF_CBC_PAD, + DES_OFB64, + DES_OFB8, + DES_CFB64, + DES_CFB8, + MD2, + MD2_HMAC, + MD2_HMAC_GENERAL, + MD5, + MD5_HMAC, + MD5_HMAC_GENERAL, + SHA1, + SHA, + SHA_1, + SHA_1_HMAC, + SHA_1_HMAC_GENERAL, + RIPEMD128, + RIPEMD128_HMAC, + RIPEMD128_HMAC_GENERAL, + RIPEMD160, + RIPEMD160_HMAC, + RIPEMD160_HMAC_GENERAL, + SHA256, + SHA256_HMAC, + SHA256_HMAC_GENERAL, + SHA224, + SHA224_HMAC, + SHA224_HMAC_GENERAL, + SHA384, + SHA384_HMAC, + SHA384_HMAC_GENERAL, + SHA512, + SHA512_HMAC, + SHA512_HMAC_GENERAL, + SECURID_KEY_GEN, + SECURID, + HOTP_KEY_GEN, + HOTP, + ACTI, + ACTI_KEY_GEN, + CAST_KEY_GEN, + CAST_ECB, + CAST_CBC, + CAST_MAC, + CAST_MAC_GENERAL, + CAST_CBC_PAD, + CAST3_KEY_GEN, + CAST3_ECB, + CAST3_CBC, + CAST3_MAC, + CAST3_MAC_GENERAL, + CAST3_CBC_PAD, + CAST5_KEY_GEN, + CAST128_KEY_GEN, + CAST5_ECB, + CAST128_ECB, + CAST5_CBC, + CAST128_CBC, + CAST5_MAC, + CAST128_MAC, + CAST5_MAC_GENERAL, + CAST128_MAC_GENERAL, + CAST5_CBC_PAD, + CAST128_CBC_PAD, + RC5_KEY_GEN, + RC5_ECB, + RC5_CBC, + RC5_MAC, + RC5_MAC_GENERAL, + RC5_CBC_PAD, + IDEA_KEY_GEN, + IDEA_ECB, + IDEA_CBC, + IDEA_MAC, + IDEA_MAC_GENERAL, + IDEA_CBC_PAD, + GENERIC_SECRET_KEY_GEN, + CONCATENATE_BASE_AND_KEY, + CONCATENATE_BASE_AND_DATA, + CONCATENATE_DATA_AND_BASE, + XOR_BASE_AND_DATA, + EXTRACT_KEY_FROM_KEY, + SSL3_PRE_MASTER_KEY_GEN, + SSL3_MASTER_KEY_DERIVE, + SSL3_KEY_AND_MAC_DERIVE, + SSL3_MASTER_KEY_DERIVE_DH, + TLS_PRE_MASTER_KEY_GEN, + TLS_MASTER_KEY_DERIVE, + TLS_KEY_AND_MAC_DERIVE, + TLS_MASTER_KEY_DERIVE_DH, + TLS_PRF, + SSL3_MD5_MAC, + SSL3_SHA1_MAC, + MD5_KEY_DERIVATION, + MD2_KEY_DERIVATION, + SHA1_KEY_DERIVATION, + SHA256_KEY_DERIVATION, + SHA384_KEY_DERIVATION, + SHA512_KEY_DERIVATION, + SHA224_KEY_DERIVATION, + PBE_MD2_DES_CBC, + PBE_MD5_DES_CBC, + PBE_MD5_CAST_CBC, + PBE_MD5_CAST3_CBC, + PBE_MD5_CAST5_CBC, + PBE_MD5_CAST128_CBC, + PBE_SHA1_CAST5_CBC, + PBE_SHA1_CAST128_CBC, + PBE_SHA1_RC4_128, + PBE_SHA1_RC4_40, + PBE_SHA1_DES3_EDE_CBC, + PBE_SHA1_DES2_EDE_CBC, + PBE_SHA1_RC2_128_CBC, + PBE_SHA1_RC2_40_CBC, + PKCS5_PBKD2, + PBA_SHA1_WITH_SHA1_HMAC, + WTLS_PRE_MASTER_KEY_GEN, + WTLS_MASTER_KEY_DERIVE, + WTLS_MASTER_KEY_DERIVE_DH_ECC, + WTLS_PRF, + WTLS_SERVER_KEY_AND_MAC_DERIVE, + WTLS_CLIENT_KEY_AND_MAC_DERIVE, + KEY_WRAP_LYNKS, + KEY_WRAP_SET_OAEP, + CAMELLIA_KEY_GEN, + CAMELLIA_ECB, + CAMELLIA_CBC, + CAMELLIA_MAC, + CAMELLIA_MAC_GENERAL, + CAMELLIA_CBC_PAD, + CAMELLIA_ECB_ENCRYPT_DATA, + CAMELLIA_CBC_ENCRYPT_DATA, + CAMELLIA_CTR, + ARIA_KEY_GEN, + ARIA_ECB, + ARIA_CBC, + ARIA_MAC, + ARIA_MAC_GENERAL, + ARIA_CBC_PAD, + ARIA_ECB_ENCRYPT_DATA, + ARIA_CBC_ENCRYPT_DATA, + SKIPJACK_KEY_GEN, + SKIPJACK_ECB64, + SKIPJACK_CBC64, + SKIPJACK_OFB64, + SKIPJACK_CFB64, + SKIPJACK_CFB32, + SKIPJACK_CFB16, + SKIPJACK_CFB8, + SKIPJACK_WRAP, + SKIPJACK_PRIVATE_WRAP, + SKIPJACK_RELAYX, + KEA_KEY_PAIR_GEN, + KEA_KEY_DERIVE, + FORTEZZA_TIMESTAMP, + BATON_KEY_GEN, + BATON_ECB128, + BATON_ECB96, + BATON_CBC128, + BATON_COUNTER, + BATON_SHUFFLE, + BATON_WRAP, + ECDSA_KEY_PAIR_GEN, + EC_KEY_PAIR_GEN, + ECDSA, + ECDSA_SHA1, + ECDSA_SHA224, + ECDSA_SHA256, + ECDSA_SHA384, + ECDSA_SHA512, + ECDH1_DERIVE, + ECDH1_COFACTOR_DERIVE, + ECMQV_DERIVE, + JUNIPER_KEY_GEN, + JUNIPER_ECB128, + JUNIPER_CBC128, + JUNIPER_COUNTER, + JUNIPER_SHUFFLE, + JUNIPER_WRAP, + FASTHASH, + AES_KEY_GEN, + AES_ECB, + AES_CBC, + AES_MAC, + AES_MAC_GENERAL, + AES_CBC_PAD, + AES_CTR, + AES_CMAC, + AES_CMAC_GENERAL, + BLOWFISH_KEY_GEN, + BLOWFISH_CBC, + TWOFISH_KEY_GEN, + TWOFISH_CBC, + AES_GCM, + AES_CCM, + AES_KEY_WRAP, + AES_KEY_WRAP_PAD, + DES_ECB_ENCRYPT_DATA, + DES_CBC_ENCRYPT_DATA, + DES3_ECB_ENCRYPT_DATA, + DES3_CBC_ENCRYPT_DATA, + AES_ECB_ENCRYPT_DATA, + AES_CBC_ENCRYPT_DATA, + GOSTR3410_KEY_PAIR_GEN, + GOSTR3410, + GOSTR3410_WITH_GOSTR3411, + GOSTR3410_KEY_WRAP, + GOSTR3410_DERIVE, + GOSTR3411, + GOSTR3411_HMAC, + GOST28147_KEY_GEN, + GOST28147_ECB, + GOST28147, + GOST28147_MAC, + GOST28147_KEY_WRAP, + DSA_PARAMETER_GEN, + DH_PKCS_PARAMETER_GEN, + X9_42_DH_PARAMETER_GEN, + VENDOR_DEFINED, + } + + enum SessionFlag { + /** + * `True` if the session is read/write; `false` if the session is read-only + */ + RW_SESSION, + /** + * This flag is provided for backward compatibility, and should always be set to `true` + */ + SERIAL_SESSION, + } + + enum UserType { + /** + * Security Officer + */ + SO, + /** + * User + */ + USER, + /** + * Context specific + */ + CONTEXT_SPECIFIC, } interface IKeyPair { @@ -788,11 +1471,13 @@ declare module "types/graphene-pk11" { /** * provides information about a session * - * @ + * @export * @class Session - * @extends {HandleObject} + * @extends {core.HandleObject} */ - interface Session extends HandleObject { + class Session extends HandleObject { + + constructor(handle: Handle, slot: Slot, lib: pkcs11.PKCS11); /** * Slot * @@ -817,6 +1502,9 @@ declare module "types/graphene-pk11" { * @type {number} */ deviceError: number; + + protected getInfo(): void; + /** * closes a session between an application and a token */ @@ -858,7 +1546,7 @@ declare module "types/graphene-pk11" { * but the token may impose subset restrictions * @param {} userType the user type. Default is `USER` */ - login(pin: string, userType?: graphene.UserType): void; + login(pin: string, userType?: UserType): void; /** * logs a user out from a token */ @@ -942,130 +1630,6 @@ declare module "types/graphene-pk11" { generateRandom(size: number): Buffer; } - interface Slot extends HandleObject { - slotDescription: string; - manufacturerID: string; - flags: number; - hardwareVersion: pkcs11.Version; - firmwareVersion: pkcs11.Version; - module: graphene.Module; - /** - * Returns information about token - * - * @returns {Token} - */ - getToken(): Token; - /** - * returns list of `MechanismInfo` - * - * @returns {MechanismCollection} - */ - getMechanisms(): MechanismCollection; - /** - * initializes a token - * - * @param {string} pin the SO's initial PIN - * @returns {string} - */ - initToken(pin: string): string; - /** - * opens a session between an application and a token in a particular slot - * - * @param {SessionFlag} [flags=session.SessionFlag.SERIAL_SESSION] indicates the type of session - * @returns {Session} - */ - open(flags?: graphene.SessionFlag): Session; - /** - * closes all sessions an application has with a token - */ - closeAll(): void; - } - - interface Token extends HandleObject { - /** - * application-defined label, assigned during token initialization. - * - Must be padded with the blank character (' '). - * - Should __not__ be null-terminated. - */ - label: string; - /** - * ID of the device manufacturer. - * - Must be padded with the blank character (' '). - * - Should __not__ be null-terminated. - */ - manufacturerID: string; - /** - * model of the device. - * - Must be padded with the blank character (' '). - * - Should __not__ be null-terminated. - */ - model: string; - /** - * character-string serial number of the device. - * - Must be padded with the blank character (' '). - * - Should __not__ be null-terminated. - */ - serialNumber: string; - /** - * bit flags indicating capabilities and status of the device - */ - flags: number; - /** - * maximum number of sessions that can be opened with the token at one time by a single application - */ - maxSessionCount: number; - /** - * number of sessions that this application currently has open with the token - */ - sessionCount: number; - /** - * maximum number of read/write sessions that can be opened - * with the token at one time by a single application - */ - maxRwSessionCount: number; - /** - * number of read/write sessions that this application currently has open with the token - */ - rwSessionCount: number; - /** - * maximum length in bytes of the PIN - */ - maxPinLen: number; - /** - * minimum length in bytes of the PIN - */ - minPinLen: number; - /** - * the total amount of memory on the token in bytes in which public objects may be stored - */ - totalPublicMemory: number; - /** - * the amount of free (unused) memory on the token in bytes for public objects - */ - freePublicMemory: number; - /** - * the total amount of memory on the token in bytes in which private objects may be stored - */ - totalPrivateMemory: number; - /** - * the amount of free (unused) memory on the token in bytes for private objects - */ - freePrivateMemory: number; - /** - * version number of hardware - */ - hardwareVersion: pkcs11.Version; - /** - * version number of firmware - */ - firmwareVersion: pkcs11.Version; - /** - * current time as a character-string of length 16, - * represented in the format YYYYMMDDhhmmssxx - */ - utcTime: Date; - } - interface ITemplate { /** * CKA_CLASS @@ -1466,683 +2030,9 @@ declare module "types/graphene-pk11" { allowedMechanisms?: any; } -} - -declare module "graphene-pk11" { - import * as graphene from "types/graphene-pk11"; - import * as pkcs11 from "pkcs11js"; - - // ========== Parameters ========== - - // ========== AES ========== - - /** - * Parameter AES CBC - * - * @class AesCbcParams - * @implements {graphene.IParams} - * @implements {pkcs11.AesCBC} - */ - class AesCbcParams implements graphene.IParams, pkcs11.AesCBC { - /** - * initialization vector - * - must have a fixed size of 16 bytes - */ - iv: Buffer; - /** - * the data - */ - data: Buffer; - type: MechParams; - constructor(iv: Buffer, data?: Buffer); - toCKI(): Buffer; - } - - /** - * Parameter AES CCM - * - * @class AesCcmParams - * @implements {graphene.IParams} - */ - class AesCcmParams implements graphene.IParams { - /** - * length of the data where 0 <= dataLength < 2^8L - */ - dataLength: number; - /** - * the nonce - */ - nonce: Buffer; - /** - * the additional authentication data - * - This data is authenticated but not encrypted - */ - aad: Buffer; - /** - * length of authentication tag (output following cipher text) in bits. - * - Can be any value between 0 and 128 - */ - macLength: number; - type: MechParams; - constructor(dataLength: number, nonce: Buffer, aad?: Buffer, macLength?: number); - toCKI(): pkcs11.AesCCM; - } - - /** - * Parameter AES GCM - * - * @class AesGcmParams - * @implements {graphene.IParams} - */ - class AesGcmParams implements graphene.IParams { - /** - * initialization vector - * - The length of the initialization vector can be any number between 1 and 256. - * 96-bit (12 byte) IV values can be processed more efficiently, - * so that length is recommended for situations in which efficiency is critical. - */ - iv: Buffer; - /** - * pointer to additional authentication data. - * This data is authenticated but not encrypted. - */ - aad: Buffer; - /** - * length of authentication tag (output following cipher text) in bits. - * Can be any value between 0 and 128. Default 128 - */ - tagBits: number; - type: MechParams; - constructor(iv: Buffer, aad?: Buffer, tagBits?: number); - toCKI(): pkcs11.AesGCM; - } - - // ========== EC ========== - - /** - * Parameter EC DH - * - * @class EcdhParams - * @implements {graphene.IParams} - * @implements {pkcs11.ECDH1} - */ - class EcdhParams implements graphene.IParams, pkcs11.ECDH1 { - /** - * key derivation function used on the shared secret value - */ - kdf: EcKdf; - /** - * some data shared between the two parties - */ - sharedData: Buffer; - /** - * other party's EC public key value - */ - publicData: Buffer; - type: MechParams; - /** - * Creates an instance of EcdhParams. - * - * @param {EcKdf} kdf key derivation function used on the shared secret value - * @param {Buffer} [sharedData=null] some data shared between the two parties - * @param {Buffer} [publicData=null] other party's EC public key value - */ - constructor(kdf: EcKdf, sharedData?: Buffer, publicData?: Buffer); - toCKI(): pkcs11.ECDH1; - } - - class NamedCurve { - static getByName(name: string): graphene.INamedCurve; - static getByOid(oid: string): graphene.INamedCurve; - } - - /** - * EcKdf is used to indicate the Key Derivation Function (KDF) - * applied to derive keying data from a shared secret. - * The key derivation function will be used by the EC key agreement schemes. - */ - enum EcKdf { - NULL, - SHA1, - SHA224, - SHA256, - SHA384, - SHA512, - } - - // ========== RSA ========== - - /** - * Parameter RSA OAEP - * - * @class RsaOaepParams - * @implements {graphene.IParams} - */ - class RsaOaepParams implements graphene.IParams { - hashAlgorithm: MechanismEnum; - mgf: RsaMgf; - source: number; - sourceData: Buffer; - type: MechParams; - constructor(hashAlg?: MechanismEnum, mgf?: RsaMgf, sourceData?: Buffer); - toCKI(): pkcs11.RsaOAEP; - } - - /** - * Parameter RSA PSS - * - * @class RsaPssParams - * @implements {graphene.IParams} - */ - class RsaPssParams implements graphene.IParams { - /** - * hash algorithm used in the PSS encoding; - * - if the signature mechanism does not include message hashing, - * then this value must be the mechanism used by the application to generate - * the message hash; - * - if the signature mechanism includes hashing, - * then this value must match the hash algorithm indicated - * by the signature mechanism - */ - hashAlgorithm: MechanismEnum; - /** - * mask generation function to use on the encoded block - */ - mgf: RsaMgf; - /** - * length, in bytes, of the salt value used in the PSS encoding; - * - typical values are the length of the message hash and zero - */ - saltLength: number; - type: MechParams; - constructor(hashAlg?: MechanismEnum, mgf?: RsaMgf, saltLen?: number); - toCKI(): pkcs11.RsaPSS; - } - - enum RsaMgf { - MGF1_SHA1, - MGF1_SHA224, - MGF1_SHA256, - MGF1_SHA384, - MGF1_SHA512, - } - - - // ========== Enums ========== - - enum ObjectClass { - DATA, - CERTIFICATE, - PUBLIC_KEY, - PRIVATE_KEY, - SECRET_KEY, - HW_FEATURE, - DOMAIN_PARAMETERS, - MECHANISM, - OTP_KEY, - } - - class Mechanism { - static vendor(jsonFile: string): void; - static vendor(name: string, value: number): void; - } - - enum CertificateType { - X_509, - X_509_ATTR_CERT, - WTLS, - } - - enum CertificateCategory { - Unspecified = 0, - TokenUser = 1, - Authority = 2, - OtherEntity = 3, - } - - enum KeyType { - RSA, - DSA, - DH, - ECDSA, - EC, - X9_42_DH, - KEA, - GENERIC_SECRET, - RC2, - RC4, - DES, - DES2, - DES3, - CAST, - CAST3, - CAST5, - CAST128, - RC5, - IDEA, - SKIPJACK, - BATON, - JUNIPER, - CDMF, - AES, - GOSTR3410, - GOSTR3411, - GOST28147, - BLOWFISH, - TWOFISH, - SECURID, - HOTP, - ACTI, - CAMELLIA, - ARIA, - } - - enum KeyGenMechanism { - AES, - RSA, - RSA_X9_31, - DSA, - DH_PKCS, - DH_X9_42, - GOSTR3410, - GOST28147, - RC2, - RC4, - DES, - DES2, - SECURID, - ACTI, - CAST, - CAST3, - CAST5, - CAST128, - RC5, - IDEA, - GENERIC_SECRET, - SSL3_PRE_MASTER, - CAMELLIA, - ARIA, - SKIPJACK, - KEA, - BATON, - ECDSA, - EC, - JUNIPER, - TWOFISH, - } - - enum MechanismFlag { - /** - * `True` if the mechanism is performed by the device; `false` if the mechanism is performed in software - */ - HW, - /** - * `True` if the mechanism can be used with encrypt function - */ - ENCRYPT, - /** - * `True` if the mechanism can be used with decrypt function - */ - DECRYPT, - /** - * `True` if the mechanism can be used with digest function - */ - DIGEST, - /** - * `True` if the mechanism can be used with sign function - */ - SIGN, - /** - * `True` if the mechanism can be used with sign recover function - */ - SIGN_RECOVER, - /** - * `True` if the mechanism can be used with verify function - */ - VERIFY, - /** - * `True` if the mechanism can be used with verify recover function - */ - VERIFY_RECOVER, - /** - * `True` if the mechanism can be used with geberate function - */ - GENERATE, - /** - * `True` if the mechanism can be used with generate key pair function - */ - GENERATE_KEY_PAIR, - /** - * `True` if the mechanism can be used with wrap function - */ - WRAP, - /** - * `True` if the mechanism can be used with unwrap function - */ - UNWRAP, - /** - * `True` if the mechanism can be used with derive function - */ - DERIVE, - } - - enum MechanismEnum { - RSA_PKCS_KEY_PAIR_GEN, - RSA_PKCS, - RSA_9796, - RSA_X_509, - MD2_RSA_PKCS, - MD5_RSA_PKCS, - SHA1_RSA_PKCS, - RIPEMD128_RSA_PKCS, - RIPEMD160_RSA_PKCS, - RSA_PKCS_OAEP, - RSA_X9_31_KEY_PAIR_GEN, - RSA_X9_31, - SHA1_RSA_X9_31, - RSA_PKCS_PSS, - SHA1_RSA_PKCS_PSS, - DSA_KEY_PAIR_GEN, - DSA, - DSA_SHA1, - DSA_SHA224, - DSA_SHA256, - DSA_SHA384, - DSA_SHA512, - DH_PKCS_KEY_PAIR_GEN, - DH_PKCS_DERIVE, - X9_42_DH_KEY_PAIR_GEN, - X9_42_DH_DERIVE, - X9_42_DH_HYBRID_DERIVE, - X9_42_MQV_DERIVE, - SHA256_RSA_PKCS, - SHA384_RSA_PKCS, - SHA512_RSA_PKCS, - SHA256_RSA_PKCS_PSS, - SHA384_RSA_PKCS_PSS, - SHA512_RSA_PKCS_PSS, - SHA224_RSA_PKCS, - SHA224_RSA_PKCS_PSS, - RC2_KEY_GEN, - RC2_ECB, - RC2_CBC, - RC2_MAC, - RC2_MAC_GENERAL, - RC2_CBC_PAD, - RC4_KEY_GEN, - RC4, - DES_KEY_GEN, - DES_ECB, - DES_CBC, - DES_MAC, - DES_MAC_GENERAL, - DES_CBC_PAD, - DES2_KEY_GEN, - DES3_KEY_GEN, - DES3_ECB, - DES3_CBC, - DES3_MAC, - DES3_MAC_GENERAL, - DES3_CBC_PAD, - CDMF_KEY_GEN, - CDMF_ECB, - CDMF_CBC, - CDMF_MAC, - CDMF_MAC_GENERAL, - CDMF_CBC_PAD, - DES_OFB64, - DES_OFB8, - DES_CFB64, - DES_CFB8, - MD2, - MD2_HMAC, - MD2_HMAC_GENERAL, - MD5, - MD5_HMAC, - MD5_HMAC_GENERAL, - SHA1, - SHA, - SHA_1, - SHA_1_HMAC, - SHA_1_HMAC_GENERAL, - RIPEMD128, - RIPEMD128_HMAC, - RIPEMD128_HMAC_GENERAL, - RIPEMD160, - RIPEMD160_HMAC, - RIPEMD160_HMAC_GENERAL, - SHA256, - SHA256_HMAC, - SHA256_HMAC_GENERAL, - SHA224, - SHA224_HMAC, - SHA224_HMAC_GENERAL, - SHA384, - SHA384_HMAC, - SHA384_HMAC_GENERAL, - SHA512, - SHA512_HMAC, - SHA512_HMAC_GENERAL, - SECURID_KEY_GEN, - SECURID, - HOTP_KEY_GEN, - HOTP, - ACTI, - ACTI_KEY_GEN, - CAST_KEY_GEN, - CAST_ECB, - CAST_CBC, - CAST_MAC, - CAST_MAC_GENERAL, - CAST_CBC_PAD, - CAST3_KEY_GEN, - CAST3_ECB, - CAST3_CBC, - CAST3_MAC, - CAST3_MAC_GENERAL, - CAST3_CBC_PAD, - CAST5_KEY_GEN, - CAST128_KEY_GEN, - CAST5_ECB, - CAST128_ECB, - CAST5_CBC, - CAST128_CBC, - CAST5_MAC, - CAST128_MAC, - CAST5_MAC_GENERAL, - CAST128_MAC_GENERAL, - CAST5_CBC_PAD, - CAST128_CBC_PAD, - RC5_KEY_GEN, - RC5_ECB, - RC5_CBC, - RC5_MAC, - RC5_MAC_GENERAL, - RC5_CBC_PAD, - IDEA_KEY_GEN, - IDEA_ECB, - IDEA_CBC, - IDEA_MAC, - IDEA_MAC_GENERAL, - IDEA_CBC_PAD, - GENERIC_SECRET_KEY_GEN, - CONCATENATE_BASE_AND_KEY, - CONCATENATE_BASE_AND_DATA, - CONCATENATE_DATA_AND_BASE, - XOR_BASE_AND_DATA, - EXTRACT_KEY_FROM_KEY, - SSL3_PRE_MASTER_KEY_GEN, - SSL3_MASTER_KEY_DERIVE, - SSL3_KEY_AND_MAC_DERIVE, - SSL3_MASTER_KEY_DERIVE_DH, - TLS_PRE_MASTER_KEY_GEN, - TLS_MASTER_KEY_DERIVE, - TLS_KEY_AND_MAC_DERIVE, - TLS_MASTER_KEY_DERIVE_DH, - TLS_PRF, - SSL3_MD5_MAC, - SSL3_SHA1_MAC, - MD5_KEY_DERIVATION, - MD2_KEY_DERIVATION, - SHA1_KEY_DERIVATION, - SHA256_KEY_DERIVATION, - SHA384_KEY_DERIVATION, - SHA512_KEY_DERIVATION, - SHA224_KEY_DERIVATION, - PBE_MD2_DES_CBC, - PBE_MD5_DES_CBC, - PBE_MD5_CAST_CBC, - PBE_MD5_CAST3_CBC, - PBE_MD5_CAST5_CBC, - PBE_MD5_CAST128_CBC, - PBE_SHA1_CAST5_CBC, - PBE_SHA1_CAST128_CBC, - PBE_SHA1_RC4_128, - PBE_SHA1_RC4_40, - PBE_SHA1_DES3_EDE_CBC, - PBE_SHA1_DES2_EDE_CBC, - PBE_SHA1_RC2_128_CBC, - PBE_SHA1_RC2_40_CBC, - PKCS5_PBKD2, - PBA_SHA1_WITH_SHA1_HMAC, - WTLS_PRE_MASTER_KEY_GEN, - WTLS_MASTER_KEY_DERIVE, - WTLS_MASTER_KEY_DERIVE_DH_ECC, - WTLS_PRF, - WTLS_SERVER_KEY_AND_MAC_DERIVE, - WTLS_CLIENT_KEY_AND_MAC_DERIVE, - KEY_WRAP_LYNKS, - KEY_WRAP_SET_OAEP, - CAMELLIA_KEY_GEN, - CAMELLIA_ECB, - CAMELLIA_CBC, - CAMELLIA_MAC, - CAMELLIA_MAC_GENERAL, - CAMELLIA_CBC_PAD, - CAMELLIA_ECB_ENCRYPT_DATA, - CAMELLIA_CBC_ENCRYPT_DATA, - CAMELLIA_CTR, - ARIA_KEY_GEN, - ARIA_ECB, - ARIA_CBC, - ARIA_MAC, - ARIA_MAC_GENERAL, - ARIA_CBC_PAD, - ARIA_ECB_ENCRYPT_DATA, - ARIA_CBC_ENCRYPT_DATA, - SKIPJACK_KEY_GEN, - SKIPJACK_ECB64, - SKIPJACK_CBC64, - SKIPJACK_OFB64, - SKIPJACK_CFB64, - SKIPJACK_CFB32, - SKIPJACK_CFB16, - SKIPJACK_CFB8, - SKIPJACK_WRAP, - SKIPJACK_PRIVATE_WRAP, - SKIPJACK_RELAYX, - KEA_KEY_PAIR_GEN, - KEA_KEY_DERIVE, - FORTEZZA_TIMESTAMP, - BATON_KEY_GEN, - BATON_ECB128, - BATON_ECB96, - BATON_CBC128, - BATON_COUNTER, - BATON_SHUFFLE, - BATON_WRAP, - ECDSA_KEY_PAIR_GEN, - EC_KEY_PAIR_GEN, - ECDSA, - ECDSA_SHA1, - ECDSA_SHA224, - ECDSA_SHA256, - ECDSA_SHA384, - ECDSA_SHA512, - ECDH1_DERIVE, - ECDH1_COFACTOR_DERIVE, - ECMQV_DERIVE, - JUNIPER_KEY_GEN, - JUNIPER_ECB128, - JUNIPER_CBC128, - JUNIPER_COUNTER, - JUNIPER_SHUFFLE, - JUNIPER_WRAP, - FASTHASH, - AES_KEY_GEN, - AES_ECB, - AES_CBC, - AES_MAC, - AES_MAC_GENERAL, - AES_CBC_PAD, - AES_CTR, - AES_CMAC, - AES_CMAC_GENERAL, - BLOWFISH_KEY_GEN, - BLOWFISH_CBC, - TWOFISH_KEY_GEN, - TWOFISH_CBC, - AES_GCM, - AES_CCM, - AES_KEY_WRAP, - AES_KEY_WRAP_PAD, - DES_ECB_ENCRYPT_DATA, - DES_CBC_ENCRYPT_DATA, - DES3_ECB_ENCRYPT_DATA, - DES3_CBC_ENCRYPT_DATA, - AES_ECB_ENCRYPT_DATA, - AES_CBC_ENCRYPT_DATA, - GOSTR3410_KEY_PAIR_GEN, - GOSTR3410, - GOSTR3410_WITH_GOSTR3411, - GOSTR3410_KEY_WRAP, - GOSTR3410_DERIVE, - GOSTR3411, - GOSTR3411_HMAC, - GOST28147_KEY_GEN, - GOST28147_ECB, - GOST28147, - GOST28147_MAC, - GOST28147_KEY_WRAP, - DSA_PARAMETER_GEN, - DH_PKCS_PARAMETER_GEN, - X9_42_DH_PARAMETER_GEN, - VENDOR_DEFINED, - } - - enum MechParams { - AesCBC = 1, - AesCCM = 2, - AesGCM = 3, - RsaOAEP = 4, - RsaPSS = 5, - EcDH = 6, - } - - enum SessionFlag { - /** - * `True` if the session is read/write; `false` if the session is read-only - */ - RW_SESSION, - /** - * This flag is provided for backward compatibility, and should always be set to `true` - */ - SERIAL_SESSION - } - - enum UserType { - /** - * Security Officer - */ - SO, - /** - * User - */ - USER, - /** - * Context specific - */ - CONTEXT_SPECIFIC + class Template { + static toPkcs11(tmpl: ITemplate): pkcs11.Attribute[]; + static fromPkcs11(tmpl: pkcs11.Template): ITemplate; } enum SlotFlag { @@ -2157,7 +2047,69 @@ declare module "graphene-pk11" { /** * True if the slot is a hardware slot, as opposed to a software slot implementing a "soft token" */ - HW_SLOT + HW_SLOT, + } + class Slot extends HandleObject { + + slotDescription: string; + manufacturerID: string; + flags: number; + hardwareVersion: pkcs11.Version; + firmwareVersion: pkcs11.Version; + module: Module; + + constructor(handle: Handle, module: Module, lib: pkcs11.PKCS11); + + /** + * Recieve information about Slot + * + * @protected + */ + protected getInfo(): void; + + /** + * Returns information about token + * + * @returns {Token} + */ + getToken(): Token; + /** + * returns list of `MechanismInfo` + * + * @returns {MechanismCollection} + */ + getMechanisms(): MechanismCollection; + /** + * initializes a token + * + * @param {string} pin the SO's initial PIN + * @returns {string} + */ + initToken(pin: string): string; + /** + * opens a session between an application and a token in a particular slot + * + * @param {SessionFlag} [flags=session.SessionFlag.SERIAL_SESSION] indicates the type of session + * @returns {Session} + */ + open(flags?: SessionFlag): Session; + /** + * closes all sessions an application has with a token + */ + closeAll(): void; + } + + /** + * Collection of slots + * + * @export + * @class SlotCollection + * @extends {core.Collection} + */ + class SlotCollection extends Collection { + module: Module; + items(index: number): Slot; + constructor(items: Array, module: Module, lib: pkcs11.PKCS11, classType?: any); } enum TokenFlag { @@ -2178,19 +2130,99 @@ declare module "graphene-pk11" { SO_PIN_COUNT_LOW, SO_PIN_FINAL_TRY, SO_PIN_LOCKED, - SO_PIN_TO_BE_CHANGED + SO_PIN_TO_BE_CHANGED, } - enum JavaMIDP { - Unspecified, - Manufacturer, - Operator, - ThirdParty + class Token extends HandleObject { + /** + * application-defined label, assigned during token initialization. + * - Must be padded with the blank character (' '). + * - Should __not__ be null-terminated. + */ + label: string; + /** + * ID of the device manufacturer. + * - Must be padded with the blank character (' '). + * - Should __not__ be null-terminated. + */ + manufacturerID: string; + /** + * model of the device. + * - Must be padded with the blank character (' '). + * - Should __not__ be null-terminated. + */ + model: string; + /** + * character-string serial number of the device. + * - Must be padded with the blank character (' '). + * - Should __not__ be null-terminated. + */ + serialNumber: string; + /** + * bit flags indicating capabilities and status of the device + */ + flags: number; + /** + * maximum number of sessions that can be opened with the token at one time by a single application + */ + maxSessionCount: number; + /** + * number of sessions that this application currently has open with the token + */ + sessionCount: number; + /** + * maximum number of read/write sessions that can be opened + * with the token at one time by a single application + */ + maxRwSessionCount: number; + /** + * number of read/write sessions that this application currently has open with the token + */ + rwSessionCount: number; + /** + * maximum length in bytes of the PIN + */ + maxPinLen: number; + /** + * minimum length in bytes of the PIN + */ + minPinLen: number; + /** + * the total amount of memory on the token in bytes in which public objects may be stored + */ + totalPublicMemory: number; + /** + * the amount of free (unused) memory on the token in bytes for public objects + */ + freePublicMemory: number; + /** + * the total amount of memory on the token in bytes in which private objects may be stored + */ + totalPrivateMemory: number; + /** + * the amount of free (unused) memory on the token in bytes for private objects + */ + freePrivateMemory: number; + /** + * version number of hardware + */ + hardwareVersion: pkcs11.Version; + /** + * version number of firmware + */ + firmwareVersion: pkcs11.Version; + /** + * current time as a character-string of length 16, + * represented in the format YYYYMMDDhhmmssxx + */ + utcTime: Date; + + constructor(handle: Handle, lib: pkcs11.PKCS11); + + protected getInfo(): void; } - // ========== Module ========== - - class Module implements graphene.BaseObject { + class Module extends BaseObject { libFile: string; libName: string; /** @@ -2213,9 +2245,8 @@ declare module "graphene-pk11" { * version of library */ libraryVersion: pkcs11.Version; - constructor(lib: pkcs11.PKCS11); - + protected getInfo(): void; /** * initializes the Cryptoki library */ @@ -2229,11 +2260,11 @@ declare module "graphene-pk11" { * @param {number} index index of an element in collection * @param {number} tokenPresent only slots with tokens. Default `True` */ - getSlots(index: number, tokenPresent?: boolean): graphene.Slot; + getSlots(index: number, tokenPresent?: boolean): Slot; /** * @param {number} tokenPresent only slots with tokens. Default `True` */ - getSlots(tokenPresent?: boolean): graphene.SlotCollection; + getSlots(tokenPresent?: boolean): SlotCollection; /** * loads pkcs11 lib * @param libFile path to PKCS11 library @@ -2242,4 +2273,5 @@ declare module "graphene-pk11" { static load(libFile: string, libName?: string): Module; } -} \ No newline at end of file + +} \ No newline at end of file diff --git a/graphlib/graphlib-tests.ts b/graphlib/graphlib-tests.ts new file mode 100644 index 0000000000..ff9268ab0f --- /dev/null +++ b/graphlib/graphlib-tests.ts @@ -0,0 +1,24 @@ +/// + +import * as graphlib from 'graphlib'; + +function test_graph() { + var g = new graphlib.Graph(); + g.setEdge('a', 'b'); + g.setEdge('a', 'b', 1.023); + + g.edge('a', 'b'); + g.edge({v: 'a', w: 'b'}); + + graphlib.json.read(graphlib.json.write(g)); + + graphlib.alg.dijkstra(g, 'a', e => g.edge(e)); + graphlib.alg.dijkstraAll(g, e => g.edge(e)); + graphlib.alg.dijkstraAll(g); + + graphlib.alg.findCycles(g); + graphlib.alg.isAcyclic(g); + graphlib.alg.prim(g, e => g.edge(e)); + graphlib.alg.tarjan(g); + graphlib.alg.topsort(g); +} diff --git a/graphlib/graphlib.d.ts b/graphlib/graphlib.d.ts new file mode 100644 index 0000000000..1f017d5383 --- /dev/null +++ b/graphlib/graphlib.d.ts @@ -0,0 +1,291 @@ +// Type definitions for graphlib 2.1.1 +// Project: https://github.com/cpettitt/graphlib +// Definitions by: Dan Vanderkam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare module "graphlib" { + export interface GraphOptions { + directed?: boolean; // default: true. + multigraph?: boolean; // default: false. + compound?: boolean; // default: false. + } + + export interface Edge { + v: string; + w: string; + /** The name that uniquely identifies a multi-edge. */ + name?: string; + } + + // TODO: add template parameters for edge and vertex labels? + export class Graph { + constructor(options?: GraphOptions); + + /** + * Creates or updates the value for the node v in the graph. If label is supplied + * it is set as the value for the node. If label is not supplied and the node was + * created by this call then the default node label will be assigned. Returns the + * graph, allowing this to be chained with other functions. Takes O(1) time. + */ + setNode(name: string, label?: any): Graph; + + hasNode(name: string): boolean; + + /** + * Remove the node with the id v in the graph or do nothing if the node is not in + * the graph. If the node was removed this function also removes any incident + * edges. Returns the graph, allowing this to be chained with other functions. + * Takes O(|E|) time. */ + removeNode(name: string): Graph; + + nodes(): string[]; + + /** Returns the label for this node. */ + node(name: string): any; + + /** + * Creates or updates the label for the edge (v, w) with the optionally supplied + * name. If label is supplied it is set as the value for the edge. If label is not + * supplied and the edge was created by this call then the default edge label will + * be assigned. The name parameter is only useful with multigraphs. Returns the + * graph, allowing this to be chained with other functions. Takes O(1) time. + */ + setEdge(v: string, w: string, label?: any): Graph; + + edges(): Edge[]; + + /** Returns the label for this edge. */ + edge(v: string, w: string): any; + edge(e: Edge): any; + + /** + * Return all edges that point to the node v. Optionally filters those edges down to just those + * coming from node u. Behavior is undefined for undirected graphs - use nodeEdges instead. + * Returns undefined if node v is not in the graph. Takes O(|E|) time. + */ + inEdges(v: string, u?: string): Edge[]; + + /** + * Return all edges that are pointed at by node v. Optionally filters those edges down to just + * those point to w. Behavior is undefined for undirected graphs - use nodeEdges instead. + * Returns undefined if node v is not in the graph. Takes O(|E|) time. + */ + outEdges(v: string, w?: string): Edge[]; + + /** + * Returns all edges to or from node v regardless of direction. Optionally filters those edges + * down to just those between nodes v and w regardless of direction. Returns undefined if node v + * is not in the graph. Takes O(|E|) time. + */ + nodeEdges(v: string, w?: string): Edge[]; + + /** + * Return all nodes that are predecessors of the specified node or undefined if node v is not in + * the graph. Behavior is undefined for undirected graphs - use neighbors instead. Takes O(|V|) + * time. + */ + predecessors(node: string): string[]; + + /** + * Return all nodes that are successors of the specified node or undefined if node v is not in + * the graph. Behavior is undefined for undirected graphs - use neighbors instead. Takes O(|V|) + * time. + */ + successors(node: string): string[]; + + /** + * Return all nodes that are predecessors or successors of the specified node or undefined if + * node v is not in the graph. Takes O(|V|) time. + */ + neighbors(node: string): string[]; + + isDirected(): boolean; + isMultigraph(): boolean; + isCompound(): boolean; + + /** Sets the label for the graph to label. */ + setGraph(label: string): void; + + /** + * Returns the currently assigned label for the graph. If no label has been assigned, + * returns undefined. + */ + graph(): string; + + /** + * Returns the number of nodes in the graph. + */ + nodeCount(): number; + + /** + * Returns the number of edges in the graph. + */ + edgeCount(): number; + + /** Returns those nodes in the graph that have no in-edges. Takes O(|V|) time. */ + sources(): string[]; + + /** Returns those nodes in the graph that have no out-edges. Takes O(|V|) time. */ + sinks(): string[]; + } + + export namespace json { + /** + * Creates a JSONrepresentation of the graph that can be serialized to a string with + * JSON.stringify. The graph can later be restored using json.read. + */ + function write(g: Graph): Object; + + /** + * Takes JSON as input and returns the graph representation. For example, if we have + * serialized the graph in json-write to a string named str, we can restore it to a + * graph as follows: + * + * var g2 = graphlib.json.read(JSON.parse(str)); + * g2.nodes(); + * // ['a', 'b'] + * g2.edges() + * // [ { v: 'a', w: 'b' } ] + */ + function read(json: Object): Graph; + } + + export interface Path { + distance: number; + predecessor: string; + } + + export namespace alg { + /** + * Finds all connected components in a graph and returns an array of these components. + * Each component is itself an array that contains the ids of nodes in the component. + * This function takes O(|V|) time. + */ + function components(g: Graph): string[][]; + + /** + * This function is an implementation of Dijkstra's algorithm which finds the shortest + * path from source to all other nodes in g. This function returns a map of + * v -> { distance, predecessor }. The distance property holds the sum of the weights + * from source to v along the shortest path or Number.POSITIVE_INFINITY if there is no path + * from source. The predecessor property can be used to walk the individual elements of the + * path from source to v in reverse order. + * + * It takes an optional weightFn(e) which returns the weight of the edge e. If no weightFn + * is supplied then each edge is assumed to have a weight of 1. This function throws an + * Error if any of the traversed edges have a negative edge weight. + * + * It takes an optional edgeFn(v) which returns the ids of all edges incident to the node v + * for the purposes of shortest path traversal. By default this function uses the g.outEdges. + * + * It takes O((|E| + |V|) * log |V|) time. + */ + function dijkstra( + graph: Graph, + source: string, + weightFn?: (e: Edge) => number, + edgeFn?: (v: string) => Edge[] + ): {[node: string]: Path}; + + /** + * This function finds the shortest path from each node to every other reachable node in + * the graph. It is similar to alg.dijkstra, but instead of returning a single-source + * array, it returns a mapping of of source -> alg.dijksta(g, source, weightFn, edgeFn). + * + * This function takes an optional weightFn(e) which returns the weight of the edge e. + * If no weightFn is supplied then each edge is assumed to have a weight of 1. This + * function throws an Error if any of the traversed edges have a negative edge weight. + * + * This function takes an optional edgeFn(u) which returns the ids of all edges incident + * to the node u for the purposes of shortest path traversal. By default this function + * uses g.outEdges. + * + * This function takes O(|V| * (|E| + |V|) * log |V|) time. + */ + function dijkstraAll( + graph: Graph, + weightFn?: (e: Edge) => number, + edgeFn?: (v: string) => Edge[] + ): {[source: string]: {[node: string]: Path}}; + + /** + * Given a Graph, g, this function returns all nodes that are part of a cycle. As there + * may be more than one cycle in a graph this function return an array of these cycles, + * where each cycle is itself represented by an array of ids for each node involved in + * that cycle. + * + * alg.isAcyclic is more efficient if you only need to determine whether a graph has a + * cycle or not. + */ + function findCycles(graph: Graph): string[][]; + + /** + * This function is an implementation of the Floyd-Warshall algorithm, which finds the + * shortest path from each node to every other reachable node in the graph. It is similar + * to alg.dijkstraAll, but it handles negative edge weights and is more efficient for some types + * of graphs. This function returns a map of source -> { target -> { distance, predecessor }. + * The distance property holds the sum of the weights from source to target along the shortest + * path of Number.POSITIVE_INFINITY if there is no path from source. The predecessor property + * can be used to walk the individual elements of the path from source to target in reverse + * order. + * + * This function takes an optional weightFn(e) which returns the weight of the edge e. If no + * weightFunc is supplied then each edge is assumed to have a weight of 1. + * + * This function takes an optional edgeFn(v) which returns the ids of all edges incident to the + * node v for the purposes of shortest path traversal. By default this function uses the + * outEdges function on the supplied graph. + * + * This algorithm takes O(|V|^3) time. + */ + function floydWarshall( + graph: Graph, + weightFn?: (e: Edge) => number, + edgeFn?: (v: string) => Edge[] + ): {[source: string]: {[node: string]: Path}}; + + /** + * Given a Graph, g, this function returns true if the graph has no cycles and returns false if it + * does. This algorithm returns as soon as it detects the first cycle. You can use alg.findCycles + * to get the actual list of cycles in the graph. + */ + function isAcyclic(graph: Graph): boolean; + + /** + * Prim's algorithm takes a connected undirected graph and generates a minimum spanning tree. This + * function returns the minimum spanning tree as an undirected graph. This algorithm is derived + * from the description in "Introduction to Algorithms", Third Edition, Cormen, et al., Pg 634. + * + * This function takes a weightFn(e) which returns the weight of the edge e. It throws an Error if + * the graph is not connected. + * + * This function takes O(|E| log |V|) time. + */ + function prim(graph: Graph, weightFn: (e: Edge) => number): Graph; + + /** + * This function is an implementation of Tarjan's algorithm which finds all strongly connected + * components in the directed graph g. Each strongly connected component is composed of nodes that + * can reach all other nodes in the component via directed edges. A strongly connected component + * can consist of a single node if that node cannot both reach and be reached by any other + * specific node in the graph. Components of more than one node are guaranteed to have at least + * one cycle. + * + * This function returns an array of components. Each component is itself an array that contains + * the ids of all nodes in the component. + */ + function tarjan(graph: Graph): string[][]; + + /** + * An implementation of topological sorting. + * + * Given a Graph g this function returns an array of nodes such that for each edge u -> v, u + * appears before v in the array. If the graph has a cycle it is impossible to generate such a + * list and CycleException is thrown. + * + * Takes O(|V| + |E|) time. + */ + function topsort(graph: Graph): string[]; + } +} diff --git a/gulp-angular-templatecache/gulp-angular-templatecache-tests.ts b/gulp-angular-templatecache/gulp-angular-templatecache-tests.ts new file mode 100644 index 0000000000..fd7a053ce6 --- /dev/null +++ b/gulp-angular-templatecache/gulp-angular-templatecache-tests.ts @@ -0,0 +1,36 @@ +/// +/// + +import * as gulp from 'gulp'; +import * as templateCache from 'gulp-angular-templatecache'; + +gulp.task('templatecache:no-arguments', function () { + return gulp.src('templates/**/*.html') + .pipe(templateCache()) + .pipe(gulp.dest('public')); +}); + +gulp.task('templatecache:with-filename', function () { + return gulp.src('templates/**/*.html') + .pipe(templateCache('templates.js')) + .pipe(gulp.dest('public')); +}); + +gulp.task('templatecache:with-options', function () { + return gulp.src('templates/**/*.html') + .pipe(templateCache({ + filename: 'templates.js', + standalone: true, + module: 'app.templates' + })) + .pipe(gulp.dest('public')); +}); + +gulp.task('templatecache:with-filename-and-options', function () { + return gulp.src('templates/**/*.html') + .pipe(templateCache('templates.js', { + standalone: true, + module: 'app.templates' + })) + .pipe(gulp.dest('public')); +}); \ No newline at end of file diff --git a/gulp-angular-templatecache/gulp-angular-templatecache.d.ts b/gulp-angular-templatecache/gulp-angular-templatecache.d.ts new file mode 100644 index 0000000000..34e52acc36 --- /dev/null +++ b/gulp-angular-templatecache/gulp-angular-templatecache.d.ts @@ -0,0 +1,69 @@ +// Type definitions for gulp-angular-templatecache v2.0.0 +// Project: https://github.com/miickel/gulp-angular-templatecache +// Definitions by: Aman Mahajan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "gulp-angular-templatecache" { + function templatecache(): NodeJS.ReadWriteStream; + function templatecache(filename: string): NodeJS.ReadWriteStream; + function templatecache(options: templatecache.Options): NodeJS.ReadWriteStream; + function templatecache(filename: string, options: templatecache.Options): NodeJS.ReadWriteStream; + + namespace templatecache { + interface Options { + /** + * Name to use when concatenating. + */ + filename?: string; + + /** + * Prefix for template URLs. + */ + root?: string; + + /** + * Name of AngularJS module. + */ + module?: string; + + /** + * Create a new AngularJS module, instead of using an existing. + */ + standalone?: boolean; + + /** + * Override file base path. + */ + base?: string | Function; + + /** + * Wrap the templateCache in a module system. Currently supported systems: RequireJS, Browserify, ES6 and IIFE (Immediately-Invoked Function Expression). + */ + moduleSystem?: string; + + /** + * Transform the generated URL before it's put into $templateCache. + */ + transformUrl?: Function; + + /** + * Override template header. + */ + templateHeader?: string; + + /** + * Override template body. + */ + templateBody?: string; + + /** + * Override template footer. + */ + templateFooter?: string; + } + } + + export = templatecache; +} \ No newline at end of file diff --git a/gulp-rename/gulp-rename-tests.ts b/gulp-rename/gulp-rename-tests.ts index 6b204a36d9..b27f0f5ba9 100644 --- a/gulp-rename/gulp-rename-tests.ts +++ b/gulp-rename/gulp-rename-tests.ts @@ -3,6 +3,9 @@ import gulp = require("gulp"); import rename = require("gulp-rename"); +// Test that new import syntax works +import * as newRename from 'gulp-rename'; + // rename via string gulp.src("./src/main/text/hello.txt") .pipe(rename("main/text/ciao/goodbye.md")) @@ -26,4 +29,4 @@ gulp.src("./src/main/text/hello.txt", { base: process.cwd() }) suffix: "-hola", extname: ".md" })) - .pipe(gulp.dest("./dist")); // ./dist/main/text/ciao/bonjour-aloha-hola.md \ No newline at end of file + .pipe(gulp.dest("./dist")); // ./dist/main/text/ciao/bonjour-aloha-hola.md diff --git a/gulp-rename/gulp-rename.d.ts b/gulp-rename/gulp-rename.d.ts index 11368e9698..4c68aecde7 100644 --- a/gulp-rename/gulp-rename.d.ts +++ b/gulp-rename/gulp-rename.d.ts @@ -20,5 +20,12 @@ declare module "gulp-rename" { function rename(name: string): NodeJS.ReadWriteStream; function rename(callback: (path: ParsedPath) => any): NodeJS.ReadWriteStream; function rename(opts: Options): NodeJS.ReadWriteStream; + + /** + * This is required as per: + * https://github.com/Microsoft/TypeScript/issues/5073 + */ + namespace rename {} + export = rename; -} \ No newline at end of file +} diff --git a/gulp-uglify/gulp-uglify-tests.ts b/gulp-uglify/gulp-uglify-tests.ts index 01cfb06f9e..6a1cf1281d 100644 --- a/gulp-uglify/gulp-uglify-tests.ts +++ b/gulp-uglify/gulp-uglify-tests.ts @@ -14,7 +14,7 @@ gulp.task('compress2', function() { var tsResult = gulp.src('lib/*.ts') .pipe(uglify({ mangle: false, - preserverComments: "some", + preserveComments: "some", compress: false, output: { max_line_len: 300 diff --git a/gulp-uglify/gulp-uglify.d.ts b/gulp-uglify/gulp-uglify.d.ts index 13eda63706..60cd8f11ea 100644 --- a/gulp-uglify/gulp-uglify.d.ts +++ b/gulp-uglify/gulp-uglify.d.ts @@ -32,7 +32,7 @@ declare module "gulp-uglify" { * some - Preserve comments that start with a bang (!) or include a Closure Compiler directive (@preserve, @license, @cc_on) * function - Specify your own comment preservation function. You will be passed the current node and the current comment and are expected to return either true or false. */ - preserverComments?: string|((node: any, comment: UglifyJS.Tokenizer) => boolean); + preserveComments?: string|((node: any, comment: UglifyJS.Tokenizer) => boolean); } } diff --git a/halfred/halfred-tests.ts b/halfred/halfred-tests.ts new file mode 100644 index 0000000000..3aecf39962 --- /dev/null +++ b/halfred/halfred-tests.ts @@ -0,0 +1,13 @@ +/// + +// run test with: $ tsc --noImplicitAny --target es6 --module commonjs halfred-tests.ts +import { parse } from 'halfred'; // require('halfred'); +let resource = parse({foo: "bar", "_links": { "self": { href: "fooo" }}}); +console.log(resource); + +let allLinks = resource.allLinks(); +for (let key in allLinks) { + let link = allLinks[key]; + + console.log(link[0].href); +} diff --git a/halfred/halfred.d.ts b/halfred/halfred.d.ts new file mode 100644 index 0000000000..9c1d571a9d --- /dev/null +++ b/halfred/halfred.d.ts @@ -0,0 +1,247 @@ +// Type definitions for Halfred v1.0.0 +// Project: https://github.com/basti1302/halfred +// Definitions by: David Herges +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare module "halfred" { + + /** + * halfred.parse(object) returns a Resource object. + * + * @see https://github.com/basti1302/halfred#usage + */ + export function parse(object: any): Resource; + + /** @see https://github.com/basti1302/halfred#enabledisable-validation */ + export function enableValidation(flag: boolean): void; + + /** @see https://github.com/basti1302/halfred#enabledisable-validation */ + export function disableValidation(): void; + + /** @see https://github.com/basti1302/halfred#resource-api */ + export interface Resource { + + /** + * Returns an object which has an array for each link that was present in the source object. + * See below why each link is represented as an array. + */ + allLinkArrays(): LinkCollection; + + /** Alias for allLinkArrays() */ + allLinks(): LinkCollection; + + /** + * Returns the array of links for the given key, or null if there are no links for this key. + */ + linkArray(key: string): Link[]; + + /** + * Returns the first element of the array of links for the given key or null if there are no + * links for this key. + */ + link(key: string): Link; + + /** + * Returns an object which has an array for each embedded resource that was present in the + * source object. + * See below why each embedded resource is represented as an array. Each element of any of + * this arrays is in turn a Resource object. + */ + allEmbeddedResourceArrays(): ResourceCollection; + + /** Alias for allEmbeddedResourceArrays() */ + allEmbeddedArrays(): ResourceCollection; + + /** Alias for allEmbeddedResourceArrays() */ + allEmbeddedResources(): ResourceCollection; + + /** + * Returns the array of embedded resources for the given key, or null if there are no embedded + * resources for this key. Each element of this arrays is in turn a Resource object. + */ + embeddedResourceArray(key: string): Resource[]; + + /** Alias for embeddedResourceArray() */ + embeddedArray(key: string): Resource[]; + + /** + * Returns the first element of the array of embedded resources for the given key or null if + * there are no embedded resources for this key. The returend object is a Resource object. + */ + embeddedResource(key: string): Resource; + + /** Alias for embeddedResource(key) */ + embedded(key: string): Resource; + + /** + * Returns the unmodified, original object that was parsed to this resource. This is rather + * uninteresting for the source object you give to the parse method (because you probably + * still have a reference to the source object) but it is a convenient way to get the part of + * the source object that corresponds to an embedded resource. + */ + original(): any; + + /** + * Returns true if the resource has any CURIEs (Compact URIs). + * + * @see http://www.w3.org/TR/2010/NOTE-curie-20101216/ + */ + hasCuries(): boolean; + + /** + * Returns the array of CURIEs. Each object in the array is a link object, which means it + * can be templated etc. See below for the link object API. + */ + curieArray(): Link[]; + + /** + * Returns the curie with the given name, if any. The returned object is a link object, which + * means it can be templated etc. See below for link object API. + */ + curie(name: string): Link; + + /** + * Returns the compact URI for the given full URL, if any + */ + reverseResolveCurie(fullUrl: string): string; + + /** + * Returns all validation issues. Validation issues are only gathered if validation has been + * turned on by calling ``halfred.enableValidation()`` before calling ``halfred.parse``. + */ + validationIssues(): any; + + /** + * Alias for validationIssues() + */ + validation(): any; + + /* + XX ... think we should NOT try to represent these things in TypeScript. + + In addition to the methods mentioned here, resource has all properties of the source object. + This is also true for embedded Resource objects. The non-HAL properties (that is, any + property except _links and _embedded) are copied over to the Resource object. This is always + a shallow copy, so modifying the a non-HAL property in the Resource object might also alter + the source object and vice versa. + + The Resource object also has the properties _links and _embedded but they might differ from + the _links/_embedded properties in the source object (Halfred applies some normalization to + them). These are not intended to be accessed by clients directly, instead, use the provided + methods to work with links and embedded resources. + */ + } + + /** @see https://github.com/basti1302/halfred#links-and-embedded-resources */ + interface ResourceCollection { + [key: string]: Resource[]; + } + + /** @see https://github.com/basti1302/halfred#links-and-embedded-resources */ + interface LinkCollection { + [rel: string]: Link[] + } + + /** + * A Link Object represents a hyperlink from the containing resource to a URI. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5 + */ + interface Link { + + /** + * The "href" property is REQUIRED. + * + * Its value is either a URI [RFC3986] or a URI Template [RFC6570]. + * + * If the value is a URI Template then the Link Object SHOULD have a + * "templated" attribute whose value is true. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.1 + */ + href: string; + + /** + * The "templated" property is OPTIONAL. + * + * Its value is boolean and SHOULD be true when the Link Object's "href" + * property is a URI Template. + * + * Its value SHOULD be considered false if it is undefined or any other + * value than true. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.2 + */ + templated?: boolean; + + /** + * The "type" property is OPTIONAL. + * + * Its value is a string used as a hint to indicate the media type + * expected when dereferencing the target resource. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.3 + */ + type?: string; + + /** + * The "deprecation" property is OPTIONAL. + * + * Its presence indicates that the link is to be deprecated (i.e. + * removed) at a future date. Its value is a URL that SHOULD provide + * further information about the deprecation. + * + * A client SHOULD provide some notification (for example, by logging a + * warning message) whenever it traverses over a link that has this + * property. The notification SHOULD include the deprecation property's + * value so that a client manitainer can easily find information about + * the deprecation. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.4 + */ + deprecation?: string; + + /** + * The "name" property is OPTIONAL. + * + * Its value MAY be used as a secondary key for selecting Link Objects + * which share the same relation type. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.5 + */ + name?: string; + + /** + * The "profile" property is OPTIONAL. + * + * Its value is a string which is a URI that hints about the profile (as + * defined by [I-D.wilde-profile-link]) of the target resource. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.6 + */ + profile?: string; + + /** + * The "title" property is OPTIONAL. + * + * Its value is a string and is intended for labelling the link with a + * human-readable identifier (as defined by [RFC5988]). + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.7 + */ + title?: string; + + /** + * The "hreflang" property is OPTIONAL. + * + * Its value is a string and is intended for indicating the language of + * the target resource (as defined by [RFC5988]). + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.8 + */ + hreflang?: string; + + } + +} diff --git a/hapi/hapi.d.ts b/hapi/hapi.d.ts index 68f6857110..ff5e1d9fe8 100644 --- a/hapi/hapi.d.ts +++ b/hapi/hapi.d.ts @@ -1605,6 +1605,9 @@ declare module "hapi" { addEventListener: any; info: IServerConnectionInfo; } + + type RequestExtPoints = "onRequest" | "onPreResponse" | "onPreAuth" | "onPostAuth" | "onPreHandler" | "onPostHandler" | "onPreResponse"; + type ServerExtPoints = "onPreStart" | "onPostStart" | "onPreStop" | "onPostStop"; /** Server http://hapijs.com/api#server rver object is the main application container. The server manages all incoming connections along with all the facilities provided by the framework. A server can contain more than one connection (e.g. listen to port 80 and 8080). @@ -2039,8 +2042,9 @@ declare module "hapi" { server.route({ method: 'GET', path: '/test', handler: handler }); server.start(); // All requests will get routed to '/test'*/ - ext(event: string, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; - ext(event: string, method: (request: Request, reply: IStrictReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; + ext(event: RequestExtPoints, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; + ext(event: RequestExtPoints, method: (request: Request, reply: IStrictReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; + ext(event: ServerExtPoints, method: (server: Server, next: (err?: any) => void, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; /** server.handler(name, method) Registers a new handler type to be used in routes where: diff --git a/heremaps/heremaps-tests.ts b/heremaps/heremaps-tests.ts new file mode 100644 index 0000000000..3b2e1b5c30 --- /dev/null +++ b/heremaps/heremaps-tests.ts @@ -0,0 +1,82 @@ +// Test file for HERE Maps API for JavaScript Definition file +/// + +/** + * EXAMPLE from the HERE Maps API + * Takes a snapshot of the map. + * + * @param {Element} resultContainer Reference to DOM Element to show the captured map area + * @param {H.Map} map Reference to initialized map object + * @param {H.ui.UI} ui Reference to UI component + */ +function capture(resultContainer: HTMLElement, map: H.Map, ui: H.ui.UI) { + // Capturing area of the map is asynchronous, callback function receives HTML5 canvas + // element with desired map area rendered on it. + // We also pass an H.ui.UI reference in order to see the ScaleBar in the output. + // If dimensions are omitted, whole veiw port will be captured + map.capture((canvas: HTMLCanvasElement) => { + if (canvas) { + resultContainer.innerHTML = ''; + resultContainer.appendChild(canvas); + } else { + // For example when map is in Panorama mode + resultContainer.innerHTML = 'Capturing is not supported'; + } + }, [ui], 50, 50, 500, 200); +} + +/** + * Boilerplate map initialization code starts below: + */ +// Step 1: initialize communication with the platform +var platform = new H.service.Platform({ + app_id: 'DemoAppId01082013GAL', + app_code: 'AJKnXv84fjrb0KIHawS0Tg', + useHTTPS: true, + useCIT: true +}); + +var defaultLayers = platform.createDefaultLayers(); + +var mapContainer = document.getElementById('map'); + +// Step 2: initialize a map +var map = new H.Map(mapContainer, defaultLayers.normal.map, { + // initial center and zoom level of the map + zoom: 16, + // Champs-Elysees + center: {lat: 48.869145, lng: 2.314298} +}); + +// Step 3: make the map interactive +// MapEvents enables the event system +// Behavior implements default interactions for pan/zoom (also on mobile touch environments) +var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map)); + +// Step 4: Create the default UI +var ui = H.ui.UI.createDefault(map, defaultLayers, 'en-US'); + + +// Step 6: Create "Capture" button and place for showing the captured area +var resultContainer = document.getElementById('panel'); + +// Create container for the "Capture" button +var containerNode = document.createElement('div'); +containerNode.setAttribute('style', + 'position:absolute;top:0;left:0;background-color:#fff; padding:10px;'); +containerNode.className = 'btn-group'; + +// Create the "Capture" button +var captureBtn = document.createElement('input'); +captureBtn.value = 'Capture'; +captureBtn.type = 'button'; +captureBtn.className = 'btn btn-sm btn-default'; + +// Add both button and container to the DOM +containerNode.appendChild(captureBtn); +mapContainer.appendChild(containerNode); + +// Step 7: Handle capture button click event +captureBtn.onclick = function() { + capture(resultContainer, map, ui); +}; \ No newline at end of file diff --git a/heremaps/heremaps.d.ts b/heremaps/heremaps.d.ts new file mode 100644 index 0000000000..fe79e55ecf --- /dev/null +++ b/heremaps/heremaps.d.ts @@ -0,0 +1,6045 @@ +// Type definitions for HERE Maps API for JavaScript v3.0.12.4 +// Project: https://developer.here.com/ +// Definitions by: Joshua Efiong +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace H { + /***** Map *****/ + /** + * Map class defines map instance in the application. By creating this object you will initialize a visible map object which is attached to the provided dom element. Map class is an entry point to all operations related to layers, map objects and geo-screen transformations. By specifying options you can initialize map with predefined view. + */ + export class Map extends H.util.EventTarget { + /** + * Constructor + * @param element {Element} - html element into which the map will be rendered + * @param baseLayer {H.map.layer.Layer} - The layer to be used as the base (bottom most) layer. + * @param opt_options {H.Map.Options=} - additional map options + */ + constructor(element: Element, baseLayer: H.map.layer.Layer, opt_options?: H.Map.Options); + + /** + * This method returns the map root html element + * @returns {Element} + */ + getElement(): Element; + + /** + * This method sets the new center on a map. + * @param center {H.geo.IPoint} - requested center to be set + * @param opt_animate {boolean=} - parameter indicates if animated transition should be applied, default is false + * @returns {H.Map} - the instance itself + */ + setCenter(center: H.geo.IPoint, opt_animate?: boolean): H.Map; + + /** + * This method returns currently rendered center of the map. + * @returns {H.geo.Point} + */ + getCenter(): H.geo.Point; + + /** + * This method sets the zoom level on the map. Every zoom level represents different scale i.e map at zoom level 2 is twice as large as the map at zoom level 1. + * @param zoom {number} - requested zoom level + * @param opt_animate {boolean=} - parameter indicates if animated transition should be applied, default is false + * @returns {H.Map} - the instance itself + */ + setZoom(zoom: number, opt_animate?: boolean): H.Map; + + /** + * This method returns currently rendered zoom level. + * @returns {number} + */ + getZoom(): number; + + /** + * This method changes the map zoom while keeping target screen coordinates specified as x,y at the same place where they were before. + * @param zoom {number} - new zoom level + * @param x {number} - map viewport x-axis pixel coordinate + * @param y {number} - map viewport y-axis pixel coordinate + */ + zoomAt(zoom: number, x: number, y: number): void; + + /** + * This method sets the bounding rect to be displayed by the map. Maps display the bounding rect in a way that it fits entirely in the current viewport. + * @param boundingRect {H.geo.Rect} - view bound which should be shown on map + * @param opt_animate {boolean=} - parameter indicates if animated transition should be applied, default is false + * @returns {H.Map} - the instance itself + */ + setViewBounds(boundingRect: H.geo.Rect, opt_animate?: boolean): H.Map; + + /** + * This method returns bounding rect for the current map view. Returned bounding rect defines entire currently viewable area on the screen. + * @returns {H.geo.Rect} + */ + getViewBounds(): H.geo.Rect; + + /** + * Calculates the best CameraModel to show the provided bounding rectangle + * @param rect {H.geo.Rect} - The geographical bounding rectangle to use + * @returns {H.map.ViewModel.CameraData} - The result, represented by the properties zoom (number) and position (geo.Point) + */ + getCameraDataForBounds(rect: H.geo.Rect): H.map.ViewModel.CameraData; + + /** + * This method returns current map viewport. Viewport can be used to modify padding and margin which will reflect the position of the viewport center and the amount of extra data loaded (for margin) + * @returns {H.map.ViewPort} + */ + getViewPort(): H.map.ViewPort; + + /** + * This method returns current view model. View model can be used to modify the current view or camera. H.map.ViewModel + * @returns {H.map.ViewModel} + */ + getViewModel(): H.map.ViewModel; + + /** + * This method returns the map's current layer collection. + * @returns {H.map.DataModel} + */ + getLayers(): H.map.DataModel; + + /** + * This method returns the imprint object for this map. + * @returns {H.map.Imprint} + */ + getImprint(): H.map.Imprint; + + /** + * This method captures desired region of the map and objects on it. Result is returned as an HTML5 Canvas element. Origin of coordinate system for capturing is in the top left corner of the viewport. + * @param callback {function(HTMLCanvasElement=)} - Callback function to call once result of the capturing is ready + * @param opt_capturables {Array=} - Collection of "capturable" element(s) to draw into the resulting canvas + * @param opt_x1 {number=} - The X coordinate of the left edge of the capturing rectangle defaults to 0 + * @param opt_y1 {number=} - The Y coordinate of the top edge of the capturing rectangle defaults to 0 + * @param opt_x2 {number=} - The X coordinate of the right edge of the capturing rectangle defaults to viewport width + * @param opt_y2 {number=} - The Y coordinate of the bottom edge of the capturing rectangle defaults to viewport height + */ + capture(callback?: (canvas: HTMLCanvasElement) => void, opt_capturables?: Array, opt_x1?: number, opt_y1?: number, opt_x2?: number, opt_y2?: number): void; + + /** + * This method sets the rendering engine type for the map. Rendering engine is responsible for displaying i.e tiles and data on the map. + * @param type {H.Map.EngineType} + * @returns {H.Map} - the map itself + */ + setEngineType(type: H.Map.EngineType): H.Map; + + /** + * To persistently store the content of a map layer for a given area and range of zoom levels. It can be used to enable map rendering when no internet connection is established and also to reduce the download traffic for frequently visited map areas. + * @param opt_onprogress {function(H.util.Request)=} - A callback which is invoked every time when the progress state of the returned store request changes. + * @param opt_bounds {H.geo.Rect=} - The area to store, default is the current view bounds + * @param opt_min {number=} - The minimum zoom level to store, default is the current zoom level + * @param opt_max {number=} - The maximum zoom level to store, default is the current zoom level + * @param opt_layer {H.map.layer.BaseTileLayer=} - The layer to store, default is the current base layer + * @returns {H.util.Request} - A handle to the created storage request + */ + storeContent(opt_onprogress?: (req: H.util.Request) => void, opt_bounds?: H.geo.Rect, opt_min?: number, opt_max?: number, opt_layer?: H.map.layer.BaseTileLayer): H.util.Request; + + /** + * To clear the entire stored content + * @param opt_onprogress {function(H.util.Request)=} - A callback which is invoked every time when the progress state of the returned clear request changes + * @returns {H.util.Request} - A handle to the created flush request + */ + clearContent(opt_onprogress?: (req: H.util.Request) => void): H.util.Request; + + /** + * This method adds a layer to the map. + * @param layer {H.map.layer.Layer} - The map layer to be added + * @param opt_idx {number=} - index at which the new layer should be inserted + * @returns {H.Map} - current map instance + */ + addLayer(layer: H.map.layer.Layer, opt_idx?: number): H.Map; + + /** + * This method removes layer from the map. + * @param layer {H.map.layer.Layer} - The map layer to be removed + * @returns {H.Map} - current map instance + */ + removeLayer(layer: H.map.layer.Layer): H.Map; + + /** + * This method will set provided layer as base map. The layer will be inserted as the bottom most layer in the map. + * @param layer {H.map.layer.Layer} - The layer to use as base map + * @returns {H.Map} - the instance itself + */ + setBaseLayer(layer: H.map.layer.Layer): H.Map; + + /** + * To get the current base map layer. + * @returns {?H.map.layer.Layer} + */ + getBaseLayer(): H.map.layer.Layer; + + /** + * Returns the screen coordinates according to the given geographical coordinates. This method returns a screen pixel coordinates for the provided geo point. + * @param geoPoint {H.geo.IPoint} - point on the map + * @returns {?H.math.Point} + */ + geoToScreen(geoPoint: H.geo.IPoint): H.math.Point; + + /** + * Returns the geographical coordinates according to the given screen coordinates. + * @param x {number} - map viewport x-axis pixel coordinate + * @param y {number} - map viewport y-axis pixel coordinate + * @returns {?H.geo.Point} + */ + screenToGeo(x: number, y: number): H.geo.Point; + + /** + * Returns the camera data according to the given screen coordinates. Method converts screen pixel coordinates to correct camera data object + * @param x {number} - map viewport x-axis pixel coordinate + * @param y {number} - map viewport y-axis pixel coordinate + * @returns {H.map.ViewModel.CameraData} + */ + screenToCameraData(x: number, y: number): H.map.ViewModel.CameraData; + + /** + * This method adds an map object to the map. Map object can be a marker or a spatial object like polygon or polyline. + * @param mapObject {!H.map.Object} - The map object to add + * @returns {!H.map.Object} - the added map object + */ + addObject(mapObject: H.map.Object): H.map.Object; + + /** + * This method removes previously added map object from the map. + * @param mapObject {!H.map.Object} - The map object to remove + * @returns {!H.map.Object} - the removed map object + */ + removeObject(mapObject: H.map.Object): H.map.Object; + + /** + * This method retrieves the list of all objects which have been added to the map. + * @returns {Array} - the list of all use objects which are currently on the map. + */ + getObjects(): Array; + + /** + * This method adds an array of objects or an object group to the map. + * @param mapObjects {Array} + * @returns {H.Map} - the map instance + */ + addObjects(mapObjects: Array): H.Map; + + /** + * This method removes an array of object or an object group from the map. + * @param mapObjects {(Array | H.map.Group)} + * @returns {H.Map} - the map instance + */ + removeObjects(mapObjects: (Array | H.map.Group)): H.Map; + + /** + * Returns the top most z-ordered map object found under the specific screen coordinates. Coordinates are viewport pixel coordinates starting from top left corner as (0, 0) point. + * @param x {number} - map viewport x-axis pixel coordinate + * @param y {number} - map viewport y-axis pixel coordinate + * @returns {?H.map.Object} - the encountered top most map object or null if no object found + */ + getObjectAt(x: number, y: number): H.map.Object; + + /** + * Returns a list of map objects in descending z-order found under the specific screen coordinates. Coordinates are viewport pixel coordinates starting from top left corner as (0, 0) point. + * @param x {number} - map viewport x-axis pixel coordinate + * @param y {number} - map viewport y-axis pixel coordinate + * @returns {Array} + */ + getObjectsAt(x: number, y: number): Array; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module Map { + /** + * It defines the number of lower and higher zoom levels, where cached content of the base map is rendered while content of the current zoom level is still loading. Example: if range was set to {lower: 3, higher: 2} and current level is 10 then rendering engine will try to display cached tiles from lower zoom levels 7, 8, 9 and higher levels 11 and 12. + * @property lower {number} - The number of lower zoom levels to take into account, default is 0 + * @property higher {number} - The number of higher zoom levels to take into account, default is 0 + */ + export interface BackgroundRange { + lower: number; + higher: number; + } + + /** + * Types of engines + */ + export enum EngineType { + P2D, + PANORAMA, + } + + /** + * This type defines options which can be used to initialize the map. + * @property center {H.geo.IPoint=} - The initial center of the map, default is {lat:0, lng: 0} + * @property zoom {number=} - The initial zoom level of the map, default is 0 respectively the minimal zoom level of the base map + * @property bounds {H.geo.Rect=} - The view bounds to be displayed on the map. If provided, it takes precedence over center and zoom. and zoom if provided) + * @property layers {Array=} - A list of layers to render on top of the base map + * @property engineType: {H.Map.EngineType=} - The initial engine type to use, default is P2D + * @property pixelRatio {number} - The pixelRatio to use for over-sampling in cases of high-resolution displays, default is 1 + * @property imprint {H.map.Imprint.Options=} - The imprint options or null to suppress the imprint + * @property renderBaseBackground {H.Map.BackgroundRange=} - Object describes how many cached zoom levels should be used as a base map background while base map tiles are loading. Example: {lower: 3, higher: 2} + * @property autoColor {boolean=} - Indicates whether the UI's colors should automatically adjusted to the base layer, default is true. Up to now only the copyright style will be adjusted. See H.map.layer.Layer.Options#dark + * @property margin {number=} - The size in pixel of the supplemental area to render for each side of the map + * @property padding {H.map.ViewPort.Padding=} - The padding in pixels for each side of the map + * @property fixedCenter {boolean=} - Indicates whether the center of the map should remain unchanged if the viewport's size or padding has been changed, default is true + */ + export interface Options { + center?: H.geo.IPoint; + zoom?: number; + bounds?: H.geo.Rect; + layers?: Array; + engineType?: EngineType; + pixelRatio?: number; + imprint?: H.map.Imprint.Options; + renderBaseBackground?: BackgroundRange; + autoColor?: boolean; + margin?: number; + padding?: H.map.ViewPort.Padding; + fixedCenter?: boolean; + } + } + + /***** clustering *****/ + export module clustering { + /** + * This class represents the input data structure for data points to be clustered. + * @property lat {H.geo.Latitude} - The latitude coordinate of the data point's position + * @property lng {H.geo.Longitude} - The longitude coordinate of the data point's position + * @property wt {number} - The weight of the data point + * @property data {*} - Data associated with this data point + */ + export class DataPoint implements H.geo.IPoint { + /** + * Constructor + * @param lat {H.geo.Latitude} - The latitude coordinate of the data point's position + * @param lng {H.geo.Longitude} - The longitude coordinate of the data point's position + * @param opt_weight {number=} - The weight of the data point as a positive number > 0. If not specified it , default is 1. + * @param opt_data {*=} - Optional data, which will be associated with this DataPoint + */ + constructor(lat: H.geo.Latitude, lng: H.geo.Longitude, opt_weight?: number, opt_data?: any); + + lat: H.geo.Latitude; + lng: H.geo.Longitude; + alt: H.geo.Altitude; + ctx: H.geo.AltitudeContext; + wt: number; + data: any; + } + + /** + * This interface describes a cluster of data points, which fulfill the clustering specification (i.e. data points are within the epsilon and there are enough points to form a cluster). + */ + export interface ICluster { + /** + * Returns the maximum zoom level where this cluster doesn't fall apart into sub clusters and/or noise poinst + * @returns {number} + */ + getMaxZoom(): number; + + /** + * Returns the bounding rectangle of this cluster. + * @returns {H.geo.Rect} + */ + getBounds(): H.geo.Rect; + + /** + * Invokes the specified callback for each "entry" of the cluster. That "entry" can be either a cluster which implements H.clustering.ICluster interface or a noise point which implements H.clustering.INoisePoint interface. + * @param callback {function(H.clustering.IResult)} - The callback gets the currently traversed entry as an argument, which is cluster or noise point. + */ + forEachEntry(callback: (result: H.clustering.IResult) => void): void; + + /** + * Invokes the specified callback for each data point which is part of this cluster, even indirectly. + * @param callback {function(H.clustering.INoisePoint)} - The callback gets the currently traversed noise point as argument. + */ + forEachDataPoint(callback: (noise: H.clustering.INoisePoint) => void): void; + + /** + * Returns the geographical position of this cluster result. + * @returns {H.geo.Point} + */ + getPosition(): H.geo.Point; + + /** + * Returns the weight of this cluster result. + * @returns {number} + */ + getWeight(): number; + + /** + * To indicate whether this cluster result is a cluster or noise point + * @returns {boolean} + */ + isCluster(): boolean; + + /** + * Returns the minimum zoom level where this item is not part of another cluster + * @returns {number} + */ + getMinZoom(): number; + } + + /** + * This interface represents a data point which does not belong to a cluster. + */ + export interface INoisePoint { + /** + * This method returns data which coresponds to this noise point. + * @returns {*} + */ + getData(): any; + + /** + * Returns the geographical position of this cluster result. + * @returns {H.geo.Point} + */ + getPosition(): H.geo.Point; + + /** + * Returns the weight of this cluster result. + * @returns {number} + */ + getWeight(): number; + + /** + * To indicate whether this cluster result is a cluster or noise point + * @returns {boolean} + */ + isCluster(): boolean; + + /** + * Returns the minimum zoom level where this item is not part of another cluster + * @returns {number} + */ + getMinZoom(): number; + } + + /** + * This interface represents the result item of a clustering operation. + */ + export interface IResult { + + /** + * Returns the geographical position of this cluster result. + * @returns {H.geo.Point} + */ + getPosition(): H.geo.Point; + + /** + * Returns the weight of this cluster result. + * @returns {number} + */ + getWeight(): number; + + /** + * To indicate whether this cluster result is a cluster or noise point + * @returns {boolean} + */ + isCluster(): boolean; + + /** + * Returns the minimum zoom level where this item is not part of another cluster + * @returns {number} + */ + getMinZoom(): number; + } + + /** + * Interface which specifies the methods a theme must implement. + */ + export interface ITheme { + + /** + * Function returns a cluster presentation as a map object. + * @param cluster {H.clustering.ICluster} + * @returns {H.map.Object} + */ + getClusterPresentation(cluster: H.clustering.ICluster): H.map.Object; + + /** + * Function returns noise point presentation as a map object + * @param noisePoint {H.clustering.INoisePoint} + * @returns {H.map.Object} + */ + getNoisePresentation(noisePoint: H.clustering.INoisePoint): H.map.Object; + } + + /** + * The clustering provider serves clusters and noise point representation for the map depending on the provided data set. Levels for clustering as well as custom cluster representation can be set via Options. + * @property min {number} - Minimum zoom level at which provider can cluster data + * @property max {number} - Maximum zoom level at which provider can cluster data + */ + export class Provider extends H.util.EventTarget { + /** + * Constructor + * @param dataPoints {Array} + * @param opt_options {H.clustering.Provider.Options=} + */ + constructor(dataPoints: Array, opt_options?: H.clustering.Provider.Options); + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} + * @param opt_scope {Object=} + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + + /** + * This method sets new data to the provider + * @param dataPoints {Array} + */ + setDataPoints(dataPoints: Array): void; + + /** + * This method adds a data point to the provider. Beware that this method provokes reclustering of the whole data set. + * @param dataPoint {H.clustering.DataPoint} + */ + addDataPoint(dataPoint: H.clustering.DataPoint): void; + + /** + * This method adds a list of data points to the provider. Beware that this method provokes reclustering of the whole data set. + * @param dataPoints {Array} + */ + addDataPoints(dataPoints: Array): void; + + /** + * This method removes a data point from the provider. Beware that this method provokes reclustering of the whole data set. + * @param dataPoint {H.clustering.DataPoint} + */ + removeDataPoint(dataPoint: H.clustering.DataPoint): void; + + /** + * This method returns current theme used for creating cluster visualization + * @returns {H.clustering.ITheme} + */ + getTheme(): H.clustering.ITheme; + + /** + * This method sets new theme on the provider. Calling this method will change visuals for displayed clusters and noise points. + * @param theme {H.clustering.ITheme} + */ + setTheme(theme: H.clustering.ITheme): void; + + /** + * This method always returns true as we don't have information about visual representation until we have the clustering result and apply the theme. + * @returns {boolean} + */ + providesDomMarkers(): boolean; + + /** + * Returns all DomMarker cluster and noise point representations which intersect with the provided rectangular area. + * @param bounds {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestDomMarkers(bounds: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * This method always returns true as we don't have information about visual representation until we have the clustering result and apply the theme. + * @returns {boolean} + */ + providesMarkers(): boolean; + + /** + * Returns all cluster and noise point markers which intersect with the provided rectangular area. + * @param bounds {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestMarkers(bounds: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * This method always returns true as we don't have information about visual representation until we have the clustering result and apply the theme. + * @returns {boolean} + */ + providesSpatials(): boolean; + + /** + * Returns all polyline, polygon, circle and rect objects which represent cluster and noise points and intersect with the provided area. + * @param bounds {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestSpatials(bounds: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Returns the spatial objects which intersect the given tile + * @param tile {H.map.provider.SpatialTile} - The tile for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestSpatialsByTile(tile: H.map.provider.Tile, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Returns the accumulate invalidations of this provider's objects that have occurred. + * @returns {H.map.provider.Invalidations} - an invalidations object + */ + getInvalidations(): H.map.provider.Invalidations; + + /** + * To signal to this provider that a map object has been changed. The method updates the Invalidations of this provider and the given map object and triggers dispatchUpdate() + * @param mapObject {!H.map.Object} - The map object to be invalidated + * @param changes {H.math.BitMask} - The flags indicating the types of occurred changes + */ + invalidateObject(mapObject: H.map.Object, changes: H.math.BitMask): void; + + min: number; + max: number; + } + + export module Provider { + /** + * Options which are used within cluster calculations. + * @property eps {number=} - epsilon parameter for cluster calculation. For the FASTGRID strategy it must not exceed 256 and must take values that are power of 2. For the GRID and DYNAMICGRID strategies it can take values from 10 to 127. Default is 32. + * @property minWeight {number=} - the minimum points weight sum to form a cluster, default is 2 + * @property projection {H.geo.IProjection=} - projection to use for clustering, default is H.geo.mercator + * @property strategy {H.clustering.Provider.Strategy=} - clustering stretegy, defaults to H.clustering.Provider.Strategy.FASTGRID + */ + export interface ClusteringOptions { + eps?: number; + minWeight?: number; + projection?: H.geo.IProjection; + strategy?: H.clustering.Provider.Strategy; + } + + /** + * Options which are used to initialize the clustering Provider + * @property min {number=} - The minimal supported zoom level, default is 0 + * @property max {number=} - The maximal supported zoom level, default is 22 + * @property clusteringOptions {H.clustering.Provider.ClusteringOptions=} - options for clustering algorithm + * @property theme {H.clustering.ITheme=} - cluster and noise point graphical representation + */ + export interface Options { + min?: number; + max?: number; + clusteringOptions?: H.clustering.Provider.ClusteringOptions; + theme?: H.clustering.ITheme; + } + + /** + * Enumeration represents possible clustering strategies. FASTGRID clustering is the efficient way to cluster large sets of data points. GRID clustering is slower but has greater precision due to the bigger range of epsilon values, this strategy suitable for clustering smaller data sets (up to 1000 data points) on desktop devices. DYNAMICGRID clustering uses the same algorithm of clustering as the GRID, but clusters on the viewport basis is meant to be used with data sets that are subject to the frequent update operations. + */ + export enum Strategy { + FASTGRID, + GRID, + DYNAMICGRID, + } + } + } + + /***** data *****/ + export module data { + /** + * An abstract reader class defines interface for data readers and has general functionality related to fetching data and reader events. + */ + export class AbstractReader extends H.util.EventTarget { + /** + * Constructor + * @param opt_url {string=} + */ + constructor(opt_url?: string); + + /** + * Method returns H.map.layer.ObjectLayer that contains parsed data, and can be added directly to the map. It returns new instance of the class with every invocation. If data hasn't been parsed it will return H.map.layer.ObjectLayer that contains partial information, and reader will add new parsed objects to the layer's provider later on. + * @returns {H.map.layer.ObjectLayer} + */ + getLayer(): H.map.layer.ObjectLayer; + + /** + * Method returns collection of currently parsed, and converted to H.map.Object data objects. Method returns only currently parsed objects if parsing is ongoing. + * @returns {Array} + */ + getParsedObjects(): Array; + + /** + * Returns URL of the current file, which is either in process of fetching/parsing or file that has been already parsed. + * @returns {(string | undefined)} - url + */ + getUrl(): string | void; + + /** + * Method sets reader's URL. Method resets current Reader's state to its initial values (clears data about last parsed objects, etc.), and throws InvalidState exception if Reader's state is not READY or ERROR. + * @param url {string} - The new URL + * @returns {H.data.AbstractReader} + */ + setUrl(url: string): H.data.AbstractReader; + + /** + * Returns the reader's processing state for possible states see H.data.AbstractReader.State + * @returns {H.data.AbstractReader.State} + */ + getState(): H.data.AbstractReader.State; + + /** + * Method launches parsing of the data file at the current url (see H.data.AbstractReader#setUrl or H.data.AbstractReader). Method uses XHR as a transport therefore same origin policy applies, or server should respond with proper CORS headers. + */ + parse(): void; + } + + export module AbstractReader { + /** + * The event class for state events that are dispatched by AbstractReader + */ + export class Event extends H.util.Event { + /** + * Constructor + * @param target {(H.data.AbstractReader | H.map.Object)} - The target that's passed to event listeners + * @param type {string} - The type of the event + * @param state {H.data.AbstractReader.State} - The state of the target firing an event + * @param message {string} - The message associated with an event + */ + constructor(target: (H.data.AbstractReader | H.map.Object), type: string, state: H.data.AbstractReader.State, message: string); + } + + /** + * The state types of an Reader. Possible states are: + */ + export enum State { + ERROR, + LOADING, + VISIT, + READY, + } + } + } + + /***** geo *****/ + export module geo { + /** + * A Geographic coordinate that specifies the height of a point in meters. A value of undefined is treated as 0. + */ + export type Altitude = number; + + /** + * Contexts for altitudes to specify the contextual origin of an altitude's value + */ + export enum AltitudeContext { + /** Ground level */ + undefined, + /** Ground level */ + GL, + /** Obstruction level */ + OL, + /** Mean sea level */ + SL, + /** Sea bed level */ + SB, + /** WGS84 ellipsoid */ + WE, + /** WGS84 geoid */ + WG, + } + + /** + * An interface to represent a geographic point. Every point in geo space is represented by three coordinates latitude, longitude and optional altitude. + * @property lat {H.geo.Latitude} - The latitude coordinate. + * @property lng {H.geo.Longitude} - The longitude coordinate. + * @property alt {H.geo.Altitude=} - The altitude coordinate. + * @property ctx {H.geo.AltitudeContext=} - The altitude context. + */ + export interface IPoint { + lat: H.geo.Latitude; + lng: Longitude; + alt?: H.geo.Altitude; + ctx?: H.geo.AltitudeContext; + } + + export interface IProjection { + latLngToPoint(lat: number, lng: number, opt_out?: H.math.Point): H.math.Point; + xyToGeo(x: number, y: number, opt_out?: H.geo.Point): H.geo.Point; + pointToGeo(point: H.math.IPoint, opt_out?: H.geo.Point): H.geo.Point; + geoToPoint(geoPoint: H.geo.IPoint, opt_out?: H.math.Point): H.math.Point; + } + + /** + * A geographic coordinate that specifies the north-south position of a point on the Earth's surface in the range from -90 to + 90 degrees, inclusive. + */ + export type Latitude = number; + + /** + * A Geographic coordinate that specifies the east-west position of a point on the Earth's surface in the range from -180 to 180 degrees, inclusive. + */ + export type Longitude = number; + + /** + * Class represents a geographical point, which is defined by the latitude, longitude and optional altitude. + * @property lat {H.geo.Latitude} - The latitude coordinate. + * @property lng {H.geo.Longitude} - The longitude coordinate. + * @property alt {H.geo.Altitude} - The altitude coordinate. + * @property ctx {H.geo.AltitudeContext} - The altitude context. + */ + export class Point implements IPoint { + /** + * Constructor + * @property lat {H.geo.Latitude} - The latitude coordinate. + * @property lng {H.geo.Longitude} - The longitude coordinate. + * @property opt_alt {H.geo.Altitude=} - The altitude coordinate. + * @property opt_ctx {H.geo.AltitudeContext=} - The altitude context. + */ + constructor(lat: H.geo.Latitude, lng: Longitude, opt_alt?: H.geo.Altitude, opt_ctx?: H.geo.AltitudeContext); + + /** + * To compare this point with a supplied other point for equality. Two points are considered equal if they have the same lat and lng as well as equivalent values for alt and ctx. + * @param other {H.geo.IPoint} + * @returns {boolean} - Whether the two points are equal. + */ + equals(other: IPoint): boolean; + + /** + * To calculate the distance between this point and the supplied other point. The method uses the Haversine formula. The altitude is not considered. + * @param other {H.geo.IPoint} + * @returns {number} - The distance between the given location and the location supplied by the caller in meters. + */ + distance(other: IPoint): number; + + /** + * This method calculates the geographic point of a destination point using the distance and bearing specified by the caller. The altitude is ignored, instead the WGS84 Mean Radius is taken. + * @param bearing {number} - The bearing to use in the calculation in degrees. + * @param distance {number} - The distance to the destination in meters. + * @param opt_overGreatCircle {boolean=} - If true the computation uses the 'Great Circle' otherwise 'Rhumb Line'. + * @returns {H.geo.Point} - The calculated point + */ + walk(bearing: number, distance: number, opt_overGreatCircle?: boolean): Point; + + /** + * This method validates the given IPoint. It checks, if lat, lng, alt and ctx have valid types. Additionally the value of the lat property is clamped into a range of -90 ... +90 and the value of the lng property is modulo into a range of -180 ... +180 plus validates the values of the alt and ctx properties + * @param point {H.geo.IPoint} - The point to validate + * @param opt_caller {Function=} - The caller to use for InvalidArgumentError. If omitted no error is thrown + * @param opt_argNr {number=} - The argument number to use for InvalidArgumentError. + * @returns {boolean} - if the given point could validate + */ + static validate(point: IPoint, opt_caller?: Function, opt_argNr?: number): boolean; + + /** + * This method creates a Point instance from a given IPoint object. + * @param iPoint {H.geo.IPoint} - The IPoint object to use + * @returns {H.geo.Point} - the created Point instance + */ + static fromIPoint(iPoint: IPoint): Point; + + lat: H.geo.Latitude; + lng: H.geo.Longitude; + alt: H.geo.Altitude; + ctx: H.geo.AltitudeContext; + } + + /** + * This class represents a rectangular geographic area. The area is defined by four geographical coordinates two (left, right) longitudes and two (top, bottom) latitudes. + */ + export class Rect { + /** + * Constructor + * @param top {H.geo.Latitude} - the northern-most latitude + * @param left {H.geo.Longitude} - the left-most longitude + * @param bottom {H.geo.Latitude} - the southern-most latitude + * @param right {H.geo.Longitude} - the right-most latitude + */ + constructor(top: H.geo.Latitude, left: H.geo.Longitude, bottom: H.geo.Latitude, right: H.geo.Longitude); + + /** + * To compare this rectangle with a supplied other rectangle for equality. + * @param other {H.geo.Rect} + * @returns {boolean} - Whether the two rectangles are equal. + */ + equals(other: H.geo.Rect): boolean; + + /** + * Toclone this rectangle. + * @returns {H.geo.Rect} + */ + clone(): H.geo.Rect; + + /** + * This method returns the top-left corner of the rectangular area. + * @returns {H.geo.Point} - the top-left corner of the area + */ + getTopLeft(): H.geo.Point; + + /** + * This method returns the bottom-right corner of the rectangular area. + * @returns {H.geo.Point} - the bottom-right corner of the area + */ + getBottomRight(): H.geo.Point; + + /** + * This method returns the north-most latitude of this rectangular area + * @returns {H.geo.Latitude} - the north-most latitude of the area + */ + getTop(): H.geo.Latitude; + + /** + * This method returns the south-most latitude of this rectangular area + * @returns {H.geo.Latitude} - the south-most latitude of the area + */ + getBottom(): H.geo.Latitude; + + /** + * This method returns the left-most longitude of this rectangular area + * @returns {H.geo.Longitude} - the left-most longitude of the area + */ + getLeft(): H.geo.Longitude; + + /** + * This method returns the right-most longitude of this rectangular area + * @returns {H.geo.Longitude} - the right-most longitude of the area + */ + getRight(): H.geo.Longitude; + + /** + * This method returns the center point of this rectangular area + * @returns {H.geo.Point} - the center point of the area + */ + getCenter(): H.geo.Point; + + /** + * Returns this width of this rectangular area in decimal degrees. + * @returns {number} - the width of this area + */ + getWidth(): number; + + /** + * Returns this height of this rectangular area in decimal degrees. + * @returns {number} - the height of this area + */ + getHeight(): number; + + /** + * Returns a boolean value indicating whether this rectangular area spans across the date border. + * @returns {boolean} - true if the area spans across the date border, otherwise false + */ + isCDB(): boolean; + + /** + * The method checks if the area enclosed by the given bounding box is 0. + * @returns {boolean} - true if the dimensions of the area a 0, otherwise false + */ + isEmpty(): boolean; + + /** + * This method checks if the latitude and longitude supplied by the caller lie within the area of this rectangular area. + * @param lat {H.geo.Latitude} - the latitude + * @param lng {H.geo.Longitude} - the longitude + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {boolean} - true if the latitude and longitude are contained in this area, otherwise false + */ + containsLatLng(lat: H.geo.Latitude, lng: H.geo.Longitude, opt_skipValidation?: boolean): boolean; + + /** + * This method checks if the point supplied by the caller lies within the area of this rectangular area. + * @param geoPoint {H.geo.IPoint} - the point + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {boolean} - true if the point is contained in this area, otherwise false + */ + containsPoint(geoPoint: H.geo.IPoint, opt_skipValidation?: boolean): boolean; + + /** + * This method checks if the rectangular area supplied by the caller is completely contained within the area of this rectangular area. + * @param geoRect {H.geo.Rect} - the rectangular area + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {boolean} - true if the rectangular area is contained in this area, otherwise false + */ + containsRect(geoRect: H.geo.Rect, opt_skipValidation?: boolean): boolean; + + /** + * This method returns the smallest bounding box that covers this rectangular area and the latitude and longitude supplied by the caller. + * @param lat {H.geo.Latitude} - the latitude + * @param lng {H.geo.Longitude} - the longitude + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @param opt_out {H.geo.Rect=} - an optional rectangular area to store the result + * @returns {H.geo.Rect} - either the rectangular area passed as out parameter or a new rectangular area + */ + mergeLatLng(lat: H.geo.Latitude, lng: H.geo.Longitude, opt_skipValidation?: boolean, opt_out?: H.geo.Rect): H.geo.Rect; + + /** + * This method returns the smallest bounding box that covers this rectangular area and the point supplied by the caller. + * @param geoPoint {H.geo.IPoint} - the point to merge + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @param opt_out {H.geo.Rect=} - an optional rectangular area to store the result + * @returns {H.geo.Rect} - either the rectangular area passed as out parameter or a new rectangular area + */ + mergePoint(geoPoint: H.geo.IPoint, opt_skipValidation?: boolean, opt_out?: H.geo.Rect): H.geo.Rect; + + /** + * This method returns the smallest bounding box that covers this rectangular area and the rectangular area supplied by the caller. + * @param geoRect {H.geo.Rect} - the point to merge + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @param opt_out {H.geo.Rect=} - an optional rectangular area to store the result + * @returns {H.geo.Rect} - either the rectangular area passed as out parameter or a new rectangular area + */ + mergeRect(geoRect: H.geo.Rect, opt_skipValidation?: boolean, opt_out?: H.geo.Rect): H.geo.Rect; + + /** + * This method returns the smallest bounding box that covers this rectangular area and the rectangular area supplied by the caller. + * @param top {H.geo.Latitude} - The top latitude of the rectangle to merge + * @param left {H.geo.Longitude} - The left longitude of the rectangle to merge + * @param bottom {H.geo.Latitude} - The bottom latitude of the rectangle to merge + * @param right {H.geo.Longitude} - The right longitude of the rectangle to merge + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @param opt_out {H.geo.Rect=} - an optional rectangular area to store the result + * @returns {H.geo.Rect} - either the rectangular area passed as out parameter or a new rectangular area + */ + mergeTopLeftBottomRight(top: H.geo.Latitude, left: H.geo.Longitude, bottom: H.geo.Latitude, right: H.geo.Longitude, opt_skipValidation?: boolean, opt_out?: H.geo.Rect): H.geo.Rect; + + /** + * This method checks if the intersection of two bounding boxes is non-empty. + * @param geoRect {H.geo.Rect} - a rectangular area to be tested for intersection with this rectangular area + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {boolean} - a boolean value indicating whether the two areas intersect + */ + intersects(geoRect: H.geo.Rect, opt_skipValidation?: boolean): boolean; + + /** + * This method merges two rects by their values. The result of the merge is a bounding rect which covers all provided rect bounds. + * @param topA {H.geo.Latitude} - the northern-most latitude + * @param leftA {H.geo.Longitude} - the left-most longitude of operand A + * @param bottomA {H.geo.Latitude} - the southern-most latitude of operand A + * @param rightA {H.geo.Longitude} - the right-most latitude of operand A + * @param topB {H.geo.Latitude} - the northern-most latitude of operand B + * @param leftB {H.geo.Longitude} - the left-most longitude of operand B + * @param bottomB {H.geo.Latitude} - the southern-most latitude of operand B + * @param rightB {H.geo.Longitude} - the right-most latitude of operand B + * @param opt_out {H.geo.Rect=} - an optional rect to store the results + * @returns {H.geo.Rect} - either the opt_out rect or a new rect + */ + static merge(topA: H.geo.Latitude, leftA: H.geo.Longitude, bottomA: H.geo.Latitude, rightA: H.geo.Longitude, topB: H.geo.Latitude, leftB: H.geo.Longitude, bottomB: H.geo.Latitude, rightB: H.geo.Longitude, opt_out?: H.geo.Rect): H.geo.Rect; + + /** + * This method creates a rectangular area from a top-left and bottom-right point pair. + * @param topLeft {H.geo.IPoint} - the top-left corner of the area + * @param bottomRight {H.geo.IPoint} - the bottom-right corner of the area + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {H.geo.Rect} - returns the rectangular area defined by the top-left and bottom-right corners + */ + static fromPoints(topLeft: H.geo.IPoint, bottomRight: H.geo.IPoint, opt_skipValidation?: boolean): H.geo.Rect; + + /** + * This method creates the minimum rectangular area covering all of the points in the argument array. + * @param pointArray {Array} - the array of points to cover + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {H.geo.Rect} - returns the minimum rectangular area covering the points or null if no point is covered + */ + static coverPoints(pointArray: Array, opt_skipValidation?: boolean): H.geo.Rect; + + /** + * This method creates the minimum rectangular area covering all of the coordinates in the argument array. + * @param latLngAltArray {Array} - the array of coordinates to cover + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {(H.geo.Rect | undefined)} - returns the minimum rectangular area covering the coordinates + */ + static coverLatLngAlts(latLngAltArray: Array, opt_skipValidation?: boolean): H.geo.Rect | void; + + /** + * This method creates the minimum rectangular area covering all of the rectangular areas in the argument array. + * @param rectArray {Array} - the array of points to cover + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {(H.geo.Rect | undefined)} - returns the minimum rectangular area covering the rectangular areas + */ + static coverRects(rectArray: Array, opt_skipValidation?: boolean): H.geo.Rect | void; + + /** + * This method clones the given bounding rect and resizes the clone if necessary until the location supplied by the caller is at its center. + * @param center {H.geo.IPoint} - a point which is to be the center of the resized rectangular area + * @param opt_out {H.geo.Rect=} - an optional rectangular area to store the result + * @returns {H.geo.Rect} - the resized rectangular area + */ + resizeToCenter(center: H.geo.IPoint, opt_out?: H.geo.Rect): H.geo.Rect; + } + } + + /***** lang *****/ + + /***** map *****/ + export module map { + /** + * This class represents marker, which offers a means of identifying a location on the map with an icon. + */ + export class AbstractMarker extends H.map.Object { + /** + * Constructor + * @param position {H.geo.IPoint} - The location of this marker + * @param opt_options {H.map.AbstractMarker.Options=} - The values to initialize this marker + */ + constructor(position: H.geo.IPoint, opt_options?: H.map.AbstractMarker.Options); + + /** + * This method returns this marker's current position. + * @returns {H.geo.Point} - current marker geo position + */ + getPosition(): H.geo.Point; + + /** + * This method sets the marker's current position. + * @param position {H.geo.IPoint} + * @returns {H.map.AbstractMarker} - the marker itself + */ + setPosition(position: H.geo.IPoint): H.map.AbstractMarker; + + /** + * Returns this marker's current icon. + * @returns {!(H.map.Icon | H.map.DomIcon)} + */ + getIcon(): (H.map.Icon | H.map.DomIcon); + + /** + * Sets the marker's current icon. + * @param icon {!(H.map.Icon | H.map.DomIcon)} - The new marker icon + * @returns {H.map.AbstractMarker} - the marker itself + */ + setIcon(icon: (H.map.Icon | H.map.DomIcon)): H.map.AbstractMarker; + } + + export module AbstractMarker { + /** + * Options used to initialize a AbstractMarker + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property visibility {boolean=} - Indicates whether the map object is visible at all, default is true. + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property icon {(H.map.Icon | H.map.DomIcon)=} - The icon to use for the visual representation, if omitted a default icon is used. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + */ + export interface Options { + min?: number; + max?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + icon?: H.map.Icon | H.map.DomIcon; + data?: any; + } + } + + /** + * This class represents style attributes for arrows to be rendered along a polyline. A ArrowStyle instance is always treated as immutable to avoid inconstiencies and must not modified. + */ + export class ArrowStyle { + /** + * Constructor + * @param opt_options {(H.map.ArrowStyle | H.map.ArrowStyle.Options)=} + */ + constructor(opt_options?: (H.map.ArrowStyle | H.map.ArrowStyle.Options)); + + /** + * This method checks value-equality with another arrow style. + * @param other {(H.map.ArrowStyle | H.map.ArrowStyle.Options)} - the arrow style to compare with + * @returns {boolean} - true if the arrow styles are value-equal, otherwise false + */ + equals(other: (H.map.ArrowStyle | H.map.ArrowStyle.Options)): boolean; + } + + export module ArrowStyle { + /** + * An object type to specify the style of arrows to render along a polyline + * @property fillColor {string=} - The CSS color value used to fill the arrow shapes. If omitted or the value evaluates to false it defaults to "rgba(255, 255, 255, 0.75)" + * @property width {number=} - The width of the arrow shape. The value is taken as a factor of the width of the line, where the arrow description is applied. If omitted or the value is <= 0 it defaults to 1.2 + * @property length {number=} - The length of the arrow shapes. The value is taken as a factor of the width of the line at the end of which the arrow is drawn. If omitted or the value is <= 0 it defaults to 1.6 + * @property frequency {number=} - The frequency of arrow shapes. The value is taken as factor of the length of the arrow. A value of 1 results in gapless arrows. If omitted or the value is false it defaults to 5 + */ + export interface Options { + fillColor?: string; + width?: number; + length?: number; + frequency?: number; + } + } + + /** + * The class represents data model of the map. It holds list of layers that are rendered by map's RenderEngine. The class listens to 'update' events from layers and dispatches them to the RenderEngine. + */ + export class DataModel extends H.util.OList { + /** + * Constructor + * @param opt_layers {Array=} - array of layers to be added to the data model + */ + constructor(opt_layers?: Array); + } + + /** + * A visual representation of the H.map.DomMarker. + */ + export class DomIcon { + /** + * Constructor + * @param element {!(Element | string)} - The element or markup to use for this icon + * @param opt_options {H.map.DomIcon.Options=} + */ + constructor(element: (Element | string), opt_options?: H.map.DomIcon.Options); + } + + export module DomIcon { + /** + * Options used to initialize a DomIcon + * @property onAttach {function(Element, H.map.DomIcon, H.map.DomMarker)=} - A callback which is invoked before a clone of the icon's element is appended and displayed on the map. This callback can be used to setup the clone. + * @property onDetach {function(Element, H.map.DomIcon, H.map.DomMarker)=} - A callback which is invoked after a clone of the icon's element is removed from the map. This callback can be used to clean up the clone. + */ + export interface Options { + onAttach?: (el: Element, icon: H.map.DomIcon, marker: H.map.DomMarker) => void; + onDetach?: (el: Element, icon: H.map.DomIcon, marker: H.map.DomMarker) => void; + } + } + + /** + * A marker with a visual representation in the form of a full styleable and scripteable DOM element. DomMarker are predestinated if small amounts of markers with dynamic styled and/or scripted icons should be displayed om the map (e.g. animated interactive SVG). + */ + export class DomMarker extends H.map.AbstractMarker { + /** + * Constructor + * @param position {H.geo.IPoint} + * @param opt_options {H.map.DomMarker.Options=} + */ + constructor(position: H.geo.IPoint, opt_options?: H.map.DomMarker.Options); + } + + export module DomMarker { + /** + * Options used to initialize a DomMarker + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property visibility {boolean=} - Indicates whether the map object is visible at all, default is true. + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property icon {H.map.DomIcon=} - The icon to use for the visual representation, if omitted a default icon is used. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData + */ + export interface Options { + min?: number; + max?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + icon?: H.map.DomIcon; + data?: any; + } + } + + /** + * This class represents a map object which can contain other map objects. It's visibility, zIndex and object-order influences the contained map objects + */ + export class Group extends H.map.Object { + /** + * Constructor + * @param opt_options {H.map.Group.Options=} - an optional object containing initialization values + */ + constructor(opt_options?: H.map.Group.Options); + + /** + * + * @param callback {function(!H.map.Object, number, !H.map.Group)} + * @param opt_recursive {boolean=} - Indicates whether sub groups should be traversed recursively + * @param opt_context {*=} - The context to use as "this" within the callback + */ + forEach(callback: (object: H.map.Object, n: number, group: H.map.Group) => void, opt_recursive?: boolean, opt_context?: any): void; + + /** + * To get a list of all objects of this group. On groups with many chilren this method can cause a higher memory and CPU consumption. Alternatively you case use H.map.Group#forEach + * @param opt_recursive {boolean=} - Indicates whether objects in sub-groups are also collected . + * @returns {!Array} + */ + getObjects(opt_recursive?: boolean): Array; + + /** + * Method returns the bounding rectangle for the group. The rectangle is the smallest rectangle that covers all objects. If group doesn't contains objects method returns null. + * @returns {H.geo.Rect} - geo ractangle that covers all objects in the group + */ + getBounds(): H.geo.Rect; + + /** + * To add an object to this group. + * @param object {!H.map.Object} + * @returns {!H.map.Object} - a reference to the appended object + */ + addObject(object: H.map.Object): H.map.Object; + + /** + * Appends a list of objects to this group + * @param objects {Array} + */ + addObjects(objects: Array): void; + + /** + * Removes an object from this group. + * @param object {!H.map.Object} - The object to remove + * @returns {!H.map.Object} - a reference to the removed object + */ + removeObject(object: H.map.Object): H.map.Object; + + /** + * Removes objects from this group. + * @param objects {!Array} - The list of objects to remove + */ + removeObjects(objects: Array): void; + + /** + * Method removes all objects from the group. + */ + removeAll(): void; + } + + export module Group { + /** + * Options used to initialize a group + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property visibility {boolean=} - Indicates whether the map object is visible, default is true + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + * @property objects {Array=} - A list of map objects to add initially to this group. + */ + export interface Options { + min?: number; + max?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + data?: any; + objects?: Array; + } + } + + /** + * This class represents an area that objects, like a marker, occupies in the screen space, meaning that object can be probed and returned by H.Map@getObjectsAt method. + */ + export class HitArea { + /** + * Constructor + * @param shapeType {H.map.HitArea.ShapeType} - The shape type of the HitArea + * @param opt_values {Array=} - The type-dependent values to define the shape of the hit area. The format for the different types are: + */ + constructor(shapeType: H.map.HitArea.ShapeType, opt_values?: Array); + } + + export module HitArea { + /** + * Enumeration represents possible shape types that HitArea can have. + */ + export enum ShapeType { + NONE, + RECT, + CIRCLE, + POLYGON, + } + } + + /** + * Control interface defines method which are used for direct view or camera manipulation + */ + export interface IControl { + + /** + * This method starts control action for camera. This action allows to control camera animation and movement according to provided values in the H.map.IControl#control function + * @param opt_kinetics {H.util.kinetics.IKinetics=} - kinetics settings + * @param opt_atX {number=} - control starts at x screen coordinate + * @param opt_atY {number=} - control starts at y screen coordinate + */ + startControl(opt_kinetics?: H.util.kinetics.IKinetics, opt_atX?: number, opt_atY?: number): void; + + /** + * This method triggers single control action on engine. This will trigger an animation which will start modification of the view's or camera's properties according to values begin set. Modification will occur at every frame. The speed values are measure by 'levels per frame' were 1 level cooresponds to a distance to next zoom level. + * @param moveX {number} - moves the view/cam in right/left direction + * @param moveY {number} - moves the view/cam in bottom/top direction + * @param moveZ {number} - moves the view/cam in depth direction (changes zoom level) + * @param angleX {number} - rotates cam over x-axis + * @param angleY {number} - rotates cam over y-axis + * @param angleZ {number} - rotates cam over z-axis + * @param zoom {number} - changes current zoom level (for view works as moveZ) + * @param opt_timestamp {number=} + */ + control(moveX: number, moveY: number, moveZ: number, angleX: number, angleY: number, angleZ: number, zoom: number, opt_timestamp?: number): void; + + /** + * This method ends current control, which will stop ongoing animation triggered by the startControl method. This method can prevent kinetics as well as it can adjust the final view if the adjust function is being passed. + * @param opt_preventKinetics {boolean=} - if set to true will prevent kinetics animation + * @param opt_adjustView {function(H.map.ViewModel.CameraData)=} - user defined function which can adjust the final view this function takes last requestedData from the view model and should return a modified H.map.ViewModel.CameraData which will be set as the final view + */ + endControl(opt_preventKinetics?: boolean, opt_adjustView?: (data: H.map.ViewModel.CameraData) => void): void; + } + + /** + * An interface to specify a copyright note + * @property label {string} - A short textual representation of the copyright note, e.g. "DigitalGlobe 2009" + * @property alt {string} - A detailed textual representation of the copyright note, e.g. "copyright 2009 DigitalGlobe, Inc." + */ + export interface ICopyright { + label: string; + alt: string; + } + + /** + * Interface describes interaction with the view port. Interaction will reflect view change depending on the interaction coordinates passed and the modifiers which specify the type of interaction. + */ + export interface IInteraction { + /** + * This method starts the interaction with the view port. Should be called every time when new interaction is started i.e mouse grab, or touch start. + * @param modifiers {number} - a bitmask which specifies what operations should performed during every interaction + * @param opt_kinetics {H.util.kinetics.IKinetics=} - specifies kinetic move at the end of interaction + */ + startInteraction(modifiers: H.math.BitMask, opt_kinetics?: H.util.kinetics.IKinetics): void; + + /** + * This method resolves direct screen (view port) interaction. This function will modify the current view according to values passed in. + * @param x {number} - viewport x coordinate + * @param y {number} - viewport y coordinate + * @param opt_bx {number=} - x coordinate for second pointer/touch if present + * @param opt_by {number=} - y coordinate for secong pointer/touch if present + * @param opt_timestamp {number=} - known timestamp which should be passed + */ + interaction(x: number, y: number, opt_bx?: number, opt_by?: number, opt_timestamp?: number): void; + + /** + * This method ends interaction and applies kinetic movement if defined by using startInteraction method + * @param opt_preventKinetics {boolean=} - if set to true will prevent kinetics behaviour at the end of interaction + */ + endInteraction(opt_preventKinetics?: boolean): void; + } + + /** + * A visual representation of the H.map.Marker. + */ + export class Icon { + /** + * Constructor + * @param bitmap {!(string | HTMLImageElement | HTMLCanvasElement)} - Either an image URL, a SVG markup, an image or a canvas. + * @param opt_options {H.map.Icon.Options=} + */ + constructor(bitmap: (string | HTMLImageElement | HTMLCanvasElement), opt_options?: H.map.Icon.Options); + + /** + * Returns the icon's bitmap loading state + * @returns {H.map.Icon.prototype.State} + */ + getState(): H.map.Icon.State; + + /** + * Returns the bitmap of this icon or null if the bitmap is not ready yet (see H.map.Icon#getState) + * @returns {?(HTMLImageElement | HTMLCanvasElement)} + */ + getBitmap(): (HTMLImageElement | HTMLCanvasElement); + + /** + * Returns the size of this icon or null if a size wasn't specified in the constructor's options and the state of this icon is not H.map.Icon.prototype.State.READY + * @returns {?H.math.Size} + */ + getSize(): H.math.Size; + + /** + * Returns the anchor point of this icon or null if an anchor wasn't specified in the constructor's options and the state of this icon is not H.map.Icon.prototype.State.READY. + * @returns {?H.math.Point} + */ + getAnchor(): H.math.Point; + + /** + * Returns the hit area of the icon. + * @returns {?H.map.HitArea} - icon's anchor point + */ + getHitArea(): H.map.HitArea; + + /** + * This method allows to listen for specific event triggered by the object. Keep in mind, that you must removeEventListener manually or dispose an object when you no longer need it. Otherwise memory leak is possible. + * @param type {string} - name of event + * @param handler {Function} - event handler function + * @param opt_capture {boolean=} - if set to true will listen in the capture phase (bubble otherwise) + * @param opt_scope {Object=} - scope for the handler function + */ + addEventListener(type: string, handler: Function, opt_capture?: boolean, opt_scope?: Object): void; + + /** + * This method will removed previously added listener from the event target + * @param type {string} - name of event + * @param handler {Function} - previously added event handler + * @param opt_capture {boolean=} - if set to true will listen in the capture phase (bubble otherwise) + * @param opt_scope {Object=} - scope for the handler function + */ + removeEventListener(type: string, handler: Function, opt_capture?: boolean, opt_scope?: Object): void; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module Icon { + /** + * The state types of an Icon + */ + export enum State { + ERROR, + LOADING, + READY, + } + + /** + * Options used to initialize a Icon + * @property size {H.math.ISize=} - The icon's size in pixel, default is the bitmap's natural size + * @property anchor {H.math.IPoint=} - The anchorage point in pixel, default is bottom-center + * @property hitArea {H.map.HitArea=} - The area to use for hit detection, default is the whole rectangular area + * @property asCanvas {H.map.HitArea=} - Indicates whether a non canvas bitmap is converted into a canvas, default is true. The conversion improves the rendering performance but it could also cause a higher memory consumption. + * @property crossOrigin {boolean} - Specifies whether to use anonynous Cross-Origin Resource Sharing (CORS) when fetching an image to prevent resulting canvas from tainting, default is false. The option is ignored by IE9-10. + */ + export interface Options { + size?: H.math.ISize; + anchor?: H.math.IPoint; + hitArea?: H.map.HitArea; + asCanvas?: H.map.HitArea; + crossOrigin: boolean; + } + } + + /** + * This class encapsulates the brand, copyright and terms of use elements on the map. + */ + export class Imprint { + /** + * Constructor + * @param map {H.Map} - The map where the imprint is attached to + * @param opt_options {H.map.Imprint.Options=} - The options to style the imprint + */ + constructor(map: H.Map, opt_options?: H.map.Imprint.Options); + + /** + * To set the imprint options. If no opt_options argument is defined then all values are reset to their defaults. + * @param opt_options {H.map.Imprint.Options=} - The options to style the imprint + */ + setOptions(opt_options?: H.map.Imprint.Options): void; + + /** + * This method retrieves the copyright string for the current view of the map. + * @returns {string} - The copyright string for the current map view + */ + getCopyrights(): string; + + /** + * To get the CSS style declaration of the imprint DOM element + * @returns {CSSStyleDeclaration} + */ + getStyle(): CSSStyleDeclaration; + + /** + * Method adds a callback which will be triggered when the object is disposed + * @param callback {Function} + * @param opt_scope {Object=} + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + + /** + * This method is used to capture the element view + * @param canvas {HTMLCanvasElement} - HTML Canvas element to draw the view of the capturable element + * @param pixelRatio {number} - The pixelRatio to use for over-sampling in cases of high-resolution displays, default is 1 + * @param callback {function(HTMLCanvasElement=)} - Callback function to call once result of the capturing is ready + * @param opt_errback {function(string)=} - Callback function to call if error occurred during capturing + */ + capture(canvas: HTMLCanvasElement, pixelRatio: number, callback?: (canvas: HTMLCanvasElement) => void, opt_errback?: (s: string) => void): void; + } + + export module Imprint { + /** + * Options to style an imprint + * @property invert {boolean=} - Indicates whether the logo is inverted. If omitted the current value remains, default is false. + * @property font {string=} - The font of the text. If omitted the current value remains, default is "11px Arial,sans-serif". + * @property href {string=} - The URL of the "Terms of use" link. If omitted the current value remains, default is "http://here.com/terms". + */ + export interface Options { + invert?: boolean; + font?: string; + href?: string; + } + } + + /** + * A marker with a visual representation in the form of a bitmap icon. Marker are predestinated if large amounts of markers with static icons should be displayed om the map. + */ + export class Marker extends H.map.AbstractMarker { + /** + * Constructor + * @param position {H.geo.IPoint} - The location of this marker + * @param opt_options {H.map.Marker.Options=} - The values to initialize this marker + */ + constructor(position: H.geo.IPoint, opt_options?: H.map.Marker.Options); + } + + export module Marker { + /** + * Options used to initialize a Marker + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property visibility {boolean=} - Indicates whether the map object is visible at all, default is true. + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property icon {H.map.Icon=} - The icon to use for the visual representation, if omitted a default icon is used. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + */ + export interface Options { + min?: number; + max?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + icon?: H.map.Icon; + data?: any; + } + } + + /** + * This class represents the abstract base class for map objects such as polylines, polygons, markers, groups etc. + */ + export class Object extends H.util.EventTarget { + /** + * Constructor + * @param opt_options {H.map.Object.Options=} - The values to initialize this object + */ + constructor(opt_options?: H.map.Object.Options); + + /** + * Returns the ID of this object. + * @returns {*} + */ + getId(): any; + + /** + * Sets the visibility of this object. + * @param opt_visibility {boolean=} - Indicates whether this map object should be visible. + * @returns {H.map.Object} - returns this object + */ + setVisibility(opt_visibility?: boolean): H.map.Object; + + /** + * Returns the visibility of this object. + * @param opt_effective {boolean=} - Indicates that the effective visibility is requested. In this case the visibility of all possible ancestor groups is also taken into account + * @returns {boolean} + */ + getVisibility(opt_effective?: boolean): boolean; + + /** + * Returns the z-index of this object. + * @returns {(number | undefined)} + */ + getZIndex(): number | void; + + /** + * To set the-index of this object. + * @param zIndex {(number | undefined)} + * @returns {H.map.Object} - returns this object + */ + setZIndex(zIndex?: number): H.map.Object; + + /** + * Compares two objects regarding their z-order, useful to sort a list of objects via Array's sort() method + * @param first {H.map.Object} - The first object to compare + * @param second {H.map.Object} - The second object to compare + * @returns {number} - If less then 0 the first object has a lower z-order. If equal 0 booth objects have the same z-order. If greater then 0 the first object has a higher z-order. + */ + static compareZOrder(first: H.map.Object, second: H.map.Object): number; + + /** + * Returns the parent group which contains this object or null if the object is not contained by any group. + * @returns {?H.map.Group} + */ + getParentGroup(): H.map.Group; + + /** + * The root object in which this object is attached or the object itself. + * @returns {!H.map.Object} + */ + getRootGroup(): H.map.Object; + + /** + * Checks whether the given object is an inclusive descendant of this object + * @param object {*} - The object that's being compared against. + * @returns {boolean} + */ + contains(object: any): boolean; + + /** + * The current provider of this object + * @returns {?H.map.provider.ObjectProvider} - the current provider + */ + getProvider(): H.map.provider.ObjectProvider; + + /** + * Returns the invalidations of this object + * @returns {H.map.provider.Invalidations} - an invalidation object + */ + getInvalidations(): H.map.provider.Invalidations; + + /** + * This method invalidates this map object. + * @param flags {H.math.BitMask} - The flags indicating the types of occurred changes + * @returns {boolean} - indicates whether a validtion was executed (only if the object has a provider) + */ + invalidate(flags: H.math.BitMask): boolean; + + /** + * This method returns previously stored arbitrary data from this object. + * @returns {*} - the previously stored data or undefined if not data was stored. + */ + getData(): any; + + /** + * This method stores arbitrary data with this map object + * @param data {*} - the data to be stored + * @returns {H.map.Object} - returns this map object instance + */ + setData(data: any): H.map.Object; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module Object { + /** + * Options used to initialize a map object + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property visibility {boolean=} - Indicates whether the map object is visible at all, default is true + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + */ + export interface Options { + min?: number; + max?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + data?: any; + } + + /** + * The major types of map objects + */ + export enum Type { + /** spatial object */ + ANY, + /** spatial object */ + OVERLAY, + /** spatial object */ + SPATIAL, + /** Marker object */ + MARKER, + /** DomMarker object */ + DOM_MARKER, + /** DomMarker object */ + GROUP, + } + } + + /** + * This class represents an overlay, which offers a bitmap that covers a geographical reactangular area on the map. + */ + export class Overlay extends H.map.Object { + /** + * Constructor + * @param bounds {H.geo.Rect} - The geographical reactangular area of this overlay + * @param bitmap {!(string | HTMLImageElement | HTMLCanvasElement)} - Either an image URL, a SVG markup, an image or a canvas. + * @param opt_options {H.map.Overlay.Options=} - Optional values values to initialize this overlay + */ + constructor(bounds: H.geo.Rect, bitmap: (string | HTMLImageElement | HTMLCanvasElement), opt_options?: H.map.Overlay.Options); + + /** + * This method returns this overlay's current bounds. + * @returns {H.geo.Rect} + */ + getBounds(): H.geo.Rect; + + /** + * This method sets the overlay's current bounds. + * @param bounds {H.geo.Rect} + * @returns {H.map.Overlay} - the overlay itself + */ + setBounds(bounds: H.geo.Rect): H.map.Overlay; + + /** + * Returns this overlay's current bitmap. + * @returns {?(HTMLImageElement | HTMLCanvasElement)} - the bitmap of this Overlay or null if it isn't ready yet + */ + getBitmap(): (HTMLImageElement | HTMLCanvasElement); + + /** + * Sets the overlay's current bitmap. + * @param bitmap {!(string | HTMLImageElement | HTMLCanvasElement)} - Either an image URL, a SVG markup, an image or a canvas. + * @returns {H.map.Overlay} - the overlay itself + */ + setBitmap(bitmap: (string | HTMLImageElement | HTMLCanvasElement)): H.map.Overlay; + + /** + * Returns this overlay's current opacity. + * @returns {number} + */ + getOpacity(): number; + + /** + * Sets the overlay's current opacity. + * @param opacity {number} - The opacity in range from 0 (transparent) to 1 (opaque). + * @returns {H.map.Overlay} - the overlay itself + */ + setOpacity(opacity: number): H.map.Overlay; + } + + export module Overlay { + /** + * Options used to initialize an Overlay + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property opacity {number=} - The opacity of the object in range from 0 (transparent) to 1 (opaque), default is 1. + * @property visibility {boolean=} - Indicates whether the map object is visible at all, default is true. + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + */ + export interface Options { + min?: number; + max?: number; + opacity?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + data?: any; + } + } + + /** + * This class represents a spatial map object which provides its projected geometry. + */ + export class Spatial extends H.map.Object { + /** + * Constructor + * @param isClosed {boolean} - Indicates whether this spatial object represents a closed shape + * @param opt_options {H.map.Spatial.Options=} - The options to apply + */ + constructor(isClosed: boolean, opt_options?: H.map.Spatial.Options); + + /** + * To get the drawing style of this object. The returned style is treated as immutable and must not be modified afterwards to prevent inconsistancies! + * @returns {H.map.SpatialStyle} + */ + getStyle(): H.map.SpatialStyle; + + /** + * To set the drawing style of this object. If the passed opt_style argument is an instance of H.map.SpatialStyle it is treated as immutable and must not be modified afterwards to prevent inconsistancies! . + * @param opt_style {(H.map.SpatialStyle | H.map.SpatialStyle.Options)=} - The style to set. If it evaluates to a falsy the H.map.SpatialStyle.DEFAULT_STYLE is used. + * @returns {H.map.Spatial} - the Spatial instance itself + */ + setStyle(opt_style?: (H.map.SpatialStyle | H.map.SpatialStyle.Options)): H.map.Spatial; + + /** + * To get the arrow style of this spatial object or undefined if no style is defined. A returned arrow style is treated as immutable and must not be modified afterwards to prevent inconsistancies! + * @returns {(H.map.ArrowStyle | undefined)} + */ + getArrows(): H.map.ArrowStyle | void; + + /** + * To set the arrow style of this object. + * @param opt_arrows {(H.map.ArrowStyle | H.map.ArrowStyle.Options)=} - the arrow style to be applied + * @returns {H.map.Spatial} - the Spatial instance itself + */ + setArrows(opt_arrows?: (H.map.ArrowStyle | H.map.ArrowStyle.Options)): H.map.Spatial; + + /** + * Indicates whether this spatial object represents a closed shape + * @returns {boolean} + */ + isClosed(): boolean; + } + + export module Spatial { + /** + * Data to used as rendering hint for a label + * @property x {number} - The X coordinate of the first line's starting point + * @property y {number} - The Y coordinate of the first line's base line + * @property angle {number} - The clockwise rotation angle in radians + * @property font {string} - The CSS font-family + * @property size {number} - The CSS font-size + * @property color {string} - The CSS color + * @property text {string} - The text content, new line characters (\u000A) are interpreted as line breaks + */ + export interface Label { + x: number; + y: number; + angle: number; + font: string; + size: number; + color: string; + text: string; + } + + /** + * Options which are used to initialize spatial object object + * @property style {(H.map.SpatialStyle | H.map.SpatialStyle.Options)=} - the style to be used when tracing the spatial object + * @property arrows {(H.map.ArrowStyle | H.map.ArrowStyle.Options)=} - The arrows style to be used when rendering the spatial. + * @property visibility {boolean=} - An optional boolean value indicating whether this map object is visible, default is true + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + */ + export interface Options { + style?: (H.map.SpatialStyle | H.map.SpatialStyle.Options); + arrows?: (H.map.ArrowStyle | H.map.ArrowStyle.Options); + visibility?: boolean; + zIndex?: number; + min?: number; + max?: number; + provider?: H.map.provider.Provider; + data?: any; + } + } + + /** + * The SpatialStyle class represents a style with which spatial objects like polylines and polygons are drawn. A SpatialStyle instance is always treated as immutable to avoid inconstiencies and must not modified. + * @property strokeColor {string} - The color of the stroke in CSS syntax, default is 'rgba(0, 85, 170, 0.6)'. + * @property fillColor {string} - The filling color in CSS syntax, default is 'rgba(0, 85, 170, 0.4)'. + * @property lineWidth {number} - The width of the line in pixels, default is 2. + * @property lineCap {H.map.SpatialStyle.LineCap} - The style of the end caps for a line, default is 'round'. + * @property lineJoin {H.map.SpatialStyle.LineJoin} - The type of corner created, when two lines meet, default is 'miter'. + * @property miterLimit {number} - The miter length is the distance between the inner corner and the outer corner where two lines meet. The default is 10. + * @property lineDash {Array} - The line dash pattern as an even numbered list of distances to alternately produce a line and a space. The default is [ ]. + * @property lineDashOffset {number} - The phase offset of the line dash pattern The default is 0. + * @property MAX_LINE_WIDTH {number} - This constant represents the maximum line width which can be used for rendering. + * @property DEFAULT_STYLE {H.map.SpatialStyle} - This static member defines the default style for spatial objects on the map. It's value is { strokeColor: '#05A', fillColor: 'rgba(0, 85, 170, 0.4)' lineWidth: 1, lineCap: 'round', lineJoin: 'miter', miterLimit: 10, lineDash: [ ], lineDashOffset: 0 } + */ + export class SpatialStyle { + /** + * Constructor + * @param opt_options {(H.map.SpatialStyle | H.map.SpatialStyle.Options)=} - The optional style attributes + */ + constructor(opt_options?: (H.map.SpatialStyle | H.map.SpatialStyle.Options)); + + /** + * This method checks value-equality with another style. + * @param other {(H.map.SpatialStyle | H.map.SpatialStyle.Options)} - the style to compare with + * @returns {boolean} - true if the styles are value-equal, otherwise false + */ + equals(other: (H.map.SpatialStyle | H.map.SpatialStyle.Options)): boolean; + + /** + * Returns a copy of spatial style object and replaces the passed style attributes into it. + * @param opt_attributes {H.map.SpatialStyle.Options=} - The style attributes to set on the copied style instance + * @returns {H.map.SpatialStyle} + */ + getCopy(opt_attributes?: H.map.SpatialStyle.Options): H.map.SpatialStyle; + + strokeColor: string; + fillColor: string; + lineWidth: number; + lineCap: H.map.SpatialStyle.LineCap; + lineJoin: H.map.SpatialStyle.LineJoin; + miterLimit: number; + lineDash: Array; + lineDashOffset: number; + MAX_LINE_WIDTH: number; + DEFAULT_STYLE: H.map.SpatialStyle; + } + + export module SpatialStyle { + /** + * The style of the end caps for a line, one of 'butt', 'round' or 'square'. + */ + export type LineCap = 'butt' | 'round' | 'square'; + + /** + * The type of corner created, when two lines meet, one of 'round', 'bevel' or 'miter'. + */ + export type LineJoin = 'round' | 'bevel' | 'miter'; + + /** + * Options used to initialize a style. If a property is not set, the default value from H.map.SpatialStyle is taken. + * @property strokeColor {string=} - The color of the stroke in CSS syntax. + * @property fillColor {string=} - The color of the stroke in CSS syntax. + * @property lineWidth {number=} - The width of the line in pixels, default is 2. The maximum supported line width is 100. + * @property lineCap {H.map.SpatialStyle.LineCap=} - The style of the end caps for a line. + * @property lineJoin {H.map.SpatialStyle.LineJoin=} - The type of corner created, when two lines meet. + * @property miterLimit {number=} - The miter limit in pixel, default is 10. The maximum supported miter limit is 100 + * @property lineDash {Array} - The line dash pattern as an even numbered list of distances to alternately produce a line and a space. If the browser doesn't support this feature this style property is ignored. + * @property lineDashOffset {number=} - The phase offset of the line dash pattern + */ + export interface Options { + strokeColor?: string; + fillColor?: string; + lineWidth?: number; + lineCap?: H.map.SpatialStyle.LineCap; + lineJoin?: H.map.SpatialStyle.LineJoin; + miterLimit?: number; + lineDash: Array; + lineDashOffset?: number; + } + } + + /** + * This class represents a view of the map. It consists of a virtual camera and a look-at point both of which have a position in geo-space and orientation angles. The view model allows to change the values of these objects in order to move or rotate the map or zoom in and out. + */ + export class ViewModel extends H.util.EventTarget implements H.map.IControl { + /** + * This method returns the camera data, which is currently rendered. + * @returns {H.map.ViewModel.CameraData} - the current rendered camera data + */ + getCameraData(): H.map.ViewModel.CameraData; + + /** + * This method sets new camera data to be processed by the renderer. + * @param data {H.map.ViewModel.CameraData} - the values to be modified + * @returns {H.map.ViewModel} - this view model object + */ + setCameraData(data: H.map.ViewModel.CameraData): H.map.ViewModel; + + /** + * This method sets a new zoom level to be processed by the renderer + * @param zoom {number} - the new zoom level + * @param animate {boolean} + */ + setZoom(zoom: number, animate: boolean): void; + + /** + * This method returns the zoom level that is currently rendered. + * @returns {number} - current zoom level (scale) + */ + getZoom(): number; + + /** + * This method returns the currently requested data. + * @returns {H.map.ViewModel.CameraData} - last requested cam/view data + */ + getRequestedCameraData(): H.map.ViewModel.CameraData; + + /** + * A method to signal the begin of a control operation. + * @param opt_kinetics {H.util.kinetics.IKinetics=} - kinetics settings + * @param opt_atX {number=} - x screen coordinate at which control has started + * @param opt_atY {number=} - y screen coordinate at which control has started + */ + startControl(opt_kinetics?: H.util.kinetics.IKinetics, opt_atX?: number, opt_atY?: number): void; + + /** + * A method to set the values for a continuously modification of the ViewModel on different axes. If the current render engine doesn't support certain modifications then they are ignored. + * @param moveX {number} - The movement on x-axis as levels per millisecond where a level correlates to the distance between camera and look-at point. + * @param moveY {number} - The movement on y-axis as levels per millisecond where a level correlates to the distance between camera and look-at point + * @param moveZ {number} - The movement on z-axis as levels per millisecond. + * @param angleX {number} - The rotation of on screen's x axis as degrees per millisecond. + * @param angleY {number} - The rotation of on screen's y axis as degrees per millisecond. + * @param angleZ {number} - The rotation of on screen's z axis as degrees per millisecond. + * @param opt_zoom {number=} - The modification of the zoom level as levels per millisecond + */ + control(moveX: number, moveY: number, moveZ: number, angleX: number, angleY: number, angleZ: number, opt_zoom?: number): void; + + /** + * A method to signal the end of a control operation. + * @param opt_preventKinetics {boolean=} - A flag to indicate whether a kinetic effect is performed + * @param opt_adjustView {function(H.map.ViewModel.CameraData)=} - An callback to adjust the final ViewModel by modifying the passed camera data. + */ + endControl(opt_preventKinetics?: boolean, opt_adjustView?: (data: H.map.ViewModel.CameraData) => void): void; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module ViewModel { + /** + * Defines camera's properties. + * @property zoom {number=} - zoom level to be used by rendering engine + * @property position {H.geo.IPoint} - the position of the virtual camera in geo-space + * @property pitch {number=} - the rotation of the virtual camera along its local x-axis + * @property yaw {number=} - the rotation of the virtual camera along its local y-axis + * @property roll {number=} - the rotation of the virtual camera along its local z-axis + * @property fov {number=} - + */ + export interface CameraData { + zoom?: number; + position: H.geo.IPoint; + pitch?: number; + yaw?: number; + roll?: number; + fov?: number; + } + + /** + * Defines currently requested view data, which will be rendered by the map. + * @property camera {H.map.ViewModel.CameraData=} - The requested camera properties + * @property zoom {number=} - The requested zoom level + * @property animate {boolean=} - indicates if the requested transition should be animated + */ + export interface RequestedData { + camera?: H.map.ViewModel.CameraData; + zoom?: number; + animate?: boolean; + } + + /** + * Update event is fired whenever view model data is changed. It contains property which hold currently requested data + * @property target {*} - Object which triggered the event + * @property currentTarget {*} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class UpdateEvent extends H.util.Event { + /** + * Constructor + * @param requested {H.map.ViewModel.RequestedData} + */ + constructor(requested: H.map.ViewModel.RequestedData); + + /** + * Sets defaultPrevented to true. Which can be used to prevent some default behavior. + */ + preventDefault(): void; + + /** + * Stops propagation for current event. + */ + stopPropagation(): void; + + target: any; + currentTarget: any; + type: string; + defaultPrevented: boolean; + } + } + + /** + * ViewPort object holds information about the HTML element where the map is rendered. It contains information regarding the element (view port) size and triggers events when the element size is changed. + * @property element {Element} - This property holds the HTML element, which defines the viewport. + * @property width {number} - This property holds this viewport's current width + * @property height {number} - This property holds this viewport's current height + * @property margin {number} - This property holds this viewport's current margin value + * @property padding {H.map.ViewPort.Padding} - This property holds this viewport's current padding + * @property center {H.math.Point} - This property holds this viewport's current center point + */ + export class ViewPort extends H.util.EventTarget implements H.map.IInteraction { + /** + * Constructor + * @param element {Element} - html element were map will be rendered + * @param opt_options {H.map.ViewPort.Options=} - optional configuration parameters + */ + constructor(element: Element, opt_options?: H.map.ViewPort.Options); + + /** + * This method sets the margin on the viewPort + * @param margin {number} - margin which is used to fetch map data + */ + setMargin(margin: number): void; + + /** + * This method sets the padding on the viewport. Padding will result in shifted map center which will be the visual center of the padded area. + * @param top {number} - padding from the top + * @param right {number} - padding from the right + * @param bottom {number} - padding from the bottom + * @param left {number} - padding from the left + */ + setPadding(top: number, right: number, bottom: number, left: number): void; + + /** + * This method updates size of the viewport according to container size. It must be called whenever the HTML element changed size in order to update the map's viewport values. + */ + resize(): void; + + /** + * This method starts the interaction with the view port. Should be called every time when new interaction is started i.e mouse grab, or touch start. + * @param modifiers {number} - a bitmask which specifies what operations should performed during every interaction + * @param opt_kinetics {H.util.kinetics.IKinetics=} - specifies kinetic move at the end of interaction + */ + startInteraction(modifiers: H.math.BitMask, opt_kinetics?: H.util.kinetics.IKinetics): void; + + /** + * This method resolves direct screen (view port) interaction. This function will modify the current view according to values passed in. + * @param x {number} - viewport x coordinate + * @param y {number} - viewport y coordinate + * @param opt_bx {number=} - x coordinate for second pointer/touch if present + * @param opt_by {number=} - y coordinate for secong pointer/touch if present + * @param opt_timestamp {number=} - known timestamp which should be passed + */ + interaction(x: number, y: number, opt_bx?: number, opt_by?: number, opt_timestamp?: number): void; + + /** + * This method ends interaction and applies kinetic movement if defined by using startInteraction method + * @param opt_preventKinetics {boolean=} - if set to true will prevent kinetics behaviour at the end of interaction + */ + endInteraction(opt_preventKinetics?: boolean): void; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + + element: Element; + width: number; + height: number; + margin: number; + padding: H.map.ViewPort.Padding; + center: H.math.Point; + } + + export module ViewPort { + /** + * Options which may be used to initialize new ViewPort instance + * @property margin {number=} - The size in pixel of the supplemental area to render for each side of the map + * @property padding {H.map.ViewPort.Padding=} - The padding in pixels for each side of the map + * @property fixedCenter {boolean=} - Indicates whether the center of the map should remain unchanged if the viewport's size or or padding has been changed, default is true + */ + export interface Options { + margin?: number; + padding?: H.map.ViewPort.Padding; + fixedCenter?: boolean; + } + + /** + * Represents viewport padding definition. + * @property top {number} - the padding on the top edge (in pixels) + * @property right {number} - the padding on the right edge (in pixels) + * @property bottom {number} - the padding on the bottom edge (in pixels) + * @property left {number} - the padding on the left edge (in pixels) + */ + export interface Padding { + top: number; + right: number; + bottom: number; + left: number; + } + } + + export module layer { + /** + * BaseTileLayer encapsulates funcitonailty that is common to all layers that deliver tiles, such as H.map.layer.TileLayer. The functionality includes geo bounding box to grid calculation, tile request management. + */ + export class BaseTileLayer extends H.map.layer.Layer { + /** + * Constructor + * @param provider {H.map.provider.TileProvider} - data source for the TileLayer + * @param opt_options {H.map.layer.ITileLayer.Options=} - additional options + */ + constructor(provider: H.map.provider.TileProvider, opt_options?: H.map.layer.ITileLayer.Options); + + /** + * This method returns the provider which feeds this layer with data. + * @returns {H.map.provider.TileProvider} - this layer's provider + */ + getProvider(): H.map.provider.TileProvider; + + /** + * This method transforms a geo-rectangle to geometrical projected rectangle at the current projection zoom level or at provided zoom level + * @param geoRect {H.geo.Rect} - geo bounds to be projected + * @param opt_zoom {number=} - overrides current projection zoom level + * @returns {H.math.Rect} - projected 2d space rect cooresponding to provided geo bounds + */ + geoRectToRect(geoRect: H.geo.Rect, opt_zoom?: number): H.math.Rect; + + /** + * This method returns tile grid for a bounding rectangle + * @param rectBounds {H.math.Rect} - projected rect bounds which coorespond to geo bounding box + * @param zoom {number} - current zoom level + * @returns {H.math.Rect} - rectangle which represents the tile grid bounds + */ + getTileBounds(rectBounds: H.math.Rect, zoom: number): H.math.Rect; + + /** + * This method requests a single tile according to tile coordinates. It returns either a Tile object if it is already loaded or undefined and starts loading the tile + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - The zoom level for which the tile is requested + * @param cacheOnly {boolean} - indicates whether only cached tiles are to be considered + * @returns {(H.map.provider.Tile | undefined)} - tile object corresponding to requested coordinates + */ + requestTile(x: number, y: number, z: number, cacheOnly: boolean): H.map.provider.Tile | void; + + /** + * This method cancels a previously requested tile. + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - zoom level + */ + cancelTile(x: number, y: number, z: number): void; + + /** + * This method requests tiles from the data source (provider). It can return a set of tiles which are currently loaded. All tiles which are not yet loaded will be included in response as soon as they will be available during subsequent calls. + * @param tileBounds {H.math.Rect} - bounds in tile grid + * @param isCDB {boolean} + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {H.map.layer.ITileLayer.Response} - returns an array if tile which are already loaded + */ + getProviderTiles(tileBounds: H.math.Rect, isCDB: boolean, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): H.map.layer.ITileLayer.Response; + } + + /** + * This interface describes a layer which provides marker objects to the renderer. + */ + export interface IMarkerLayer { + + /** + * This method requests marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + + /** + * This method requests dom marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestDomMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + } + + export module IMarkerLayer { + /** + * This type represents a response object returned by the H.map.layer.IMarkerLayer#requestMarkers function. + * @property total {number} - The total number of markers, inclusive markers with not ready icons + * @property markers {Array} - The marker objects for the bounding rectangle (only ready) + */ + export interface Response { + total: number; + markers: Array; + } + + /** + * This type represents a response object returned by the H.map.layer.IMarkerLayer#requestMarkers function. + * @property number {number} - of returned tiles + * @property requested {number} - number of requested tiles + * @property objects {Array} - the marker objects within requested tiled area + */ + export interface TiledResponse { + number: number; + requested: number; + objects: Array; + } + } + + /** + * This interface describes a layer which provides data partitioned in quad-tree tiles in an x, y, z fashion (where z describes the level within the tree and x and y describe the absolute column and row indeces whithin the level). + */ + export interface ITileLayer { + /** + * This method requests tiles for the current bounding rectangle at the given zoom level (z-value). + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which tiles are to be returned + * @param zoomLevel {number} - The zoom level for which the tiles are requested + * @param cacheOnly {boolean} - Indicates whether only cached tiles are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {H.map.layer.ITileLayer.Response} - a response object containing the total number of tiles requested and the tile objects that could be immediately returned + */ + requestTiles(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): H.map.layer.ITileLayer.Response; + + /** + * This method requests a single tile according to tile coordinates. It returns either a Tile object if it is already loaded or undefined and starts loading the tile + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - The zoom level for which the tile is requested + * @param cacheOnly {boolean} - indicates whether only cached tiles are to be considered + * @returns {(H.map.provider.Tile | undefined)} - tile object corresponding to requested coordinates + */ + requestTile(x: number, y: number, z: number, cacheOnly: boolean): H.map.provider.Tile | void; + + /** + * This method cancels a previously requested tile. + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - zoom level + */ + cancelTile(x: number, y: number, z: number): void; + } + + export module ITileLayer { + /** + * Options which are used to initialize a TileLayer object. + * @property projection {H.geo.IProjection=} - an optional projection to be used for this layer, default is H.geo.mercator + * @property opacity {number=} - tile layer opacity, default is 1 + */ + export interface Options { + projection?: H.geo.IProjection; + opacity?: number; + } + + /** + * A response object for a tile request. Contains total number of elements requested and an array of currently available Tiles + * @property total {number} - the total number of requested tiles + * @property tiles {Array} - the tiles which this provider can currently return synchronously + */ + export interface Response { + total: number; + tiles: Array; + } + } + + /** + * The Layer class represents an object that is evaluated by the renderer in the order in which it is added to the layers collection. It provides the basic infrastructure for dispatching update events to the renderer in case new data is available. + */ + export class Layer extends H.util.EventTarget { + /** + * Constructor + * @param opt_options {H.map.layer.Layer.Options=} - optional configuration object + */ + constructor(opt_options?: H.map.layer.Layer.Options); + + /** + * This method checks if a zoom level can be served by this layer. + * @param zoomLevel {number} - the zoom level to check + * @returns {boolean} - true if this layer can provide data for the zoom level, otherwise false + */ + isValid(zoomLevel: number): boolean; + + /** + * This method sets the minimum zoom level for which this layer will provide tiles. + * @param min {number} - The new minimum zoom level of this layer + * @returns {H.map.layer.Layer} - Returns this instance of the layer + */ + setMin(min: number): H.map.layer.Layer; + + /** + * This method sets the maximum zoom level for which this layer will provide tiles. + * @param max {number} - The new maximum zoom level of this layer + * @returns {H.map.layer.Layer} - Returns this instance of the layer + */ + setMax(max: number): H.map.layer.Layer; + + /** + * This method returns the copyright of the current data provider. + * @param bounds {H.geo.Rect} - the bounding area for which to retrieve the copyright information + * @param level {number} - the zoom level for which to retrieve the copyright information + * @returns {Array} - a list of copyright information objects for the provided area and zoom level + */ + getCopyrights(bounds: H.geo.Rect, level: number): Array; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module Layer { + /** + * Options which can be used when creating new layer object. + * @property min {number=} - The minimum zoom level for which the layer can provide data, default is 0 + * @property max {number=} - The maximum zoom level for which the layer can provide data, default is 22 + * @property dark {boolean=} - Indicates whether the content of this layer is mainly dark, default is false See also H.Map.Options#autoColor + * @property projection {H.geo.IProjection=} - The projection to be used for this layer, default is H.geo.mercator + * @property minWorldSize {number=} - The minimal world size at zoom level 0, default is 256 + */ + export interface Options { + min?: number; + max?: number; + dark?: boolean; + projection?: H.geo.IProjection; + minWorldSize?: number; + } + } + + /** + * ObjectTileLayer represents map objects which are requested on a tile basis + */ + export class MarkerTileLayer extends H.map.layer.BaseTileLayer implements H.map.layer.IMarkerLayer { + /** + * Constructor + * @param provider {H.map.provider.MarkerTileProvider} + * @param opt_options {H.map.layer.ITileLayer.Options=} + */ + constructor(provider: H.map.provider.MarkerTileProvider, opt_options?: H.map.layer.ITileLayer.Options); + + /** + * This method requests marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + + /** + * This method requests dom marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestDomMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + } + + /** + * This class represents a layer which renders map objects. Spatial objects like polygons and polylines a rendered to tiles before being passed to the enigne. Point objects like markers are provided as objects given an rectangular area. + */ + export class ObjectLayer extends H.map.layer.Layer implements H.map.layer.ITileLayer { + /** + * Constructor + * @param provider {H.map.provider.ObjectProvider} - the ObjectProvider which provides the map objects to this object layer. + * @param opt_options {H.map.layer.ObjectLayer.Options=} - The options for this layer + */ + constructor(provider: H.map.provider.ObjectProvider, opt_options?: H.map.layer.ObjectLayer.Options); + + /** + * This method returns current ObjectLayer's data provider + * @returns {H.map.provider.ObjectProvider} + */ + getProvider(): H.map.provider.ObjectProvider; + + /** + * To request overlay objects for the passsed bounding rectangle. It returns all overlay objects which are contained within this bounding rectangle. + * @param bounds {H.geo.Rect} - The bounding rectangle for which overlays are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {H.map.layer.ObjectLayer.OverlaysResponse} + */ + requestOverlays(bounds: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): H.map.layer.ObjectLayer.OverlaysResponse; + + /** + * This method requests tiles for the current bounding rectangle at the given zoom level (z-value). + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which tiles are to be returned + * @param zoomLevel {number} - The zoom level for which the tiles are requested + * @param cacheOnly {boolean} - Indicates whether only cached tiles are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {H.map.layer.ITileLayer.Response} - a response object containing the total number of tiles requested and the tile objects that could be immediately returned + */ + requestTiles(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): H.map.layer.ITileLayer.Response; + + /** + * This method requests a single tile according to tile coordinates. It returns either a Tile object if it is already loaded or undefined and starts loading the tile + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - The zoom level for which the tile is requested + * @param cacheOnly {boolean} - indicates whether only cached tiles are to be considered + * @returns {(H.map.provider.Tile | undefined)} - tile object corresponding to requested coordinates + */ + requestTile(x: number, y: number, z: number, cacheOnly: boolean): H.map.provider.Tile | void; + + /** + * This method cancels a previously requested tile. + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - zoom level + */ + cancelTile(x: number, y: number, z: number): void; + + /** + * This method requests marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + + /** + * This method requests dom marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestDomMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + } + + export module ObjectLayer { + /** + * Configuration object which can be use to initialize the ObjectLayer. + * @property tileSize {number=} - the size of the tiles rendered by this layer for polylines and polygons (must be power of 2, default is 256) + * @property tileCacheSize {number=} - the number of fully rendered spatial tiles that are cached for immediate reuse, default is 32 + * @property dataCacheSize {number=} - the number of tiles to cache which have render data only, default is 512 + * @property pixelRatio {number=} - The pixelRatio to use for over-sampling in cases of high-resolution displays + */ + export interface Options { + tileSize?: number; + tileCacheSize?: number; + dataCacheSize?: number; + pixelRatio?: number; + } + + /** + * A response object returned by the H.map.layer.ObjectLayer#requestOverlays function. + * @property total {number} - The total number of overlays within the requested bounds, inclusive overlays which are not ready loaded yet + * @property overlays {Array} - A list all overlays which are ready to render + */ + export interface OverlaysResponse { + total: number; + overlays: Array; + } + } + + /** + * Tile Layer, represents data shown on map on a tile basis. Can be used to show map tile images or other type of data which is partitioned into tiles. + * @event update {H.util.Event} + */ + export class TileLayer extends H.map.layer.BaseTileLayer implements H.map.layer.ITileLayer { + /** + * Constructor + * @param provider {H.map.provider.TileProvider} - data source for the TileLayer + * @param opt_options {H.map.layer.ITileLayer.Options=} - additional options + */ + constructor(provider: H.map.provider.TileProvider, opt_options?: H.map.layer.ITileLayer.Options); + + /** + * This method requests tiles for the current bounding rectangle at the given zoom level (z-value). + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which tiles are to be returned + * @param zoomLevel {number} - The zoom level for which the tiles are requested + * @param cacheOnly {boolean} - Indicates whether only cached tiles are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {H.map.layer.ITileLayer.Response} - a response object containing the total number of tiles requested and the tile objects that could be immediately returned + */ + requestTiles(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): H.map.layer.ITileLayer.Response; + + update: H.util.Event; + } + } + + export module provider { + /** + * An ImageTileProvider uses network service to provide bitmap images as tiles. + * @property tileSize {number} - Size of a tile image supported by the provider + */ + export class ImageTileProvider extends H.map.provider.RemoteTileProvider { + /** + * Constructor + * @param options {H.map.provider.ImageTileProvider.Options} - configuration for tile provider + */ + constructor(options: H.map.provider.ImageTileProvider.Options); + + tileSize: number; + } + + export module ImageTileProvider { + /** + * Options to initialize an ImageTileProvider instance + * @property uri {string=} - The provider's unique resource identifier which must not contain an underscore "_". If omitted an auto-generated unique Session ID is used. If a cross sessions consistent IDs is needed (e.g. for storing provider data) this property must be specified. + * @property min {number=} - The minimal supported zoom level, default is 0 + * @property max {number=} - The maximal supported zoom level, default is 22 + * @property getCopyrights {(function(H.geo.Rect, number) : ?Array)=} - A function to replace the default implementation of H.map.provider.Provider#getCopyrights + * @property tileSize {number=} - The size of a tile as edge length in pixels. It must be 2^n where n is in range [0 ... 30], default is 256 + * @property getURL {function(number, number, number)} - The function to create an URL for the specified tile. If it returns a falsy the tile is not requested. + * @property crossOrigin {(string | boolean=)} - The CORS settings to use for the crossOrigin attribute for the image, if omitted or if the value evaluates to false no CORS settings are used. + */ + export interface Options { + uri?: string; + min?: number; + max?: number; + getCopyrights?: ((rect: H.geo.Rect, n: number) => Array); + tileSize?: number; + getURL: (n1: number, n2: number, n3: number) => string; + crossOrigin?: (string | boolean); + } + } + + /** + * This class represents invalidation states of a renderable object. A renderer can optimize its rendering strategies based on the information in this object. + * @property MARK_INITIAL {H.map.provider.Invalidations.Mark} - This constant represents the initial invalidation mark an invalidations object has. + */ + export class Invalidations { + + /** + * To update invalidation marks accordingly to the given the invalidation types. + * @param mark {H.map.provider.Invalidations.Mark} - The invalidation mark to set + * @param types {H.math.BitMask} - The descrete invalidation types to update + */ + update(mark: H.map.provider.Invalidations.Mark, types: H.math.BitMask): void; + + /** + * This method returns the current invalidation mark of this invalidations object. + * @returns {H.map.provider.Invalidations.Mark} - the current invalidation mark + */ + getMark(): H.map.provider.Invalidations.Mark; + + /** + * Checks whether any change occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isAny(since: H.map.provider.Invalidations.Mark): boolean; + + /** + * Checks whether a visual change occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isVisual(since: H.map.provider.Invalidations.Mark): boolean; + + /** + * Checks whether a spatial change occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isSpatial(since: H.map.provider.Invalidations.Mark): boolean; + + /** + * Checks whether an add-operation occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isAdd(since: H.map.provider.Invalidations.Mark): boolean; + + /** + * Checks whether a remove operation occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isRemove(since: H.map.provider.Invalidations.Mark): boolean; + + /** + * Checks whether a z-order change occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isZOrder(since: H.map.provider.Invalidations.Mark): boolean; + + static MARK_INITIAL: H.map.provider.Invalidations.Mark; + } + + export module Invalidations { + /** + * This enumeration encapsulates bit flags for different invalidations of map objects. + */ + export enum Flag { + NONE, + VISUAL, + SPATIAL, + ADD, + REMOVE, + Z_ORDER, + } + + /** + * The invalidation mark represents a counter which is increased whenever an invalidation takes place. + */ + export interface Mark { } + } + + /** + * A MarkerTileProvider uses network service to provide markers on tile basis. + * @property requestTile {} - Request data on a tile basis + * @property cancelTile {} - Cancels tile from being requested using x, y, z coordinates (column, row, zoom) + * @property cancelTileByKey {} - Cancels tile from being requested using a tile-key + * @property uri {string} - This provider's unique resource identifier, if not provided at construction time it defaults to provider's uid + * @property min {number} - Minimum zoom level at which provider can serve data, set at construction time + * @property max {number} - Maximum zoom level at which provider can server data, set at construction time + * @property uid {string} - Provider instance unique identifier, generated at construction time + */ + export class MarkerTileProvider extends H.map.provider.RemoteTileProvider { + /** + * Constructor + * @param options {H.map.provider.MarkerTileProvider.Options} - configuration for tile provider + */ + constructor(options: H.map.provider.MarkerTileProvider.Options); + + /** + * To signal to this provider that a map object has been changed. The method marks tile, that contains that object as invalid and triggers dispatchUpdate() + * @param marker {!H.map.AbstractMarker} - The map object to be invalidated + * @param flags {H.math.BitMask} - The flags indicating the types of occurred changes + */ + invalidateObject(marker: H.map.AbstractMarker, flags: H.math.BitMask): void; + + /** + * Checks whether this provider is currently providing H.map.DomMarker map objects. + * @returns {boolean} + */ + providesDomMarkers(): boolean; + } + + export module MarkerTileProvider { + /** + * Options which are used to initialize the MarkerTileProvider object. + * @property min {number=} - The minimal supported zoom level, default is 0 + * @property max {number=} - The maximal supported zoom level, default is 22 + * @property requestData {function(number, number, number, function(Array), Function) : H.util.ICancelable} - function that fetches marker data and creates array of H.map.AbstractMarker that is passed success callback, if function fails to fetch data onError callback must be called + * @property providesDomMarkers {boolean=} - indicates if markers provided are of type H.map.DomMarker or H.map.Marker, default is H.map.Marker + */ + export interface Options { + min?: number; + max?: number; + requestData: (n1: number, n2: number, n3: number, markerCallback: (markers: Array) => void, f: Function) => H.util.ICancelable; + providesDomMarkers?: boolean; + } + } + + /** + * An abstract class to manage and provide map objects (Marker, Polyline, Polygon) + */ + export class ObjectProvider extends H.map.provider.Provider { + /** + * Constructor + * @param opt_options {H.map.provider.Provider.Options=} + */ + constructor(opt_options?: H.map.provider.Provider.Options); + + /** + * Returns the accumulate invalidations of this provider's objects that have occurred. + * @param opt_type {H.map.Object.Type=} - The type of objects to consider for the invalidations. If undefined, all types are taken into account. + * @returns {H.map.provider.Invalidations} + */ + getInvalidations(opt_type?: H.map.Object.Type): H.map.provider.Invalidations; + + /** + * To signal to this provider that a map object has been changed. The method updates the Invalidations of this provider and the given map object and triggers dispatchUpdate() + * @param mapObject {!H.map.Object} - The map object to be invalidated + * @param changes {H.math.BitMask} - The flags indicating the types of occurred changes + */ + invalidateObject(mapObject: H.map.Object, changes: H.math.BitMask): void; + + /** + * Checks whether this provider is currently providing overlay map objects. A concrete implementation of ObjectProvider must override it if it currently provides overlays. + * @returns {boolean} + */ + providesOverlays(): boolean; + + /** + * Returns all Overlay objects which intersect with the provided area. + * @param geoRect {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestOverlays(geoRect: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Checks whether this provider is currently providing spatial map objects. A concrete implementation of ObjectProvider must override it if it currently provides Spatials. + * @returns {boolean} + */ + providesSpatials(): boolean; + + /** + * Returns all polyline, polygon, circle and rect objects which intersect with the provided area. + * @param geoRect {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestSpatials(geoRect: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Returns the spatial objects which intersect the given tile + * @param tile {H.map.provider.SpatialTile} - The tile for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestSpatialsByTile(tile: H.map.provider.Tile, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Checks whether this provider is currently providing Marker map objects. A concrete implementation of ObjectProvider must override it if it currently provides Markers. + * @returns {boolean} + */ + providesMarkers(): boolean; + + /** + * Returns all Marker map objects which intersect with the provided rectangular area. + * @param geoRect {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestMarkers(geoRect: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Checks whether this provider is currently providing DomMarker map objects. A concrete implementation of ObjectProvider must override it if it currently provides Markers. + * @returns {boolean} + */ + providesDomMarkers(): boolean; + + /** + * Returns all DomMarker map objects which intersect with the provided rectangular area. + * @param geoRect {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestDomMarkers(geoRect: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + } + + /** + * A Provider defines an object which works as a database for the map. Providers can exists in different forms they can implement client side object storage or they can request data from the remote service. + * @property uri {string} - This provider's unique resource identifier, if not provided at construction time it defaults to provider's uid + * @property min {number} - Minimum zoom level at which provider can serve data, set at construction time + * @property max {number} - Maximum zoom level at which provider can server data, set at construction time + * @property uid {string} - Provider instance unique identifier, generated at construction time + */ + export class Provider extends H.util.EventTarget { + /** + * Constructor + * @param opt_options {H.map.provider.Provider.Options=} + */ + constructor(opt_options?: H.map.provider.Provider.Options); + + /** + * This method returns the copyrights of the provided content for a certain geographical area at a specified zoom level. + * @param bounds {H.geo.Rect} - The bounding area for which to retrieve the copyright information + * @param level {number} - The zoom level for which to retrieve the copyright information + * @returns {?Array} - a list of copyright information objects for the provided area and zoom level + */ + getCopyrights(bounds: H.geo.Rect, level: number): Array; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + + uri: string; + min: number; + max: number; + uid: string; + } + + export module Provider { + /** + * Options to initialize a Provider instance + * @property uri {string=} - The provider's unique resource identifier which must not contain an underscore "_". If omitted an auto-generated unique Session ID is used. If a cross sessions consistent IDs is needed (e.g. for storing provider data) this property must be specified. + * @property min {number=} - The minimal supported zoom level, default is 0 + * @property max {number=} - The maximal supported zoom level, default is 22 + * @property getCopyrights {(function(H.geo.Rect, number) : ?Array)=} - A function to replace the default implementation of H.map.provider.Provider#getCopyrights + */ + export interface Options { + uri?: string; + min?: number; + max?: number; + getCopyrights?: (rect: H.geo.Rect, n: number) => Array; + } + } + + /** + * RemoteTileProvider is an abstract class which should be used by classes implementing data provision on a tile basis. Every child class needs to implement 'requestInternal' (to request remote tile) and 'getCache' (to provide configured cache object were tiled data is being cached) + */ + export class RemoteTileProvider extends H.map.provider.TileProvider { + /** + * Constructor + * @param options {H.map.provider.TileProvider.Options} - The options to instantiate this TileProvider + */ + constructor(options: H.map.provider.TileProvider.Options); + + /** + * This method returns cache which should be used to store tiles + * @returns {H.util.ICache} - cache + */ + getCache(): H.util.ICache; + + /** + * This method request tile from remote service + * @param x {number} - The row number of the tile + * @param y {number} - The column number of the tile + * @param z {number} - The zoom level for which the tile is requested + * @param onResponse {function((Array | HTMLImageElement | HTMLCanvasElement | ArrayBuffer | null), *=)} - function which is called after response arrives + * @param onError {function(string=)} - function which is called in case of communication error + * @param opt_priority {H.net.Request.Priority=} - optional request priority level + * @returns {H.util.ICancelable} + */ + requestInternal( + x: number, + y: number, + z: number, + + onResponse?: ( + object: Array | HTMLImageElement | HTMLCanvasElement | ArrayBuffer, + response: any + ) => void, + + onError?: (s: string) => void, + opt_priority?: H.net.Request.Priority + ): H.util.ICancelable; + + /** + * This method instructs the provider to reload data from it's source. + * @param hard {boolean} - a boolean flag indicating whether to invalidate in hard mode (true) or in soft mode (false); + */ + reload(hard: boolean): void; + } + + /** + * Generic Tile object which represents a part of the world fiting into the Tile area represented by the Tiel coordinates (x - row, y - column) and the zoom level (z). Number of tiles at particular zoom level (which means number of areas into world is being splitted) is defined as following: numberOfRows = numberOfColumns = 2^zoomlevel + * @property key {string} - Unique tile key generated by provider + * @property data {*} - Tile data (an image for example) + * @property valid {boolean} - This property holds a boolean flag indicating whether this tile is still valid (true) or whether it should be re-fetched (false) + * @property x {number} - Tile column + * @property y {number} - Tile row + * @property z {number} - Tile zoom level + */ + export class Tile { + /** + * Constructor + * @param x {number} - x tile coordinate (row) + * @param y {number} - y tile coordinate (column) + * @param z {number} - tile zoom level + * @param data {*} - generic data object which cooresponds to the given coordinates + */ + constructor(x: number, y: number, z: number, data?: any); key: string; + + data: any; + valid: boolean; + x: number; + y: number; + z: number; + } + + /** + * TileProvider is an abstract class to provide data on a tile basis + * @property requestTile {} - Request data on a tile basis + * @property cancelTile {} - Cancels tile from being requested using x, y, z coordinates (column, row, zoom) + * @property cancelTileByKey {} - Cancels tile from being requested using a tile-key + * @property uri {string} - This provider's unique resource identifier, if not provided at construction time it defaults to provider's uid + * @property min {number} - Minimum zoom level at which provider can serve data, set at construction time + * @property max {number} - Maximum zoom level at which provider can server data, set at construction time + * @property uid {string} - Provider instance unique identifier, generated at construction time + */ + export class TileProvider extends H.map.provider.Provider { + /** + * Constructor + * @param options {H.map.provider.TileProvider.Options} - The options to instantiate this TileProvider + */ + constructor(options: H.map.provider.TileProvider.Options); + + /** + * This method creates a tile object with given parameters + * @param x {number} - x tile coordinate (row) + * @param y {number} - y tile coordinate (column) + * @param z {number} - tile coordinate (zoom) + * @param data {(HTMLImageElement | HTMLCanvasElement)} - data for the tile + * @param opt_options {Object=} - free form options object. These options are meant to be used in tile specific rendering cases + * @returns {H.map.provider.Tile} + */ + createTileInternal(x: number, y: number, z: number, data: (HTMLImageElement | HTMLCanvasElement), opt_options?: { [key: string]: any }): H.map.provider.Tile; + + /** + * This method creates a tile key consisting of the provider's uri, and the tile's x, y and z coordinates, seperated by underscores e.g.: "4711_7_42_23" + * @param x {number} - The x tile coordinate (row) + * @param y {number} - The y tile coordinate (column) + * @param z {number} - The z tile coordinate (zoom level) + * @returns {string} - string + */ + getTileKey(x: number, y: number, z: number): string; + + requestTile: any; + cancelTile: any; + cancelTileByKey: any; + uri: string; + min: number; + max: number; + uid: string; + } + + export module TileProvider { + /** + * @property uri {string=} - The provider's unique resource identifier which must not contain an underscore "_". If omitted an auto-generated unique Session ID is used. If a cross sessions consistent IDs is needed (e.g. for storing provider data) this property must be specified. + * @property min {number=} - The minimal supported zoom level, default is 0 + * @property max {number=} - The maximal supported zoom level, default is 22 + * @property getCopyrights {(function(H.geo.Rect, number): Array)=} - A function to replace the default implememtation of H.map.provider.Provider#getCopyrights + * @property tileSize {number=} - The size of a tile as edge length in pixels. It must be 2^n where n is in range [0 ... 30], default is 256 + */ + export interface Options { + uri?: string; + min?: number; + max?: number; + getCopyrights?(rect: H.geo.Rect, number: number): Array; + tileSize?: number; + } + } + } + } + + /***** mapevents *****/ + export module mapevents { + /** + * Behavior class uses map events and adds behavior functionality to the map. This allows map panning and zooming via using mouse wheel + * @property DRAGGING {number} - Map responds to user dragging via mouse or touch + * @property WHEELZOOM {number} - Map zooms in or out in respond to mouse wheel events + * @property DBLTAPZOOM {number} - Map zooms in or out in response to double click or double tap. For double tap if more that one touches are on the screen map will zoom out. + */ + export class Behavior extends H.util.Disposable { + /** + * Constructor + * @param mapEvents {H.mapevents.MapEvents} - previously initialized map events instance + * @param options {H.mapevents.Behavior.Options} - additional options (i.e kinetics) + */ + constructor(mapEvents: H.mapevents.MapEvents, options?: H.mapevents.Behavior.Options); + + /** + * This method destroys all map interaction handling. Should be used when the behavior functionality is disposed. Behavior object will also be disposed (this function will be called) when attached H.mapevents.MapEvents object is dispose. + */ + dispose(): void; + + /** + * This method disables the behavior functionality for the map + * @param opt_behavior {number=} - The bitmask of behaviors to disable. If no arguments are passed, all behaviors will be disabled. + */ + disable(opt_behavior?: H.math.BitMask): void; + + /** + * This method re-enables the behavior functionality for the map. + * @param opt_behavior {number=} - The bitmask of behaviors to enable. If no arguments are passed, all behaviors will be enabled. + */ + enable(opt_behavior?: H.math.BitMask): void; + + /** + * This method checks if certain functionality is enabled + * @param behavior {number} - value like H.mapevents.Behavior.DRAGGING which the check is being performed + * @returns {boolean} + */ + isEnabled(behavior: number): boolean; + + static DRAGGING: number; + static WHEELZOOM: number; + static DBLTAPZOOM: number; + } + + export module Behavior { + /** + * Options which are used to initialize the Behavior class. + * @property kinetics {H.util.kinetics.IKinetics=} - The parameters for the kinetic movement. + * @property enable {number=} - The bitmask of behaviors to enable like H.mapevents.Behavior.DRAGGING. All are enabled by default. + */ + export interface Options { + kinetics?: H.util.kinetics.IKinetics; + enable?: H.math.BitMask; + } + } + + /** + * ContextMenuEvent should be fired, when a user right-clicks or longpresses on a map object. + * @property viewportX {Array} - Contains ContextItems, that will be used to create context menu entries. Should be filled by listeners of the "contextmenu" event + * @property viewportY {number} - Map viewport y position + * @property target {(H.map.Object | H.Map)} - Target for the event + * @property originalEvent {Event} - Original event + * @property currentTarget {(H.map.Object | H.Map)} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class ContextMenuEvent extends H.util.Event { + /** + * Constructor + * @param viewportX {number} - The x coordinate on the viewport + * @param viewportY {number} - The y coordinate on the viewport + * @param target {(H.Map | H.map.Object)} - The event's target element + * @param originalEvent {Event} - target of the event + */ + constructor(viewportX: number, viewportY: number, target: (H.Map | H.map.Object), originalEvent: Event); + + viewportX: Array; + viewportY: number; + originalEvent: Event; + } + + /** + * Custom map event. Contains list of pointers on the map, list of changed pointers and original event. Inherits from H.util.Event. + * @property pointers {Array} - Pointers which are currently on the screen + * @property changedPointers {Array} - Pointers which has changed in course of event + * @property targetPointers {Array} - Pointers which are on same target as the current pointer + * @property currentPointer {H.mapevents.Pointer} - Current pointer + * @property originalEvent {Event} - Original event fired by the browser + * @property target {(H.map.Object | H.Map)} - Object which triggered event. Can be the map object (i.e marker or polyline) or the map itself + * @property currentTarget {(H.map.Object | H.Map)} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class Event extends H.util.Event { + /** + * Constructor + * @param type {string} - type of event + * @param pointers {Array} - pointers which are currently on the screen + * @param changedPointers {Array} - pointers which changed during event + * @param targetPointers {Array} - pointers on the event target + * @param currentPointer {H.mapevents.Pointer} - pointer which triggered the event + * @param target {(H.Map | H.map.Object)} - target map object which triggered event + * @param originalEvent {Event} - original dom event + */ + constructor(type: string, pointers: Array, changedPointers: Array, targetPointers: Array, currentPointer: H.mapevents.Pointer, target: (H.Map | H.map.Object), originalEvent: Event); + + /** + * Sets defaultPrevented to true. Which can be used to prevent some default behavior. + */ + preventDefault(): void; + + /** + * Stops propagation for current event. + */ + stopPropagation(): void; + + pointers: Array; + changedPointers: Array; + targetPointers: Array; + currentPointer: H.mapevents.Pointer; + originalEvent: Event; + target: (H.map.Object | H.Map); + currentTarget: (H.map.Object | H.Map); + type: string; + defaultPrevented: boolean; + } + + /** + * MapEvents enable the events functionality on the map and on the map objects. By using this extension it is possible to listen to events on map objects like markers, polylines, polygons, circles and on the map object itself. Events are triggered depending on user interaction. Please check the Events Summary section for the list of events fired by this class and by the map objects. + */ + export class MapEvents extends H.util.Disposable { + /** + * Constructor + * @param map {H.Map} - map instance which is used for firing events + */ + constructor(map: H.Map); + + /** + * This method destroys the MapEvents by removing all handlers from the map object. After calling this function mapEvents and map objects will not trigger any events. This object will be disposed automatically if the corresponding map object is disposed. + */ + dispose(): void; + + /** + * This method returns map into which events are attached + * @returns {H.Map} + */ + getAttachedMap(): H.Map; + } + + /** + * Class representing pointer on the map surface. A pointer in platform specific definition would mean either mouse, touch, pen or any pointing device which can trigger browser events. + * @property viewportX {number} - X coordinate on the map's viewport + * @property viewportY {number} - Y coordinate on the map's viewport + * @property target {(H.map.Object | H.Map)} - Map object directly under the pointer. Can be null if if pointer is out of the map viewport + * @property id {number} - Pointer unique identifier. + * @property type {string} - Pointer type can be: 'mouse', 'touch' or 'pen' + * @property dragTarget {(H.map.Object | H.Map)} - Object which is currently dragged by the pointer + * @property button {H.mapevents.Pointer.Button} - Indicates which pointer device button has changed. + */ + export class Pointer { + /** + * Constructor + * @param viewportX {number} - pointer position on x-axis + * @param viewportY {number} - pointer position on y-axis + * @param id {number} - unique pointer identifier among currently available pointers + * @param type {string} - type of pointer can be i.e 'mouse', 'touch'. 'pen' + * @param opt_button {H.mapevents.Pointer.Button=} - Indicates which pointer device button has changed. + * @param opt_buttons {number=} - Indicates which pointer device buttons are being pressed, expressed as a bitmask. Uses the same values, as "buttons" in Pointer Events spec. + */ + constructor(viewportX: number, viewportY: number, id: number, type: string, opt_button?: H.mapevents.Pointer.Button, opt_buttons?: H.math.BitMask); + static viewportX: number; + static viewportY: number; + static target: (H.map.Object | H.Map); + static id: number; + static type: string; + static dragTarget: (H.map.Object | H.Map); + static button: H.mapevents.Pointer.Button; + } + + export module Pointer { + /** + * Types of a button + */ + export enum Button { + /** No button */ + NONE, + /** Left mouse button or touch contact or pen contact */ + LEFT, + /** Middle mouse button */ + MIDDLE, + /** Right mouse button or Pen barrel button */ + RIGHT, + } + + /** + * Indicates which pointer device buttons are being pressed, expressed as a bitmask. Bit values are: + * + * - 0: No button pressed + * - 1: Left mouse button pressed, or Touch contact or Pen contact + * - 2: Right mouse button pressed, or Pen contact with barrel button pressed + * - 4: Middle mouse button pressed + */ + // TODO not sure this is the right interpretation of the docs + export type Buttons = H.math.BitMask; + } + + /** + * WheelEvent is fired when the mouse wheel is used over the map. It contains information about cursor position and the map object which resides directly under the cursor. + * @property delta {number} - Wheel move delta + * @property viewportX {number} - Map viewport x position + * @property viewportY {number} - Map viewport y position + * @property target {(H.map.Object | H.Map)} - Target for the event + * @property originalEvent {Event} - Original mouse wheel event + * @property currentTarget {(H.map.Object | H.Map)} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class WheelEvent extends H.util.Event { + /** + * Constructor + * @param deltaY {number} - The wheel move delta on y-axis + * @param viewportX {number} - The x coordinate on the viewport + * @param viewportY {number} - The y coordinate on the viewport + * @param target {(H.Map | H.map.Object)} - The event's target element + * @param originalEvent {Event} - target of the event + */ + constructor(deltaY: number, viewportX: number, viewportY: number, target: (H.Map | H.map.Object), originalEvent: Event); + + delta: number; + viewportX: number; + viewportY: number; + originalEvent: Event; + } + } + + /***** math *****/ + export module math { + /** + * A signed 32 bit integer (JS restriction) where bit operator can be applied to. The range is [-2,147,483,648 ... 2,147,483,647] or [-2^31 ... 2^31 − 1] + */ + export type BitMask = number; + + /** + * An interface for a 2-dimensional point consisting a x and y coordinate. + * @property x {number} - The point's coordinate on X-axis. + * @property y {number} - The point's coordinate on Y-axis. + */ + export interface IPoint { + x: number; + y: number; + } + + /** + * An interface for a 2-dimensional size consisting a with and a height. + * @property w {number} - The size's width. + * @property h {number} - The size's height. + */ + export interface ISize { + w: number; + h: number; + } + + /** + * Class represents a 2-dimensional point, defined by x and y coordinates. + * @property x {number} - The point's coordinate on X-axis. + * @property y {number} - The point's coordinate on Y-axis. + */ + export class Point implements IPoint { + /** + * Constructor + * @param x {number} - The point's coordinate on X-axis. + * @param y {number} - The point's coordinate on Y-axis. + */ + constructor(x: number, y: number); + + /** + * Sets the x and y coordinate of this point + * @param x {number} - The point's coordinate on X-axis. + * @param y {number} - The point's coordinate on Y-axis. + */ + set(x: number, y: number): void; + + /** + * This method creates a copy of the current point. + * @param opt_out {H.math.Point=} - An optional point to store the copied values + * @returns {H.math.Point} - The clone of the point + */ + clone(opt_out?: Point): Point; + + /** + * This method adds given point coordinates to the current one. + * @param other {H.math.IPoint} - The point to add + * @returns {H.math.Point} - the point itself after adding + */ + add(other: IPoint): Point; + + /** + * This method subtracts given point coordinates from the current point. + * @param other {H.math.IPoint} - The point to subtract + * @returns {H.math.Point} - the point itself after subtracting + */ + sub(other: IPoint): Point; + + /** + * This method scales the current point coordinates by the given factor(s). + * @param factor {number} - multiplication factor + * @param opt_factorY {number=} - If omitted, the factor argument is used + * @returns {H.math.Point} - the point itself after scaling + */ + scale(factor: number, opt_factorY?: number): Point; + + /** + * This method rounds the x and y coordinates of the point. + * @returns {H.math.Point} - the point itself after rounding + */ + round(): Point; + + /** + * Rounds the x and y coordinates to the next smaller integer values. + * @returns {H.math.Point} - the point itself after flooring + */ + floor(): Point; + + /** + * Rounds the x and y coordinates to the next greater integer values. + * @returns {H.math.Point} - the point itself after ceiling + */ + ceil(): Point; + + /** + * This method compares current point coordinates with the supplied point coordinates. + * @param other {H.math.IPoint} - The point to compare to. + * @returns {boolean} - True if the points are equal + */ + equals(other: IPoint): boolean; + + /** + * Calculates the closest point on a given line + * @param start {H.math.IPoint} - The start point of the line + * @param end {H.math.IPoint} - The end point of the line + * @returns {H.math.IPoint} - the closest point + */ + getNearest(start: IPoint, end: IPoint): IPoint; + + /** + * This method calculates the distance to a point supplied by the caller. + * @param other {H.math.IPoint} + * @returns {number} + */ + distance(other: IPoint): number; + + /** + * This method creates a Point instance from a given IPoint object. + * @param iPoint {H.math.IPoint} - The IPoint object to use + * @returns {H.math.Point} - the created Point instance + */ + static fromIPoint(iPoint: IPoint): Point; + + x: number; + y: number; + } + + /** + * Class defines a rectangle in 2-dimensional geometric space. It is used to represent the area in projected space. + */ + export class Rect { + /** + * Constructor + * @param left {number} - The rectangle's left edge x value + * @param top {number} - The rectangle's top edge y value + * @param right {number} - The rectangle's right edge x value + * @param bottom {number} - The rectangle's bottom edge y value + */ + constructor(left: number, top: number, right: number, bottom: number); + + /** + * To set all values of the rectangle's edges + * @param left {number} - The rectangle's left edge x value + * @param top {number} - The rectangle's top edge y value + * @param right {number} - The rectangle's right edge x value + * @param bottom {number} - The rectangle's bottom edge y value + */ + set(left: number, top: number, right: number, bottom: number): void; + + /** + * To get the rectangle's top-left vertex + * @returns {H.math.Point} + */ + getTopLeft(): H.math.Point; + + /** + * To get the rectangle's bottom-right vertex + * @returns {H.math.Point} + */ + getBottomRight(): H.math.Point; + + /** + * Method checks if provided coordinates lie within rectangle. + * @param x {number} - x-coordinate to check + * @param y {number} - y-coordinate to check + * @returns {boolean} - returns true if coordinates lie within rectangle, if parameters are isNaN returns false + */ + containsXY(x: number, y: number): boolean; + + /** + * To create a rectangle from a top-left and bottom-right point pair. + * @param topLeft {H.math.IPoint} - the top-left vertex of the rectanle + * @param bottomRight {H.math.IPoint} - the bottom-right vertex of the rectanle + * @returns {H.math.Rect} - returns the rectangular area defined by the top-left and bottom-right vertices + */ + static fromPoints(topLeft: H.math.IPoint, bottomRight: H.math.IPoint): H.math.Rect; + + /** + * To clone a rectangle + * @returns {H.math.Rect} + */ + clone(): H.math.Rect; + } + + /** + * Class for representing sizes consisting of a width and height. + * @property w {number} - The size's width value + * @property h {number} - The size's height value + */ + export class Size { + /** + * Constructor + * @param width {number} - Width. + * @param height {number} - Height. + */ + constructor(width: number, height: number); + w: number; + h: number; + } + } + + /***** net *****/ + export module net { + export module Request { + export enum State { + DONE = 2, + OPENED = 1, + UNSENT = 0, + } + + // TODO no idea how this interface is set up, investigate + export interface Priority { } + } + } + + /***** places *****/ + + /***** service *****/ + export module service { + /** + * Abstract rest service class + */ + export class AbstractRestService implements H.service.IConfigurable { + /** + * Constructor + * @param opt_options {H.service.AbstractRestService.Options=} + */ + constructor(opt_options?: H.service.AbstractRestService.Options); + + /** + * This methods receive configuration parameters from the platform, that can be used by the object implementing the interface. + * @param appId {string} - The application ID to identify the client against the platform (mandatory to provide) + * @param appCode {string} - The application code to identify the client against the platform (mandatory to provide) + * @param useHTTPS {boolean} - Indicates whether secure communication should be used, default is false + * @param useCIT {boolean} - Indicates whether the Customer Integration Testing should be used, default is false + * @param opt_baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com. Note that if useHTTPS flag is passed it will override the URL scheme specified in the opt_baseUrl to use HTTPS. + * @returns {H.service.IConfigurable} + */ + configure(appId: string, appCode: string, useHTTPS: boolean, useCIT: boolean, opt_baseUrl?: H.service.Url): H.service.IConfigurable; + } + + export module AbstractRestService { + export interface Options { + + } + } + + /** + * This class encapsulates Enterprise Routing REST API as a service stub. An instance of this class can be retrieved by calling the factory method on a platform instance. H.service.Platform#getEnterpriseRoutingService. + */ + export class EnterpriseRoutingService extends H.service.AbstractRestService { + /** + * Constructor + * @param opt_options {H.service.EnterpriseRoutingService.Options=} + */ + constructor(opt_options?: H.service.EnterpriseRoutingService.Options); + + /** + * This method sends a "calculateroute" request to Enterprise Routing REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occurred. + * @param calculateRouteParams {H.service.ServiceParameters} - the service parameters to be sent with the routing request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Enterprise Routing REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + */ + calculateRoute(calculateRouteParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): void; + + /** + * This method sends a "getroute" request to Enterprise Routing REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occurred. + * @param getRouteParams {H.service.ServiceParameters} - the service parameters to be sent with the routing request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Enterprise Routing REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + */ + getRoute(getRouteParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): void; + + /** + * This method sends a "getlinkinfo" request to Enterprise Routing REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occured. + * @param getLinkInfoParams {H.service.ServiceParameters} - the service parameters to be sent with the routing request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Enterprise Routing REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + */ + getLinkInfo(getLinkInfoParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): void; + + /** + * This method sends a "calculateisoline" request to Enterprise Routing REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occurred. + * @param calculateIsolineParams {H.service.ServiceParameters} - the service parameters to be sent with the routing request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Enterprise Routing REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + */ + calculateIsoline(calculateIsolineParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): void; + } + + export module EnterpriseRoutingService { + /** + * @property subDomain {string=} - The sub-domain of the routing service relative to the platform's base URL (default is 'route') + * @property path {string=} - The path of the map tile service, default is "routing/7.2" + * @property baseUrl {H.service.Url=} - The base URL of the service, defaults to the the platform's base URL if instance was created using H.service.Platform#getEnterpriseRoutingService method. + */ + export interface Options { + subDomain?: string; + path?: string; + baseUrl?: H.service.Url; + } + } + + /** + * This class encapsulates the Geocoding REST API in a service stub with calls to its various resources implemented. + */ + export class GeocodingService extends H.service.AbstractRestService { + /** + * Constructor + * @param opt_options {H.service.GeocodingService.Options=} + */ + constructor(opt_options?: H.service.GeocodingService.Options); + + /** + * This method sends a reverse geocoding request to Geocoder REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occured. + * @param geoodingParams {H.service.ServiceParameters} - the service parameters to be sent with the geocoding request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Geocoder REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + * @returns {H.service.JsonpRequestHandle} + */ + geocode(geoodingParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): H.service.JsonpRequestHandle; + + /** + * This method sends a reverse geocoding request to Geocoder REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occured. + * @param reverseGeocodingParams {H.service.ServiceParameters} - the service parameters to be sent with the reverse geocoding request + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Geocoder REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + * @returns {H.service.JsonpRequestHandle} + */ + reverseGeocode(reverseGeocodingParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): H.service.JsonpRequestHandle; + + /** + * This method sends a landmark search request to Geocoder REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occured. + * @param searchParams {H.service.ServiceParameters} - the service parameters to be sent with the reverse geocoding request + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Geocoder REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + * @returns {H.service.JsonpRequestHandle} + */ + search(searchParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): H.service.JsonpRequestHandle; + } + + export module GeocodingService { + /** + * @property subDomain {string=} - the sub-domain of the geo-coding service relative to the platform's base URL, default is 'geocoder' + * @property path {string=} - the path of the Geocoding service, default is '6.2' + */ + export interface Options { + subDomain?: string; + path?: string; + } + } + + /** + * An interface represents an object, that can be configured credentials, settings etc. by H.service.Platform + */ + export interface IConfigurable { + /** + * This methods receive configuration parameters from the platform, that can be used by the object implementing the interface. + * @param appId {string} - The application ID to identify the client against the platform (mandatory to provide) + * @param appCode {string} - The application code to identify the client against the platform (mandatory to provide) + * @param useHTTPS {boolean} - Indicates whether secure communication should be used, default is false + * @param useCIT {boolean} - Indicates whether the Customer Integration Testing should be used, default is false + * @param opt_baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com. Note that if useHTTPS flag is passed it will override the URL scheme specified in the opt_baseUrl to use HTTPS. + * @returns {H.service.IConfigurable} + */ + configure(appId: string, appCode: string, useHTTPS: boolean, useCIT: boolean, opt_baseUrl?: H.service.Url): H.service.IConfigurable; + } + + /** + * @property id {number} - the ID associated internally with this request + * @property cancel {function()} - this function cancels the request and invokes the errback function + */ + export interface JsonpRequestHandle { + id: number; + cancel: () => void; + } + + /** + * This class encapsulates a map tile end point of the HERE Map Tile API. + */ + export class MapTileService extends H.util.EventTarget implements H.service.IConfigurable { + /** + * Constructor + * @param opt_options {H.service.MapTileService.Options=} + */ + constructor(opt_options?: H.service.MapTileService.Options); + + /** + * This method returns the map tile type provided by this service. + * @returns {string} - the map tile type + */ + getType(): string; + + /** + * This method returns the map tile service's newest version hash. + * @returns {string} - meta information for this map tile service + */ + getVersion(): string; + + /** + * This method returns the map tile service's meta information. The method will return an object once the map tile service's data has been fetched. + * @returns {(H.service.MapTileService.Info | undefined)} - meta information for this map tile service + */ + getInfo(): H.service.MapTileService.Info | void; + + /** + * This method creates a tile provider which uses the specified map tiles. This provider can be used as a data source for an ImageTileLayer. + * @param tileType {string} - the tile type + * @param scheme {string} - the tile scheme + * @param tileSize {number} - the tile size + * @param format {string} - the tile image format + * @param opt_additionalParameters {H.service.ServiceParameters=} - a hash of additional parameters to be + * @param opt_options {H.service.TileProviderOptions=} - additional set of options for the provider + * @returns {H.map.provider.ImageTileProvider} - the image tile provider + */ + createTileProvider(tileType: string, scheme: string, tileSize: number, format: string, opt_additionalParameters?: H.service.ServiceParameters, opt_options?: H.service.TileProviderOptions): H.map.provider.ImageTileProvider; + + /** + * This method creates a tile layer. This layer can be used as a layer on a map's data model. + * @param tileType {string} - the tile type + * @param scheme {string} - the tile scheme + * @param tileSize {number} - the tile size + * @param format {string} - the tile image format + * @param opt_additionalParameters {H.service.ServiceParameters=} - Additional parameters for the map tile service + * @param opt_opacity {number=} - The opacity of this layer + * @param opt_dark {boolean=} - Indicates whether the content of this layer is mainly dark, default is false See also H.Map.Options#autoColor + * @param opt_options {H.service.TileProviderOptions=} - additional set of options for the provider + * @returns {H.map.layer.TileLayer} - the tile layer + */ + createTileLayer(tileType: string, scheme: string, tileSize: number, format: string, opt_additionalParameters?: H.service.ServiceParameters, opt_opacity?: number, opt_dark?: boolean, opt_options?: H.service.TileProviderOptions): H.map.layer.TileLayer; + + /** + * This methods receive configuration parameters from the platform, that can be used by the object implementing the interface. + * @param appId {string} - The application ID to identify the client against the platform (mandatory to provide) + * @param appCode {string} - The application code to identify the client against the platform (mandatory to provide) + * @param useHTTPS {boolean} - Indicates whether secure communication should be used, default is false + * @param useCIT {boolean} - Indicates whether the Customer Integration Testing should be used, default is false + * @param opt_baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com. Note that if useHTTPS flag is passed it will override the URL scheme specified in the opt_baseUrl to use HTTPS. + * @returns {H.service.IConfigurable} + */ + configure(appId: string, appCode: string, useHTTPS: boolean, useCIT: boolean, opt_baseUrl?: H.service.Url): H.service.IConfigurable; + } + + export module MapTileService { + /** + * @property maps {Object} - + * @property schemes {Object} - + * @property tiletypes {Object} - + * @property formats {Object} - + * @property resolutions {Object} - + * @property languages {Object} - + */ + export interface Info { + maps: { [key: string]: any }; + schemes: { [key: string]: any }; + tiletypes: { [key: string]: any }; + formats: { [key: string]: any }; + resolutions: { [key: string]: any }; + languages: { [key: string]: any }; + } + + /** + * @property type {string=} - the type of the map tile service to communicate with, e.g. 'base' (default), 'aerial', etc. (refer to the Map Tile REST API documentation for available types) + * @property version {string=} - the map version hash to use for retrieving tiles, default is newest and will be automatically updated + * @property subDomain {string=} - the sub-domain of the map tile service relative to the platform's base URL, default is 'maps' + * @property path {string=} - the path of the map tile service, default is 'maptile/2.1' + */ + export interface Options { + type?: string; + version?: string; + subDomain?: string; + path?: string; + } + } + + /** + * A map type is an object holding tile layers corresponding to a map type (e.g. 'normal', 'satellite' or 'terrain'). A map type contains at least a map property which defines the basic map layer for a given map type. In addition it can hold other map layers with the given style, e.g. base, xbase, traffic etc. + * @property map {H.map.layer.TileLayer} - the basic map tiles with all features and labels + * @property mapnight {H.map.layer.TileLayer} - the basic map tiles with all features and labels (night mode) + * @property xbase {H.map.layer.TileLayer=} - map tiles without features and labels + * @property xbasenight {H.map.layer.TileLayer=} - map tiles without features and labels (night mode) + * @property base {H.map.layer.TileLayer=} - map tiles without labels + * @property basenight {H.map.layer.TileLayer=} - map tiles without labels (night mode) + * @property traffic {H.map.layer.TileLayer=} - map tiles with traffic flow highlighting + * @property trafficnight {H.map.layer.TileLayer=} - map tiles with traffic flow highlighting (night mode) + * @property transit {H.map.layer.TileLayer=} - map tiles with public transit lines highlighted + * @property panorama {H.map.layer.TileLayer=} - map tiles highlighting areas with HERE StreetLevel coverage + * @property panoramanight {H.map.layer.TileLayer=} - map tiles highlighting areas with HERE StreetLevel coverage (night mode) + * @property labels {H.map.layer.TileLayer=} - transparent map tiles with labels only + */ + export interface MapType { + map: H.map.layer.TileLayer; + mapnight: H.map.layer.TileLayer; + xbase?: H.map.layer.TileLayer; + xbasenight?: H.map.layer.TileLayer; + base?: H.map.layer.TileLayer; + basenight?: H.map.layer.TileLayer; + traffic?: H.map.layer.TileLayer; + trafficnight?: H.map.layer.TileLayer; + transit?: H.map.layer.TileLayer; + panorama?: H.map.layer.TileLayer; + panoramanight?: H.map.layer.TileLayer; + labels?: H.map.layer.TileLayer; + } + + /** + * Places service implements a low level places RestApi access. Please refer to Restful API documentation for providing parameters and handling response objects. + */ + export class PlacesService extends H.service.AbstractRestService { + /** + * Constructor + * @param opt_options {H.service.PlacesService.Options=} + */ + constructor(opt_options?: H.service.PlacesService.Options); + + /** + * This is generic method to query places RestAPI. + * @param entryPoint {string} - can be one of available entry points H.service.PlacesService.EntryPoint i.e value of H.service.PlacesService.EntryPoint.SEARCH + * @param entryPointParams {Object} - parameter map key value pairs will be transformed into the url key=value parametes. For entry point parameters description please refer to places restful api documentation documentation for available parameters for chose entry point + * @param onResult {Function} - callback which is called when result is returned + * @param onError {Function} - callback which is called when error occured (i.e request timeout) + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + request(entryPoint: string, entryPointParams: Object, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'search' entry point. Please refer to documentation for parameter specification and response handling. + * @param searchParams {H.service.ServiceParameters} - places api search entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + search(searchParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'suggestions' entry point. Please refer to documentation for parameter specification and response handling. + * @param suggestParams {H.service.ServiceParameters} - places api suggest entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + suggest(suggestParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'explore' entry point. Please refer to documentation for parameter specification and response handling. + * @param exploreParams {H.service.ServiceParameters} - places api explore entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + explore(exploreParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'around' entry point. Please refer to documentation for parameter specification and response handling. + * @param aroundParams {H.service.ServiceParameters} - places api around entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + around(aroundParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'here' entry point. Please refer to documentation for parameter specification and response handling. + * @param hereParams {H.service.ServiceParameters} - places api here entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + here(hereParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'categories' entry point. Please refer to documentation for parameter specification and response handling. + * @param categoriesParams {H.service.ServiceParameters} - places api here entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + categories(categoriesParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * This method should be used to follow hyperlinks available in results returned by dicovery queries. + * @param hyperlink {string} + * @param onResult {Function} + * @param onError {Function} + * @param opt_additionalParameters {Object=} - additional parameters to send with request + * @returns {H.service.JsonpRequestHandle} - jsonp resquest handle + */ + follow(hyperlink: string, onResult: Function, onError: Function, opt_additionalParameters?: Object): H.service.JsonpRequestHandle; + } + + export module PlacesService { + /** + * List of available entry points + */ + export enum EntryPoint { + SEARCH, + SUGGEST, + EXPLORE, + AROUND, + HERE, + CATEGORIES, + } + + /** + * @property subDomain {string=} - the sub-domain of the places service relative to the platform's base URL, default is 'places' + * @property path {string=} - the path of the places service, default is 'places/v1' + * @property baseUrl {H.service.Url=} - an optional base URL if it differs from the platform's default base URL + */ + export interface Options { + subDomain?: string; + path?: string; + baseUrl?: H.service.Url; + } + } + + /** + * The Platform class represents central class from which all other service stubs are created. It also contains the shared settings to be passed to the individual service stubs, for example the root URL of the platform, application credentials, etc. + */ + export class Platform { + /** + * Constructor + * @param options {H.service.Platform.Options} + */ + constructor(options: H.service.Platform.Options); + + /** + * Method attempts to configure object that implements H.service.IConfigurable + * @param configurable {H.service.IConfigurable} + * @returns {H.service.IConfigurable} + */ + configure(configurable: H.service.IConfigurable): H.service.IConfigurable; + + /** + * This method enables or disables HTTPS communication with the platform + * @param useHTTPS {boolean} - a boolean value indicating whether to communicate with the platform via HTTPS + */ + setUseHTTPS(useHTTPS: boolean): void; + + /** + * This method configures whether to use the "customer integration testing" instance of the platform. + * @param useCIT {boolean} - a boolean value indicating whether the CIT platform instance is to be used + */ + setUseCIT(useCIT: boolean): void; + + /** + * This method modifies the base URL to be used when creating service stubs. + * @param baseUrl {H.service.Url} - the new base URL to use + */ + setBaseUrl(baseUrl: H.service.Url): void; + + /** + * This method returns the currently used base URL. + * @returns {H.service.Url} + */ + getBaseUrl(): H.service.Url; + + /** + * This method returns an instance of H.service.TrafficIncidentsService to query the Traffic API Traffic Incident Data + * @returns {H.service.TrafficIncidentsService} - a new places service instance + */ + getTrafficIncidentsService(): H.service.TrafficIncidentsService; + + /** + * This method returns an instance of H.service.MapTileService to query the Map Tile API. + * @param opt_options {H.service.MapTileService.Options=} + * @returns {H.service.MapTileService} + */ + getMapTileService(opt_options?: H.service.MapTileService.Options): H.service.MapTileService; + + /** + * This method returns an instance of H.service.venues.Service to query the Venue Maps API + * @param opt_params {H.service.venues.Service.Options=} - additional service parameters + * @returns {H.service.venues.Service} + */ + getVenueService(opt_params?: H.service.venues.Service.Options): H.service.venues.Service; + + /** + * This method returns an instance of H.service.metaInfo.Service to query the Map Tile API Metainfo Tiles + * @param opt_params {H.service.metaInfo.Service.Options=} - additional service parameters + * @returns {H.service.metaInfo.Service} + */ + getMetaInfoService(opt_params?: H.service.metaInfo.Service.Options): H.service.metaInfo.Service; + + /** + * This method creates a pre-configured set of HERE tile layers for convenient use with the map. + * @param opt_tileSize {(H.service.Platform.DefaultLayersOptions | number)=} - When a number – optional tile size to be queried from the HERE Map Tile API, default is 256. If the parameter is an object, then it represents options and all remaining below parameters should be omitted. + * @param opt_ppi {number=} - optional 'ppi' parameter to use when querying tiles, default is not specified + * @param opt_lang {string=} - optional primary language parameter, default is not specified + * @param opt_secondaryLang {string=} - optional secondary language parameter, default is not specified + * @param opt_style {string=} - optional 'style' parameter to use when querying map tiles, default is not specified + * @param opt_pois {(string | boolean)=} - indicates if pois are displayed on the map. Pass true to indicate that all pois should be visible. Alternatively you can specify mask for the POI Categories as described at the Map Tile API documentation POI Categories chapter. + * @returns {Object} - a set of tile layers ready to use + */ + createDefaultLayers(opt_tileSize?: (H.service.Platform.DefaultLayersOptions | number), opt_ppi?: number, opt_lang?: string, opt_secondaryLang?: string, opt_style?: string, opt_pois?: (string | boolean)): H.service.Platform.MapTypes; + + /** + * This method returns an instance of H.service.RoutingService to query the Routing API. + * @param opt_options {H.service.RoutingService.Options=} + * @returns {H.service.RoutingService} + */ + getRoutingService(opt_options?: H.service.RoutingService.Options): H.service.RoutingService; + + /** + * This method returns an instance of H.service.GeocodingService to query the Geocoder API + * @param opt_options {H.service.GeocodingService.Options=} - an optional set of options for the new geocoding service to connect to + * @returns {H.service.GeocodingService} - a new geocoding service instance + */ + getGeocodingService(opt_options?: H.service.GeocodingService.Options): H.service.GeocodingService; + + /** + * This method returns an instance of H.service.PlacesService to query the Places API. + * @returns {H.service.PlacesService} - a new places service instance + */ + getPlacesService(): H.service.PlacesService; + + /** + * This method returns an instance of H.service.EnterpriseRoutingService to query the Enterprise Routing API. + * @param opt_options {H.service.EnterpriseRoutingService.Options=} + * @returns {H.service.EnterpriseRoutingService} + */ + getEnterpriseRoutingService(opt_options?: H.service.EnterpriseRoutingService.Options): H.service.EnterpriseRoutingService; + } + + export module Platform { + /** + * Options used to create default layers + * @property tileSize {number=} - tile size to be queried from the HERE Map Tile API, default is 256 + * @property ppi {number=} - 'ppi' parameter to use when querying tiles, default is not specified + * @property lg {string=} - optional primary language parameter, default is not specified + * @property lg2 {string=} - optional secondary language parameter, default is not specified + * @property style {string=} - optional 'style' parameter to use when querying map tiles, default is not specified + * @property pois {boolean=} - indicates if pois are displayed on the map + * @property crossOrigin {(string | boolean=)} - indicates if CORS headers should be used for default layers, if false is specified, CORS headers are not set, defaults to 'anonymous'. Be aware that storing of content is not possible if crossOrigin is not set to true (see H.Map#storeContent). + */ + export interface DefaultLayersOptions { + tileSize?: number; + ppi?: number; + lg?: string; + lg2?: string; + style?: string; + pois?: boolean; + crossOrigin?: (string | boolean); + } + + /** + * @property app_id {string} - The application ID to identify the client against the platform (mandatory to provide) + * @property app_code {string} - The application code to identify the client against the platform (mandatory to provide) + * @property baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com + * @property useCIT {boolean=} - Indicates whether the Customer Integration Testing should be used, default is false + * @property useHTTPS {boolean=} - Indicates whether secure communication should be used, default is false + */ + export interface Options { + app_id: string; + app_code: string; + baseUrl?: H.service.Url; + useCIT?: boolean; + useHTTPS?: boolean; + } + + /** + * pre-configured set of HERE tile layers for convenient use with the map. + */ + export interface MapTypes { + normal?: H.service.MapType; + satellite?: H.service.MapType; + terrain?: H.service.MapType; + [key: string]: H.service.MapType; + } + } + + /** + * This class encapsulates the Routing REST API as a service stub. An instance of this class can be retrieved by calling the factory method on a platform instance. H.service.Platform#getRoutingService. + */ + export class RoutingService extends H.service.AbstractRestService { + /** + * Constructor + * @param opt_options {H.service.RoutingService.Options=} + */ + constructor(opt_options?: H.service.RoutingService.Options); + + /** + * This method sends a "calculateroute" request to Routing REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occured. + * @param calculateRouteParams {H.service.ServiceParameters} - the service parameters to be sent with the routing request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Routing REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + */ + calculateRoute(calculateRouteParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): void; + } + + export module RoutingService { + /** + * @property subDomain {string=} - the sub-domain of the routing service relative to the platform's base URL, default is 'route' + * @property path {string=} - the path of the map tile service, default is 'routing/7.2' + * @property baseUrl {H.service.Url=} - an optional base URL if it differs from the platform's default base URL + */ + export interface Options { + subDomain?: string; + path?: string; + baseUrl?: H.service.Url; + } + } + + /** + * This type encapsulates URL parameters to be sent to a HERE platform service. + */ + export interface ServiceParameters { + [key: string]: string; + } + + /** + * This type encapsulates a response object provider by a HERE platform service. + */ + export interface ServiceResult { + [key: string]: string; + } + + /** + * Options which are used to initialize the tile provider. + * @property crossOrigin {boolean=} - The string to be set for the crossOrigin attribute for loaded images + */ + export interface TileProviderOptions { + crossOrigin?: boolean; + } + + /** + * TrafficIncindentsService provides functionality to the low level traffic incidents api Traffic API documentation where it is possible to retrieve traffic incident information on a tile basis + */ + export class TrafficIncidentsService extends H.service.AbstractRestService { + /** + * Constructor + * @param opt_options {H.service.TrafficIncidentsService.Options=} + */ + constructor(opt_options?: H.service.TrafficIncidentsService.Options); + + /** + * This method requests traffic incidents based on the service parameters provided. + * @param serviceParams {H.service.ServiceParameters} + * @param onResponse {function(H.service.ServiceResult)} + * @param onError {function()} + * @returns {H.service.JsonpRequestHandle} + */ + requestIncidents(serviceParams: H.service.ServiceParameters, onResponse: (result: H.service.ServiceResult) => void, onError: () => void): H.service.JsonpRequestHandle; + + /** + * This method requests traffic incident information by tile coordinates + * @param x {number} - tile column number + * @param y {number} - tile row number + * @param z {number} - zoom level + * @param onResponse {function(H.service.ServiceResult)} - callback to handle service resposne + * @param onError {function()} - callback to habdle communication error + * @param opt_serviceParams {H.service.ServiceParameters=} - optional service parameters to be added to the request + * @returns {H.service.JsonpRequestHandle} + */ + requestIncidentsByTile(x: number, y: number, z: number, onResponse: (result: H.service.ServiceResult) => void, onError: () => void, opt_serviceParams?: H.service.ServiceParameters): H.service.JsonpRequestHandle; + } + + export module TrafficIncidentsService { + /** + * @property subDomain {string=} - the sub-domain of the traffic incidents service relative to the platform's base URL, default is 'traffic' + * @property path {string=} - the path of the traffic incidents service, default is 'traffic/6.1' + * @property baseUrl {H.service.Url=} - an optional base URL if it differs from the platform's default base URL + */ + export interface Options { + subDomain?: string; + path?: string; + baseUrl?: H.service.Url; + } + } + + /** + * This class represents a URL giving access to the individual parts that make up a URL,such as the scheme, host/domain, path, etc. Use the static parse method to populate a new URL object from a URL string. Be aware that URLs with user and password like "ftp://user:password@foo.bar/" are not supported! + */ + export class Url { + /** + * Constructor + * @param scheme {string} - the URL scheme (e.g. "http" or "https" or "mailto") + * @param host {string} - the host (or domain) part of the URL + * @param opt_path {string=} - the path following the host pointing to a resource + * @param opt_params {Object=} - the query string parameters of this URL + * @param opt_port {number=} - The port of the host on which the host listens. If a string is passed it must be convertible to an integer. + * @param opt_anchor {string=} - an optional anchor part of the URL (usually preceded by '#'); + */ + constructor(scheme: string, host: string, opt_path?: string, opt_params?: Object, opt_port?: number, opt_anchor?: string); + + /** + * This function parses a URL string and returns a H.service.Url object. The URL string must contain at least a scheme and a host. + * @param url {string} - The URL string to parse. + * @param opt_baseURL {string=} - The base URL to use to resolve relative URLs. If ommited the base URL of the document which loaded the API is taken. + * @returns {H.service.Url} - the parsed URL object + */ + static parse(url: string, opt_baseURL?: string): H.service.Url; + + /** + * Clones this URL object. Optionally, mutations can be passed to this function to modify properties of the cloned object. Note that URL parameters are not replaced but merged with the parameters of this instance. + * @returns {H.service.Url} - the clone of the URL object + */ + clone(): H.service.Url; + + /** + * This function sets the scheme of this URL object. + * @param scheme {string} - the new scheme + * @returns {H.service.Url} - this URL object + */ + setScheme(scheme: string): H.service.Url; + + /** + * This function returns the scheme of this Url object. + * @returns {string} - the scheme (for example 'http') + */ + getScheme(): string; + + /** + * This function sets the host of this URL object. + * @param host {string} - the new host + * @returns {H.service.Url} - this URL object + */ + setHost(host: string): H.service.Url; + + /** + * This function returns the host name of this Url object. + * @returns {string} - the host (for example 'api.here.com') + */ + getHost(): string; + + /** + * This function sets the path of this URL object. + * @param path {(string | undefined)} - the new path or a boolean to clear the path + * @returns {H.service.Url} - this URL object + */ + setPath(path: string | boolean): H.service.Url; + + /** + * This function returns the path part of this Url object. + * @returns {(string | undefined)} - the path (for example 'myresources/resource.html') + */ + getPath(): string | void; + + /** + * This function sets the specified parameters for this URL object. Keys in this object, which are associated with undefined values will be treated as query string parameters with no value. + * @param params {(Object | undefined)} - a hash of query string parameters specifying the parameters to be set.or a boolean to clear the parameters. + * @returns {H.service.Url} - this URL object + */ + setQuery(params?: Object | boolean): H.service.Url; + + /** + * This function returns a boolean value indicating whether there are any query string parameter associated with this URL. + * @returns {boolean} - true if there are parameters, false if none are present + */ + hasQuery(): boolean; + + /** + * This function returns the query object of this Url object. + * @returns {Object} - the query object + */ + getQuery(): Object; + + /** + * This function sets the anchor of this URL object. + * @param anchor {(string | boolean | undefined)} - the new anchor or undefined to clear the anchor + * @returns {H.service.Url} - this URL object + */ + setAnchor(anchor?: string | boolean): H.service.Url; + + /** + * This function returns the anchor of this Url object. + * @returns {(string | undefined)} - the anchor + */ + getAnchor(): string | void; + + /** + * This function merges the provided parameters into this URL's existing parameters. Key-value pairs which are defined in the argument and this URL's parameters will be overwritten. Key-value pairs which are defined in the argument and are not defined in this URL's parameters will be added. Prototype properties and function properties will not be merged. + * @param other {Object} - the parmeters to be merged into this URL's query string parameters + * @returns {H.service.Url} - this URL object + */ + mergeQuery(other: Object): H.service.Url; + + /** + * This function adds a sub-domain to the host of this URL object. + * @param subDomain {string} - the sub domain (non-empty string) to be added + * @returns {H.service.Url} - this URL object + */ + addSubDomain(subDomain: string): H.service.Url; + + /** + * This function adds a sub-path to this URL's path + * @param subPath {string} - the path to be added + * @returns {H.service.Url} - this URL object + */ + addSubPath(subPath: string): H.service.Url; + + /** + * This function formats this URL object to a full URL string. + * @returns {string} - the URL's string representation + */ + toString(): string; + } + + export module metaInfo { + /** + * This class encapsulates a Metainfo Tile end point of the HERE Map Tile API. + */ + export class Service extends H.util.EventTarget implements H.service.IConfigurable { + /** + * Constructor + * @param opt_options {H.service.metaInfo.Service.Options=} - additional service parameters + */ + constructor(opt_options?: H.service.metaInfo.Service.Options); + + /** + * This method returns the meta info tile service's newest version hash. + * @returns {string} - meta information for this map tile service + */ + getVersion(): string; + + /** + * This method returns the meta info tile service's meta information. The method will return an object once the map tile service's data has been fetched. + * @returns {(H.service.metaInfo.Service.Info | undefined)} - meta information for this meta info tile service + */ + getInfo(): H.service.metaInfo.Service.Info | void; + + /** + * This method creates a tile provider which uses the meta info tile backend. This provider can be used as a data source for an TileLayer. + * @param tileSize {number} - The tile size + * @param pixelRatio {number} - The tile's pixel ratio, should be aligned with base map tile + * @param opt_categoryFilter {Array=} - A list of meta-info category names which should be suppressed. See Metainfo Tile for valid category names. + * @param opt_additionalParameters {H.service.ServiceParameters=} - Additional parameters for the meta info service + * @param opt_tileType {string=} - the tile type (default is 'maptile') + * @param opt_scheme {string=} - the scheme for which the meta info tiles a requested (default is 'normal.day') + * @returns {H.map.provider.TileProvider} - the tile provider + */ + createTileProvider(tileSize: number, pixelRatio: number, opt_categoryFilter?: Array, opt_additionalParameters?: H.service.ServiceParameters, opt_tileType?: string, opt_scheme?: string): H.map.provider.TileProvider; + + /** + * This method creates a tile layer. This layer can be used as a layer on a map's data model. + * @param tileSize {number} - The tile size + * @param pixelRatio {number} - The tile's pixel ratio, should be aligned with base map tile + * @param opt_categoryFilter {Array=} - A list of meta-info category names which should be suppressed. See Metainfo Tile for valid category names. + * @param opt_additionalParameters {H.service.ServiceParameters=} - Additional parameters for the meta info service + * @param opt_tileType {string=} - the tile type (default is 'maptile') + * @param opt_scheme {string=} - the scheme for which the meta info tiles a requested (default is 'normal.day') + * @returns {H.map.layer.TileLayer} - the tile layer + */ + createTileLayer(tileSize: number, pixelRatio: number, opt_categoryFilter?: Array, opt_additionalParameters?: H.service.ServiceParameters, opt_tileType?: string, opt_scheme?: string): H.map.layer.TileLayer; + + /** + * This methods receive configuration parameters from the platform, that can be used by the object implementing the interface. + * @param appId {string} - The application ID to identify the client against the platform (mandatory to provide) + * @param appCode {string} - The application code to identify the client against the platform (mandatory to provide) + * @param useHTTPS {boolean} - Indicates whether secure communication should be used, default is false + * @param useCIT {boolean} - Indicates whether the Customer Integration Testing should be used, default is false + * @param opt_baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com. Note that if useHTTPS flag is passed it will override the URL scheme specified in the opt_baseUrl to use HTTPS. + * @returns {H.service.IConfigurable} + */ + configure(appId: string, appCode: string, useHTTPS: boolean, useCIT: boolean, opt_baseUrl?: H.service.Url): H.service.IConfigurable; + } + + export module Service { + /** + * @property maps {Object} - + * @property schemes {Object} - + * @property tiletypes {Object} - + * @property formats {Object} - + * @property resolutions {Object} - + * @property languages {Object} - + */ + export interface Info { + maps: { [key: string]: any }; + schemes: { [key: string]: any }; + tiletypes: { [key: string]: any }; + formats: { [key: string]: any }; + resolutions: { [key: string]: any }; + languages: { [key: string]: any }; + } + + /** + * @property type {string=} - the type of the map tile service to communicate with, e.g. 'base' (default), 'aerial', etc. (refer to the Map Tile REST API documentation for available types) + * @property version {string=} - the map version hash to use for retrieving tiles, default is newest and will be automatically updated + * @property subDomain {string=} - the sub-domain of the map tile service relative to the platform's base URL, default is 'maps' + */ + export interface Options { + type?: string; + version?: string; + subDomain?: string; + } + } + + /** + * This class utilizes Metainfo Tiles functionality provided by the Map Tile API to load meta information about map objects (buildings, labels, public transport etc.). + */ + export class TileProvider extends H.map.provider.RemoteTileProvider { + /** + * Constructor + * @param service {(H.service.metaInfo.Service | H.service.MapTileService)} - the tile service which holds information from about the source of the tiles + * @param opt_params {H.service.ServiceParameters=} - an additional set of URL parameters + * @param opt_options {H.service.metaInfo.TileProvider.Options=} - additional parameters + */ + constructor(service: (H.service.metaInfo.Service | H.service.MapTileService), opt_params?: H.service.ServiceParameters, opt_options?: H.service.metaInfo.TileProvider.Options); + } + + export module TileProvider { + /** + * Configuration object which can be used to initialize the TileProvider. + * @property tileType {string=} - The tile type for which to request meta info + * @property scheme {string=} - The map scheme for which to request meta info + * @property tileCacheSize {number=} - The number of fully rendered spatial tiles that are cached for immediate reuse, default is 32 + * @property tileSize {number=} - The size of the tiles rendered by this provider (must be power of 2, default is 256) + * @property pixelRatio {number=} - The pixel ratio to use for over-sampling in cases of high-resolution displays + * @property categoryFilter {Array=} - A list of meta-info category names which should be suppressed. See Metainfo Tile for valid category names. + */ + export interface Options { + tileType?: string; + scheme?: string; + tileCacheSize?: number; + tileSize?: number; + pixelRatio?: number; + categoryFilter?: Array; + } + } + } + + export module venues { + /** + * The class represents the building in the venue hiearachy (see H.service.venues.Venue) and holds floors that belong to the building. + */ + export class Building extends H.map.Group { + /** + * Constructor + * @param provider {H.map.provider.ObjectProvider} - The object provider of this venue building + * @param uid {string} - The unique identifier of this building + * @param minLevel {number} - The minimum floor level of this building + * @param maxLevel {number} - The maximum floor level of this building + */ + constructor(provider: H.map.provider.ObjectProvider, uid: string, minLevel: number, maxLevel: number); + + /** + * Method returns the parent object - venue (see H.service.venues.Venue) to which the building belongs to. + * @returns {H.service.venues.Venue} + */ + getVenue(): H.service.venues.Venue; + + /** + * Method returns the minimum floor level of this building. + * @returns {number} + */ + getMinLevel(): number; + + /** + * Method returns the maximum floor level of this building + * @returns {number} + */ + getMaxLevel(): number; + + /** + * Method returns the floor (see H.service.venues.Floor) if one was already loaded. This method doesn't make attempt to fetch the floor data. + * @param level {number} - floor level within minimum and maximum level boundaries for the building + * @returns {(H.service.venues.Floor | undefined)} - The floor object or undefined if floor was not loaded + */ + getFloor(level: number): H.service.venues.Floor | void; + } + + /** + * The class represents the floor object in the venue hierarchy (see H.service.venues.Venue). The class holds information about floor geometry and spaces (see H.service.venues.Space) that belong to this floor. + */ + export class Floor extends H.map.Group { + /** + * Constructor + * @param provider {H.map.provider.ObjectProvider} - The object provider of this venue floor + * @param data {*} - The meta data of this floor + * @param level {number} - The level of this floor + */ + constructor(provider: H.map.provider.ObjectProvider, data: any, level: number); + + /** + * Method returns the level of the floor in the building. + * @returns {number} + */ + getLevel(): number; + + /** + * Method returns map geometry that represents floor boundaries. + * @returns {(H.service.venues.Space | undefined)} + */ + getFloorSpace(): H.service.venues.Space | void; + + /** + * Method returns the H.map.Group of all spaces that belong to the floor. + * @returns {H.map.Group} + */ + getSpaces(): H.map.Group; + + /** + * Method returns parent object - building (see H.service.venues.Building) of the floor. + * @returns {H.service.venues.Building} + */ + getBuilding(): H.service.venues.Building; + + /** + * Method returns raw data associated with the floor. For more details on data format see http://developer.here.com/rest-apis/documentation/venue-maps/topics/resource-type-venue-interaction-tile-floor.html + * @returns {*} - the raw floor data object + */ + getData(): any; + + /** + * Method returns the space object with the given ID, that belongs to the floor. + * @param id {string} - The ID of the space. + * @returns {(H.service.venues.Space | undefined)} - The requested space or undefined if space not found. + */ + getSpace(id: string): H.service.venues.Space | void; + } + + /** + * This class encapsulates methods to call Venue Maps API endpoints. + */ + export class Service extends H.util.EventTarget implements H.service.IConfigurable { + /** + * Constructor + * @param opt_options {H.service.venues.Service.Options=} - additional service parameters + */ + constructor(opt_options?: H.service.venues.Service.Options); + + /** + * This method sends a discovery request to the Venue Maps API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object, or the onError callback if a communication error occured. + * @param serviceParams {H.service.ServiceParameters} - the service parameters to be sent with the discovery request + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Venue Maps API provides a response to the request + * @param onError {function(string)} - this function will be called if a communication error occurs during request and error type is passed as an argument + */ + discover(serviceParams: H.service.ServiceParameters, onResult: (res: H.service.ServiceResult) => void, onError: (s: string) => void): void; + + /** + * This method creates a tile layer which can be added to the map in order to see the venues. It uses Interaction Tile endpoint of the Venue Maps API, more at http://developer.here.com/rest-apis/documentation/venue-maps/topics/quick-start-get-interaction-tile.html. + * @param opt_options {H.service.venues.TileProvider.Options=} - Tile provider options + * @returns {H.map.layer.TileLayer} - the tile layer + */ + createTileLayer(opt_options?: H.service.venues.TileProvider.Options): H.map.layer.TileLayer; + + /** + * Method returns current state of the service. + * @returns {H.service.venues.Service.State} - State of the service + */ + getState(): H.service.venues.Service.State; + + /** + * This methods receive configuration parameters from the platform, that can be used by the object implementing the interface. + * @param appId {string} - The application ID to identify the client against the platform (mandatory to provide) + * @param appCode {string} - The application code to identify the client against the platform (mandatory to provide) + * @param useHTTPS {boolean} - Indicates whether secure communication should be used, default is false + * @param useCIT {boolean} - Indicates whether the Customer Integration Testing should be used, default is false + * @param opt_baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com. Note that if useHTTPS flag is passed it will override the URL scheme specified in the opt_baseUrl to use HTTPS. + * @returns {H.service.IConfigurable} + */ + configure(appId: string, appCode: string, useHTTPS: boolean, useCIT: boolean, opt_baseUrl?: H.service.Url): H.service.IConfigurable; + } + + export module Service { + /** + * @property subDomain {string=} - the sub-domain of the Venue Maps service relative to the platform's base URL, default is 'venue.maps' + * @property path {string=} - the path to append after host name when making requests to the Venue Maps API, default is empty + */ + export interface Options { + subDomain?: string; + path?: string; + } + + /** + * The state types of the H.service.venues.Service. Possible states are: + */ + export enum State { + ERROR, + INIT, + READY, + } + } + + /** + * Represents a spatial object for this space. Each space object contains data associated with that space and can be retrieved by using H.service.venues.Space#getData method. + */ + export class Space { + /** + * Constructor + * @param provider {H.map.provider.ObjectProvider} - The provider of this object. + * @param uid {string} - The unique identifier of this space + * @param data {*} - The meta data of this space + * @param opt_isFloorSpace {boolean=} - Indicates whether this space represents a floor itself, defaults to false + */ + constructor(provider: H.map.provider.ObjectProvider, uid: string, data?: any, opt_isFloorSpace?: boolean); + + /** + * The method indicates whether the spatial object represents the whole floor space or a space within a floor boundaries, that belongs to the floor. + * @returns {boolean} - True if this spatial object represents the floor space. + */ + isFloorSpace(): boolean; + + /** + * This method sets custom style to use for rendering the labels. Should be called before the first render of the space, otherwise has no any effect. Note that due to the design consistency currently it is not allowed to change the font family and the size of the labels. + * @param labelStyle {(H.map.SpatialStyle | H.map.SpatialStyle.Options)} - Custom label style + */ + initLabelStyle(labelStyle: (H.map.SpatialStyle | H.map.SpatialStyle.Options)): void; + + /** + * Method returns parent object - floor (see H.service.venues.Floor) of the space. + * @returns {H.service.venues.Floor} + */ + getFloor(): H.service.venues.Floor; + + /** + * Method returns raw data associated with the space. For more details on data format see http://developer.here.com/rest-apis/documentation/venue-maps/topics/resource-type-venue-interaction-tile-space.html + * @returns {Object} - raw space data object + */ + getData(): Object; + } + + /** + * This class represents a Venue Maps tile provider which requests venues tiles from a platform venue tile service. + */ + export class TileProvider extends H.map.provider.RemoteTileProvider { + /** + * Constructor + * @param service {H.service.venues.Service} + * @param opt_options {H.service.venues.TileProvider.Options=} + */ + constructor(service: H.service.venues.Service, opt_options?: H.service.venues.TileProvider.Options); + + /** + * Method specifies which floor level of the venues must be fetched by provider. Floor level is global to all venues and defaults to 0. + * @param level {number} + */ + setCurrentLevel(level: number): void; + + /** + * Method returns the floor level that provider uses for tile fetching. + * @returns {number} - current provider's floor level + */ + getCurrentLevel(): number; + } + + export module TileProvider { + /** + * Configuration object which can be used to initialize the TileProvider. + * @property tileCacheSize {number=} - The number of fully rendered spatial tiles that are cached for immediate reuse, default is 32 + * @property pixelRatio {number=} - The pixel ratio to use for over-sampling in cases of high-resolution displays + * @property onSpaceCreated {function(H.service.venues.Space)=} - A callback function that is called on every created space (see H.service.venues.Space) object. The function can be used for space object styling. + */ + export interface Options { + tileCacheSize?: number; + pixelRatio?: number; + onSpaceCreated?: (space: H.service.venues.Space) => void; + } + } + + /** + * The class represents the venue, it is a root for the venue object heirarchy. The venue inherits from H.map.Group and holds building objects (see H.service.venues.Building). Building objects hold floor objects (see H.service.venues.Floor) and inherit from H.map.Group as well. Leaf objects are spaces (see H.service.venues.Space) that are spatial map objects and reside inside floor containers. + */ + export class Venue extends H.map.Group { + /** + * Constructor + * @param provider {H.map.provider.ObjectProvider} - The object provider of this venue + * @param uid {string} - The unique identifier of this venue + */ + constructor(provider: H.map.provider.ObjectProvider, uid: string); + + /** + * Method returns the building object, that belongs to the venue, with the given ID . The method doesn't attempt to fetch building data. + * @param id {string} - the ID of the building + * @returns {(H.service.venues.Building | undefined)} - The requested building or undefined if building wasn't loaded + */ + getBuilding(id: string): H.service.venues.Building | void; + + /** + * Method returns map of all loaded buildings associated with the venue. + * @returns {Object<*, H.service.venues.Building>} + */ + getBuildings(): any; + } + } + } + + /***** ui *****/ + export module ui { + /** + * This class represents the base class for UI controls on the map. + */ + export class Control extends H.ui.base.Container { + /** + * This abstract method can be overridden by deriving classes to be invoked when the UI object's unit system changes. + * @param unitSystem {H.ui.UnitSystem} - the unit system the UI currently uses + */ + onUnitSystemChange(unitSystem: H.ui.UnitSystem): void; + + /** + * This abstract method can be overridden by deriving classes to be invoked when the underlying map engine changes. + * @param engineType {H.Map.EngineType} - the engine type the map currently uses + */ + onMapEngineTypeChange(engineType: H.Map.EngineType): void; + + /** + * This method returns the map to which this control is attached. + * @returns {?H.Map} - return the map + */ + getMap(): H.Map; + + /** + * This method returns the localization object which corresponds to the UI's current locale. + * @returns {H.ui.i18n.Localization} + */ + getLocalization(): H.ui.i18n.Localization; + + /** + * This method returns this control's layout alignment. + * @returns {H.ui.LayoutAlignment} - the control's current layout alignment + */ + getAlignment(): H.ui.LayoutAlignment; + + /** + * This method sets the control's layout alignments. + * @param alignment {H.ui.LayoutAlignment} - The new alignment of the control + * @returns {H.ui.Control} - returns this control instance + */ + setAlignment(alignment: H.ui.LayoutAlignment): H.ui.Control; + } + + /** + * This class represents a distance measurement control which helps calculating distances between geographical locations indicated by the user clicks. + */ + export class DistanceMeasurement extends H.ui.Control { + /** + * Constructor + * @param opt_options {H.ui.DistanceMeasurement.Options=} - optional parameters to be passed to this control + */ + constructor(opt_options?: H.ui.DistanceMeasurement.Options); + } + + export module DistanceMeasurement { + /** + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, default is H.ui.LayoutAlignment.RIGHT_BOTTOM + * @property startIcon {H.map.Icon=} - the icon to use for the first measurement point + * @property stopoverIcon {H.map.Icon=} - the icon to use for the intermediate measurement points + * @property endIcon {H.map.Icon=} - the icon to use for the last measurement point + * @property splitIcon {H.map.Icon=} - the icon to use for indicating position under pointer over the line where new point will be created once user clicks + * @property lineStyle {(H.map.SpatialStyle | H.map.SpatialStyle.Options)} - the style to use for connecting lines of the measurement points + * @property distanceFormatter {function(number)=} - Optional function used for formatting a distance. By default distance measurement tool will do the formatting according to the specified measurement unit (see H.ui.UI.Options#unitSystem) + */ + export interface Options { + alignment?: H.ui.LayoutAlignment; + startIcon?: H.map.Icon; + stopoverIcon?: H.map.Icon; + endIcon?: H.map.Icon; + splitIcon?: H.map.Icon; + lineStyle: H.map.SpatialStyle | H.map.SpatialStyle.Options; + distanceFormatter?(n: number): void; + } + } + + /** + * This class represents an information bubble bound to a geo-position on the map. + */ + export class InfoBubble extends base.Element { + /** + * Constructor + * @param position {H.geo.IPoint} - the geo-position to which this info bubble corresponds + * @param opt_options {H.ui.InfoBubble.Options=} - optional parameters to be passed to the info bubble + */ + constructor(position: H.geo.IPoint, opt_options?: InfoBubble.Options); + + /** + * This method sets the geo-position of this info bubble + * @param position {(H.geo.IPoint | H.geo.Point)} - the new geo-position of this bubble + */ + setPosition(position: H.geo.IPoint | H.geo.Point): void; + + /** + * This method returns this info bubble's current state. + * @returns {H.ui.InfoBubble.State} - this bubble's current state + */ + getState(): InfoBubble.State; + + /** + * This method sets the info bubble's state. + * @param state {H.ui.InfoBubble.State} - the new state + */ + setState(state: InfoBubble.State): void; + + /** + * This method closes the info bubble (setting its state to CLOSED) + */ + close(): void; + + /** + * This method opens the info bubble (setting its state to OPEN) + */ + open(): void; + + /** + * This method returns the bubble's content element. + * + * Note: Before adding an info bubble to a UI object the content element is null. + * @returns {?HTMLElement} - the content element of this info bubble + */ + getContentElement(): HTMLElement; + + /** + * This methods sets the content of the info bubble. This can either be a string (applied as innerHTML) to the content element of this info bubble or a HTML node which is appended to the content element. + * @param content {(string | Node)} - the content for this bubble + */ + setContent(content: string | Node): void; + } + + export module InfoBubble { + /** + * This enumeration holds the state an info bubble can have. + */ + export enum State { + /** This value represents the state where an info bubble is open and visible (value: 'open'). */ + OPEN, + /** This value represents the state where an info bubble is closed and invisible (value: 'closed') */ + CLOSED, + } + + export interface Options { + /** + * a callback to be invoked when the info bubble's state changes + * @param event {H.util.Event} + */ + onStateChange?(event: H.util.Event): void; + + /** + * content to be added to the info bubble + */ + content: string | Node; + } + } + + /** + * This enumeration holds the possible layout alignments for the UI elements. + */ + export enum LayoutAlignment { + TOP_LEFT, + TOP_CENTER, + TOP_RIGHT, + LEFT_TOP, + LEFT_MIDDLE, + LEFT_BOTTOM, + RIGHT_TOP, + RIGHT_MIDDLE, + RIGHT_BOTTOM, + BOTTOM_LEFT, + BOTTOM_CENTER, + BOTTOM_RIGHT, + } + + /** + * This class represents a menu control allowing to control which map type the map shows, etc. + */ + export class MapSettingsControl extends H.ui.Control { + /** + * Constructor + * @param opt_options {H.ui.MapSettingsControl.Options=} - optional parameters to be passed to this control + */ + constructor(opt_options?: H.ui.MapSettingsControl.Options); + + /** + * Sets the traffic incidents layer to be shown when activating the respective button on the map settings control. + * @param incidentsLayer {H.map.layer.Layer} - the incidents layer + */ + setIncidentsLayer(incidentsLayer: H.map.layer.Layer): void; + } + + export module MapSettingsControl { + /** + * The map type entry is an object containing a display name and a map type object to which it refers. + * @property name {string} - label which describes the map type + * @property mapType {H.service.MapType} - reference to map type + */ + export interface MapTypeEntry { + name: string; + mapType: H.service.MapType; + } + + /** + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, default is H.ui.LayoutAlignment.BOTTOM_RIGHT + * @property entries {Array=} - the map type entries to be shown in this map settings control + * @property incidents {H.map.layer.Layer} - the traffic incidents layer to be activated by the map settings control + */ + export interface Options { + alignment?: H.ui.LayoutAlignment; + entries?: Array; + incidents: H.map.layer.Layer; + } + } + + /** + * This class represents the UI controls for panorama + */ + export class Pano extends H.ui.Control { + /** + * Constructor + * @param opt_options {H.ui.Pano.Options=} - optional parameters to be passed to the map. + */ + constructor(opt_options?: H.ui.Pano.Options); + } + + export module Pano { + /** + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, default is H.ui.LayoutAlignment.RIGHT_BOTTOM + * @property mapTypes {H.service.MapTypes} - The map types to use + */ + export interface Options { + alignment?: H.ui.LayoutAlignment; + mapTypes: H.service.MapType; + } + } + + /** + * This class represents a UI element showing the current zoom scale. + */ + export class ScaleBar { + /** + * Constructor + * @param opt_options {H.ui.ScaleBar.Options=} - optional parameters to be passed to this scale bar. + */ + constructor(opt_options?: H.ui.ScaleBar.Options); + } + + export module ScaleBar { + /** + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, default is H.ui.LayoutAlignment.BOTTOM_RIGHT + */ + export interface Options { + alignment?: H.ui.LayoutAlignment; + } + } + + /** + * This class encapsulates map UI functionality. + */ + export class UI implements H.util.ICapturable { + /** + * Constructor + * @param map {H.Map} + * @param opt_options {H.ui.UI.Options=} + */ + constructor(map: H.Map, opt_options?: UI.Options); + + /** + * This method returns this ui's root element. + * @returns {ELement} - the root element + */ + getElement(): Element; + + /** + * Returns the map instance to which this UI was added. + * @returns {H.Map} + */ + getMap(): H.Map; + + /** + * This method returns this UI object's current unit system. + * @returns {H.ui.UnitSystem} - the current unit system + */ + getUnitSystem(): UnitSystem; + + /** + * This method sets this UI object's unit system for displaying distances. + * @param unitSystem {H.ui.UnitSystem} - the unit system to use + */ + setUnitSystem(unitSystem: UnitSystem): void; + + /** + * Toggles this UI's unit system between {@link H.ui.UnitSystem.METRIC} and {@link H.ui.UnitSystem.IMPERIAL}. + */ + toggleUnitSystem(): void; + + /** + * This method adds an info bubble to the UI. + * @param bubble {H.ui.InfoBubble} - the info bubble to be added + */ + addBubble(bubble: InfoBubble): void; + + /** + * This method removes a previously added info bubble from the UI. + * @param bubble {H.ui.InfoBubble} - the info bubble to be removed + */ + removeBubble(bubble: InfoBubble): void; + + /** + * This method returns a list of info bubble objects which are currently attached to this UI. + * @returns {Array} - the list of info bubbles + */ + getBubbles(): Array; + + /** + * This method appends a control to the UI. + * @param name {string} - the name under which to register this control + * @param control {H.ui.Control} - the control to add to this UI + */ + addControl(name: string, control: Control): void; + + /** + * Removes a previously registered control from the UI object. + * @param name {string} - the name under which this control was previously registered + * @returns {H.ui.Control} - the removed control + */ + removeControl(name: string): Control; + + /** + * This method returns a UI control which was previously registered with the provided name. + * @param name {string} - the name under which the control was registered. + * @returns {H.ui.Control} - the control or undefined if the control does not exist. + */ + getControl(name: string): Control; + + /** + * This function creates the default UI including the zoom control, + * map settings control and scalebar and panorama discovery control. + * The default controls will be assigned the following values: + * + * Zoom control: + * id: 'zoom' + * alignment: 'right-middle' + * Map settings control: + * id: 'mapsettings' + * alignment: 'bottom-right' + * Scalebar: + * id: 'scalebar' + * alignment: 'bottom-right' + * Pano: + * id: 'panorama' + * alignment: 'top-right' + * + * @param map {H.Map} - The map instance to which to append the UI + * @param mapTypes {Object} - The map types to use + * @param opt_locale {(H.ui.i18n.Localization | string)=} - the language to use (or a full localization object). + * @returns {H.ui.UI} - the UI instance configured with the default controls + */ + static createDefault(map: H.Map, mapTypes: H.service.Platform.MapTypes, opt_locale?: H.ui.i18n.Localization | string): UI; + + /** + * This method is used to capture the element view + * @param canvas {HTMLCanvasElement} - HTML Canvas element to draw the view of the capturable element + * @param pixelRation {number} - The pixelRatio to use for over-sampling in cases of high-resolution displays, default is 1 + * @param callback {ICapturable~captureCallback} - Callback function to call once result of the capturing is ready + * @param opt_errback {ICapturable~errorCallback} - Callback function to call if error occurred during capturing + */ + capture(canvas: HTMLCanvasElement, pixelRation: number, callback: (canvas?: HTMLCanvasElement) => void, opt_errback?: (error: string) => void): void; + + /** + * @callback ICapturable~captureCallback + * @param canvas {HTMLCanvasElement=} + */ + + /** + * @callback ICapturable~errorCallback + * @param error {string} + */ + } + + export module UI { + /** + * Optional parameters to be passed to the UI constructor. + * @property unitSystem {H.ui.UnitSystem=} - An optional unit system to be used by the UI, default is H.ui.UnitSystem.METRIC + * @property zoom {(H.ui.ZoomControl.Options | boolean)=} - + * @property zoomrectangle {(H.ui.ZoomRectangle.Options | boolean)=} - + * @property mapsettings {(H.ui.MapSettingsControl.Options | boolean)=} - + * @property scalebar {(H.ui.ScaleBar.Options | boolean)=} - + * @property panorama {(H.ui.Pano.Options | boolean)=} - + * @property distancemeasurement {(H.ui.DistanceMeasurement.Options | boolean)=} - + * @property locale {(H.ui.i18n.Localization | string)=} - defines language in which UI can be rendered. It can be predefined H.ui.i18n.Localization object with custom translation map, or a string one of following 'en-US', 'de-DE', 'es-ES', 'fi-FI', 'fr-FR', 'it-IT', 'nl-NL', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'tr-TR', 'zh-CN'. If not defined ui will use 'en-US' by default + */ + export interface Options { + unitSystem?: H.ui.UnitSystem; + zoom?: (H.ui.ZoomControl.Options | boolean); + zoomrectangle?: (H.ui.ZoomRectangle.Options | boolean); + mapsettings?: (H.ui.MapSettingsControl.Options | boolean); + scalebar?: (H.ui.ScaleBar.Options | boolean); + panorama?: (H.ui.Pano.Options | boolean); + distancemeasurement?: (H.ui.DistanceMeasurement.Options | boolean); + locale?: (H.ui.i18n.Localization | string); + } + } + + /** + * This enumeration holds the possible unit systems for the UI to display distances. + */ + export enum UnitSystem { + /** This value represents the imperial unit system using miles and feet (value: 'imperial'). */ + IMPERIAL, + /** This value represents the metric unit system using meters and kilometers, etc (value: 'metric'). */ + METRIC, + } + + /** + * This class represents the UI controls for zooming in an out of the map. + */ + export class ZoomControl extends H.ui.Control { + /** + * Constructor + * @param opt_options {H.ui.ZoomControl.Options=} - optional parameters to be passed to the map. + */ + constructor(opt_options?: H.ui.ZoomControl.Options); + + /** + * This method returns the zoom speed (in levels per millisecond) which is applied when the button is pressed constantly. + * @returns {number} - the current zoom speed + */ + getZoomSpeed(): number; + } + + export module ZoomControl { + /** + * @property zoomSpeed {number=} - the speed if zooming in and out in levels per millisecond, defaults to 0.05 + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, defaults to H.ui.LayoutAlignment.RIGHT_MIDDLE + * @property slider {boolean=} - flag whether to show the slider (true) or not, defaults to false + * @property sliderSnaps {boolean=} - flag whether slider should snap to the integer values or not, defaults to false. This option has effect only if slider is enabled. + */ + export interface Options { + zoomSpeed?: number; + alignment?: H.ui.LayoutAlignment; + slider?: boolean; + sliderSnaps?: boolean; + } + } + + /** + * This class represents a zoom rectangle control element that allows zooming to the selected area on the screen. + */ + export class ZoomRectangle extends H.ui.Control { + /** + * Constructor + * @param opt_options {H.ui.ZoomRectangle.Options=} - optional parameters to be passed to this control + */ + constructor(opt_options?: H.ui.ZoomRectangle.Options); + } + + export module ZoomRectangle { + /** + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, default is H.ui.LayoutAlignment.BOTTOM_RIGHT + * @property adjustZoom {function(number, H.Map) : number=} - optional function that defines how zoom level should be changed, by default zoom level is picked to fit the bounding rectangle into the view port. + */ + export interface Options { + alignment?: H.ui.LayoutAlignment; + adjustZoom?(n: number, m: H.Map): number; + } + } + + type ES6Element = Element; + + /** + * This namespace contains basic UI elements from which the UI controls are built. + */ + export module base { + export class Container extends H.util.EventTarget { + /** + * Constructor + * @param opt_elementType {string=} - the type of HTML element this UI element renders as, default is 'div' + * @param opt_className {string=} - an optional class name to be used on this element + * @param opt_children {Array=} - optional child elements to be added to this container + */ + constructor(opt_elementType?: string, opt_className?: string, opt_children?: Array); + + /** + * Adds a child element to be rendered within the container element. + * @param child {H.ui.base.Element} - the child element to be added + * @returns {H.ui.base.Container} - this container instance + */ + addChild(child: Element): Container; + + /** + * Returns the child collection of this container. + * @returns {Array} - Returns the child collection of this container. + */ + getChildren(): Array; + + /** + * Removes a child element from this container's child collection. + * @param child {H.ui.base.Element} - the child element to be removed + */ + removeChild(child: Element): void; + + /** + * This method is the concrete implementation of the UI element. This method receives the pre-rendered HTML element which may be modified by deriving classes. + * @param element {Element} - this UI element's HTML representation + * @param doc {Document} - the HTML document into which the element is currently being rendered + */ + renderInternal(element: ES6Element, doc: Document): void; + + /** + * This method returns this UI element's disabled state as a boolean value. + * @returns {boolean} - true if the element is disabled, false otherwise + */ + isDisabled(): boolean; + + /** + * This method set's the disabled state of this UI element. + * @param disabled {boolean} - true to disable the element, false to enable it + * @param opt_force {boolean=} - an optional boolean flag indicating that the value should be set and propagated even if it is the same as the current state + * @returns {H.ui.base.Element} - this element instance + */ + setDisabled(disabled: boolean, opt_force?: boolean): ES6Element; + + /** + * This method returns a previously stored arbitrary data from this element. + * @returns {*} - the previously stored data object or null if not data was stored. + */ + getData(): any; + + /** + * This method stores arbitrary data with this UI element. + * @param data {*} - the data to be stored + */ + setData(data: any): void; + + /** + * This method returns the HTML element this UI element renders. + * + * Note: Before the UI element was rendered the method returns null. + * @returns {?HTMLElement} - the element + */ + getElement(): HTMLElement; + + /** + * Sets the visibility of this element. + * @param visibility {boolean} - visibility + */ + setVisibility(visibility: boolean): void; + + /** + * Returns the visibility of this element. + * @returns {boolean} - visibility + */ + getVisibility(): boolean; + + /** + * This method adds a CSS class to this UI element (if it is not already present). + * @param className {string} - the CSS class name to add + * @returns {H.ui.base.Element} - this UI element instance + */ + addClass(className: string): Element; + + /** + * This method removes a CSS class from this UI element (if it is present). + * @param className {string} - the CSS class name to remove + * @returns {H.ui.base.Element} - this UI element instance + */ + removeClass(className: string): Element; + } + + export class Element extends H.util.EventTarget { + /** + * Constructor + * @param opt_elementType {string=} - the type of HTML element this UI element renders as, default is 'div' + * @param opt_className {string=} - an optional class name to be used on this element + */ + constructor(opt_elementType?: string, opt_className?: string); + + /** + * This method is the concrete implementation of the UI element. This method receives the pre-rendered HTML element which may be modified by deriving classes. + * @param element {Element} - this UI element's HTML representation + * @param doc {Document} - the HTML document into which the element is currently being rendered + */ + renderInternal(element: ES6Element, doc: Document): void; + + /** + * This method returns this UI element's disabled state as a boolean value. + * @returns {boolean} - true if the element is disabled, false otherwise + */ + isDisabled(): boolean; + + /** + * This method set's the disabled state of this UI element. + * @param disabled {boolean} - true to disable the element, false to enable it + * @param opt_force {boolean=} - an optional boolean flag indicating that the value should be set and propagated even if it is the same as the current state + * @returns {H.ui.base.Element} - this element instance + */ + setDisabled(disabled: boolean, opt_force?: boolean): ES6Element; + + /** + * This method returns a previously stored arbitrary data from this element. + * @returns {*} - the previously stored data object or null if not data was stored. + */ + getData(): any; + + /** + * This method stores arbitrary data with this UI element. + * @param data {*} - the data to be stored + */ + setData(data: any): void; + + /** + * This method returns the HTML element this UI element renders. + * + * Note: Before the UI element was rendered the method returns null. + * @returns {?HTMLElement} - the element + */ + getElement(): HTMLElement; + + /** + * Sets the visibility of this element. + * @param visibility {boolean} - visibility + */ + setVisibility(visibility: boolean): void; + + /** + * Returns the visibility of this element. + * @returns {boolean} - visibility + */ + getVisibility(): boolean; + + /** + * This method adds a CSS class to this UI element (if it is not already present). + * @param className {string} - the CSS class name to add + * @returns {H.ui.base.Element} - this UI element instance + */ + addClass(className: string): Element; + + /** + * This method removes a CSS class from this UI element (if it is present). + * @param className {string} - the CSS class name to remove + * @returns {H.ui.base.Element} - this UI element instance + */ + removeClass(className: string): Element; + } + } + + /** + * Namespace contains functionality related to internationalization. + */ + export module i18n { + /** + * Default available locales. UI provides default translations for this set of locale codes. + */ + export const defaultLocales: Array; + + /** + * This class is used for internationalization of UI components. + */ + export class Localization { + constructor(locale: string, opt_translationMap?: any); + + /** + * This method returns current locale code i.e 'en-US' + * @returns {string} - locale code + */ + getLocale(): string; + + /** + * This method returns translation keys for current locale. Keys from this set can be used to get translations via translate method. + * @returns {Array} + */ + getKeys(): Array; + + /** + * This method returns a boolean value indicating whether this localization object has a translation for the specified translation key. + * @param key {string} - a translation key + * @returns {boolean} - true if the key exists, otherwise false + */ + hasKey(key: string): boolean; + + /** + * This method returns translation for provided key. It throws exception if translation is not available + * @param key {string} - a translation key + * @returns {string} - a localized string corresponding to provided key + */ + translate(key: string): string; + } + } + } + + /***** util *****/ + export module util { + /** + * The cache represents a in-memory LRU-cache with a fixed size. It stores any data that is added until the cache's content exceeds a maximum size. Once the size of all content elements exceeds the maximum size the cache will drop the least recently retrieved elements until the size of the cache is within the bounds of its maximum size. Data elements are always associated with an identifier that allow to retrieve them at a later stage and their content size. + */ + export class Cache implements H.util.ICache { + /** + * Constructor + * @param maxSize {number} - the maximum size of the cache + * @param opt_onDrop {function(string, ?, number)=} - A callback to be invoked when a data element is dropped from the cache + * @param opt_filter {(function(string, ?, number) : boolean)=} - A function to filter data elements that are not to be cached + */ + constructor(maxSize: number, opt_onDrop?: (s: string, i: any, n: number) => void, opt_filter?: (s: string, i: any, n: number) => boolean); + + /** + * This method sets this cache's maximum size to a new size. If the cache's contents exceed the new size, least recently used data elements will be dropped. + * @param maxSize {number} - the new maximum size of this cache. + * @returns {H.util.Cache} - this cache + */ + setMaxSize(maxSize: number): H.util.Cache; + + /** + * This method returns the maximum size of this cache. + * @returns {number} - the maximum size of the cache + */ + getMaxSize(): number; + + /** + * This method returns the current size of this cache. + * @returns {number} - the current size of the cache + */ + getCurrentSize(): number; + + /** + * This method adds an element to the cache. + * @param id {*} - The identifier of this data element, the value is converted to a string. + * @param data {*} - the actual data to be stored + * @param size {number} - the size of the data element + * @returns {boolean} - a boolean value indicating whether the data was added + */ + add(id: any, data: any, size: number): boolean; + + /** + * This method retrieves an element from the cache. + * @param id {string} - the ID of the data element to be retrieved. + * @param opt_noUpdate {boolean=} - and optional flag to indicate that the retrieved object should not be marked as 'most recently used'. + * @returns {*} - returns the data associated with the ID or undefined if the data element is not currently in the cache. + */ + get(id: string, opt_noUpdate?: boolean): any; + + /** + * This method explicitly drops an element from the cache. + * @param id {*} - the id of the item to drop + */ + drop(id: any): void; + + /** + * This method will execute the provided callback function on each of the cache's entries. If the optional match predicate is passed to this method the callback will only be executed on those entries for which the predicated returns true. + * @param callback {function(string, ?, number)} - the callback to be invoked for each entry + * @param opt_ctx {Object=} - an optional context object to be used as this within the callback + * @param opt_matcher {(function(string, ?, number) : boolean)=} - an optional match predicate to customize on which entries the callback will be called + */ + forEach(callback: (s: string, i: any, n: number) => void, opt_ctx?: any, opt_matcher?: (s: string, i: any, n: number) => boolean): void; + + /** + * This method removes all data elements from the cache. If the optional match predicate is passed to this method only those data elements will be removed for which the predicate return true. + * @param opt_matcher {(function(string, ?, number) : boolean)=} - an optional function that receives an entries id, data and size and may return true or false to either remove it or leave the entry in the cache respectively + */ + removeAll(opt_matcher?: (s: string, i: any, n: number) => boolean): void; + + /** + * This method registers a callback that should be called each time an entry is dropped from the cache. + * @param callback {(function(string, ?, number))} - the callback to be invoked for each entry + */ + registerOnDrop(callback: (s: string, i: any, n: number) => void): void; + } + + /** + * This event indicates a change. It contains the old and the new value. + * @property target {*} - Object which triggered the event + * @property currentTarget {*} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class ChangeEvent extends H.util.Event { + /** + * Constructor + * @param type {string} - The type of the event + * @param newValue {*} - The new value of the property + * @param oldValue {*} - The previous value of the property + */ + constructor(type: string, newValue: any, oldValue: any); + + /** + * Sets defaultPrevented to true. Which can be used to prevent some default behavior. + */ + preventDefault(): void; + + /** + * Stops propagation for current event. + */ + stopPropagation(): void; + + target: any; + currentTarget: any; + type: string; + defaultPrevented: boolean; + } + + /** + * This class represents a contextual information/action. + * @property SEPARATOR {H.util.ContextItem} - Separator for the context items + */ + export class ContextItem extends H.util.EventTarget { + /** + * Constructor + * @param opt_options {H.util.ContextItem.Options=} - The values to initialize this context item + */ + constructor(opt_options?: H.util.ContextItem.Options); + + /** + * This method returns label of the context item + * @returns {string} - the label of the context item + */ + getLabel(): string; + + /** + * This method changes context item label to the specified one + * @param label {string} - New label for the context item + * @returns {H.util.ContextItem} - this context item instance + */ + setLabel(label: string): H.util.ContextItem; + + /** + * This method returns disabled state of the context item. + * @returns {boolean} - true if the item is disabled, false otherwise + */ + isDisabled(): boolean; + + /** + * This method enables/disables the context item + * @param disabled {boolean} - true to disable and false to enabled it + * @returns {H.util.ContextItem} - this context item instance + */ + setDisabled(disabled: boolean): H.util.ContextItem; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + + static SEPARATOR: H.util.ContextItem; + } + + export module ContextItem { + /** + * This type defines options which can be used to initialize the context item. + * @property label {string=} - the label of the context item + * @property disabled {boolean=} - flag indicatting whether context item is disabled or no, by default false + * @property callback {function(H.util.Event)=} - Optional callback function to call once context item is selected + */ + export interface Options { + label?: string; + disabled?: boolean; + callback?: (event: H.util.Event) => void; + } + } + + /** + * Object which can be safely disposed. + */ + export class Disposable { + /** + * Constructor + */ + constructor(); + + /** + * Method adds a callback which will be triggered when the object is disposed + * @param callback {Function} + * @param opt_scope {Object=} + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + /** + * Base Event class which is used for all events dispatched by any EventTarget within the api. + * @property target {*} - Object which triggered the event + * @property currentTarget {*} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class Event { + /** + * Constructor + * @param type {string} - Event Type. + * @param opt_target {Object=} - Reference to the object that is the target of this event. It has to implement the {@link EventTargetInstance} interface. + */ + constructor(type: string, opt_target?: any); + + /** + * Sets defaultPrevented to true. Which can be used to prevent some default behavior. + */ + preventDefault(): void; + + /** + * Stops propagation for current event. + */ + stopPropagation(): void; + + target: any; + currentTarget: any; + type: string; + defaultPrevented: boolean; + } + + /** + * EventTarget enabled listening and dispatching events on all instances and derived classes. + */ + export class EventTarget { + /** + * Constructor + */ + constructor(); + + /** + * This method allows to listen for specific event triggered by the object. Keep in mind, that you must removeEventListener manually or dispose an object when you no longer need it. Otherwise memory leak is possible. + * @param type {string} - name of event + * @param handler {Function} - event handler function + * @param opt_capture {boolean=} - if set to true will listen in the capture phase (bubble otherwise) + * @param opt_scope {Object=} - scope for the handler function + */ + addEventListener(type: string, handler: EventListenerOrEventListenerObject, opt_capture?: boolean, opt_scope?: any): void; + + /** + * This method will removed previously added listener from the event target + * @param type {string} - name of event + * @param handler {Function} - event handler function + * @param opt_capture {boolean=} - if set to true will listen in the capture phase (bubble otherwise) + * @param opt_scope {Object=} - scope for the handler function + */ + removeEventListener(type: string, handler: EventListenerOrEventListenerObject, opt_capture?: boolean, opt_scope?: any): void; + + /** + * This method will dispatch event on the event target object + * @param evt {H.util.Event | string} - event object or event name + */ + dispatchEvent(evt: H.util.Event | string): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: () => void, opt_scope?: any): void; + } + + /** + * An interface definition for the generic cache. Any data elements can be stored in the cache. They are always associated with an identifier to retrieve them at a later stage and their content size. + */ + export interface ICache { + /** + * This method adds an element to the cache. + * @param id {*} - The identifier of this data element, the value is converted to a string. + * @param data {*} - the actual data to be stored + * @param size {number} - the size of the data element + * @returns {boolean} - a boolean value indicating whether the data was added + */ + add(id: any, data: any, size: number): boolean; + + /** + * This method retrieves an element from the cache. + * @param id {string} - the ID of the data element to be retrieved. + * @param opt_noUpdate {boolean=} - and optional flag to indicate that the retrieved object should not be marked as 'most recently used'. + * @returns {*} - returns the data associated with the ID or undefined if the data element is not currently in the cache. + */ + get(id: string, opt_noUpdate?: boolean): any; + + /** + * This method explicitly drops an element from the cache. + * @param id {*} - the id of the item to drop + */ + drop(id: any): void; + + /** + * This method will execute the provided callback function on each of the cache's entries. If the optional match predicate is passed to this method the callback will only be executed on those entries for which the predicated returns true. + * @param callback {function(string, ?, number)} - the callback to be invoked for each entry + * @param opt_ctx {Object=} - an optional context object to be used as this within the callback + * @param opt_matcher {(function(string, ?, number) : boolean)=} - an optional match predicate to customize on which entries the callback will be called + */ + forEach(callback: (s: string, t: any, n: number) => void, opt_ctx?: Object, opt_matcher?: ((s: string, t: any, n: number) => boolean)): void; + + /** + * This method removes all data elements from the cache. If the optional match predicate is passed to this method only those data elements will be removed for which the predicate return true. + * @param opt_matcher {(function(string, ?, number) : boolean)=} - an optional function that receives an entries id, data and size and may return true or false to either remove it or leave the entry in the cache respectively + */ + removeAll(opt_matcher?: ((s: string, t: any, n: number) => boolean)): void; + + /** + * This method registers a callback that should be called each time an entry is dropped from the cache. + * @param callback {(function(string, ?, number))} - the callback to be invoked for each entry + */ + registerOnDrop(callback: ((s: string, t: any, n: number) => void)): void; + } + + /** + * An interface to cancelable requests and actions. + */ + export interface ICancelable { + /** + * This method is used to cancel current action + */ + cancel(): void; + } + + export interface ICapturable { + /** + * This method is used to capture the element view + * @param canvas {HTMLCanvasElement} - HTML Canvas element to draw the view of the capturable element + * @param pixelRation {number} - The pixelRatio to use for over-sampling in cases of high-resolution displays, default is 1 + * @param callback {ICapturable~captureCallback} - Callback function to call once result of the capturing is ready + * @param opt_errback {ICapturable~errorCallback} - Callback function to call if error occurred during capturing + */ + capture(canvas: HTMLCanvasElement, pixelRation: number, callback: (canvas?: HTMLCanvasElement) => void, opt_errback?: (error: string) => void): void; + + /** + * @callback ICapturable~captureCallback + * @param canvas {HTMLCanvasElement=} + */ + + /** + * @callback ICapturable~errorCallback + * @param error {string} + */ + } + + /** + * This class represents an list of ordered entries which dispatches events when the list is modified. + * @event add {H.util.OList.Event} - Fired when an entry was added to the list. + * @event remove {H.util.OList.Event} - Fired when an entry was removed from the list. + * @event set {H.util.OList.Event} - Fired when an entry was set in the list. + * @event move {H.util.OList.Event} - Fired when an entry was moved within the list. + */ + export class OList extends H.util.EventTarget { + + /** + * This method inserts an entry to the list. Optionally it can place new entry at provided index. + * @param entry {?} - The entry to insert + * @param opt_idx {number=} - The index where the new entry should be inserted; if omitted or greater then the current size of the list, the entry is added at the end of the list; a negative index is treated as being relative from the end of the list + */ + add(entry: any, opt_idx?: number): void; + + /** + * This method removes an entry by a given index from the list. + * @param idx {number} - The index of the entry which should be removed; a negative index is treated as being relative from the end of the list + * @returns {?} - The removed entry + */ + removeAt(idx: number): any; + + /** + * This method removes the the first entry which is identical with the given entry. + * @param entry {?} - The entry to remove + * @returns {boolean} - signals if the entry could be found in the list and is removed + */ + remove(entry: any): boolean; + + /** + * This method replaces an entry at the given index with the given entry. + * @param idx {number} - The index of the entry which should be replaced; a negative index is treated as being relative from the end of the list + * @param entry {?} - The entry which replaces the existing one + * @returns {?} - The replaced entry + */ + set(idx: number, entry: any): any; + + /** + * This method retrieves the index of the first object in this list that is identical with the object supplied by the caller. + * @param entry {?} - The entry for which to return the index. + * @returns {number} - The index of the first matching entry in this list or -1 if the entry provided by the caller is not found in the list + */ + indexOf(entry: any): number; + + /** + * To get the entry at the specified index. + * @param idx {number} - The index of the entry to get a negative index is treated as being relative from the end of the list + * @returns {?} - The element at the given index + */ + get(idx: number): any; + + /** + * This method returns the length of the list. + * @returns {number} + */ + getLength(): number; + + /** + * This method returns all list's entries as an array. + * @returns {Array<*>} - The list as an array + */ + asArray(): Array; + + /** + * This method removes all entries from the list. + */ + flush(): void; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module OList { + /** + * The event class for events that are dispatched by OList + * @property target {*} - Object which triggered the event + * @property currentTarget {*} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class Event extends H.util.Event { + /** + * Constructor + * @param list {H.util.OList} - The OList instance which is emitting the event + * @param type {H.util.OList.prototype.EventType} - The type of the event + * @param idx {number} - The affected index within this list + * @param added {?*} - The value of the entry which was added or set + * @param removed {?*} - The value of the entry which was removed or replaced + * @param moved {?*} - The value of the entry which was moved + */ + constructor(list: H.util.OList, type: string, idx: number, added: any, removed: any, moved: any); + + /** + * Sets defaultPrevented to true. Which can be used to prevent some default behavior. + */ + preventDefault(): void; + + /** + * Stops propagation for current event. + */ + stopPropagation(): void; + + target: any; + currentTarget: any; + type: string; + defaultPrevented: boolean; + } + } + + /** + * A generic class to represent a handle for any kind of asynchronous processed requests + */ + export class Request { + /** + * Constructor + * @param opt_onprogress {function(H.util.Request)=} - A callback to invoke every time when the request's progress state changes + * @param opt_total {number=} - The total number of processing steps to complete this request, default is 1 + */ + constructor(opt_onprogress?: (req: H.util.Request) => void, opt_total?: number); + + /** + * Returns the state of this request + * @returns {H.util.Request.State} + */ + getState(): H.util.Request.State; + + /** + * Returns the number of processing steps to complete this request + * @returns {number} + */ + getTotal(): number; + + /** + * Returns the number of steps which are already processed by this request + * @returns {number} + */ + getProcessed(): number; + + /** + * Returns the number of processingsteps which have been failed + * @returns {number} + */ + getFailed(): number; + } + + export module Request { + /** + * The supported states of an request + */ + export enum State { + PENDING, + PROCESSING, + COMPLETE, + CANCELLED, + ERROR, + } + } + + export module animation { + /** + * This mamespace contains easing functions used for Animation class. + */ + export class ease { + /** + * This function defines linear ease. + * @param val {number} - A value in range [0..1] to translate + * @returns {number} - the translated value + */ + static LINEAR(val: number): number; + + /** + * This function defines quadratic ease in. + * @param val {number} - A value in range [0..1] to translate + * @returns {number} - the translated value + */ + static EASE_IN_QUAD(val: number): number; + + /** + * This function defines quadratic ease out. + * @param val {number} - A value in range [0..1] to translate + * @returns {number} - the translated value + */ + static EASE_OUT_QUAD(val: number): number; + + /** + * This function defines ease in and out with slope. + * @param val {number} - A value in range [0..1] to translate + * @returns {number} - the translated value + */ + static EASE_IN_OUT_QUINT(val: number): number; + + /** + * This function defines ease out with circ function. + * @param val {number} - A value in range [0..1] to translate + * @returns {number} - the translated value + */ + static EASE_OUT_CIRC(val: number): number; + } + } + + export module kinetics { + /** + * This interface defines kinetic move parameters used by map for kinetic drag. + * @property power {number} - Power multiplier. Multiplier is used to increase the speed of the kinetic move. By default map uses 1. + * @property duration {number} - Defines duration of the kinetic move. + */ + export interface IKinetics { + /** + * Easing function modifies animation progress. In example it can modify the animation in a way it starts rapidly and then slows down at the end. + * @param p {number} - current progress + * @returns {number} - modified progress + */ + ease(p: number): number; + + power: number; + duration: number; + } + } + } +} diff --git a/highcharts/highcharts-modules-exporting.d.ts b/highcharts/highcharts-modules-exporting.d.ts new file mode 100644 index 0000000000..4d3bdaa648 --- /dev/null +++ b/highcharts/highcharts-modules-exporting.d.ts @@ -0,0 +1,12 @@ +// Type definitions for Highcharts 4.2.6 (exporting module) +// Project: http://www.highcharts.com/ +// Definitions by: Maciej Suchecki +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare var HighchartsExporting: (H: HighchartsStatic) => HighchartsStatic; + +declare module "highcharts/modules/exporting" { + export = HighchartsExporting; +} diff --git a/highcharts/highcharts-modules-no-data-to-display-tests.ts b/highcharts/highcharts-modules-no-data-to-display-tests.ts new file mode 100644 index 0000000000..64b50f831f --- /dev/null +++ b/highcharts/highcharts-modules-no-data-to-display-tests.ts @@ -0,0 +1,10 @@ +/// +/// +/// + +function test_NoDataToDisplay() { + var chart = $("#container").highcharts(); + var chartHasData = chart.hasData(); + chart.hideNoData(); + chart.showNoData("Custom no data message"); +} diff --git a/highcharts/highcharts-modules-no-data-to-display.d.ts b/highcharts/highcharts-modules-no-data-to-display.d.ts new file mode 100644 index 0000000000..ab5fdd1d0d --- /dev/null +++ b/highcharts/highcharts-modules-no-data-to-display.d.ts @@ -0,0 +1,26 @@ +// Type definitions for Highcharts No Data to Display +// Project: http://www.highcharts.com/ +// Definitions by: Andrey Zolotin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// +interface HighchartsChartObject { + /** + * Returns true if there are data points within the plot area now + * @return {boolean} If chart has any data. + * @since 3.0.8 + */ + hasData(): boolean; + + /** + * Hide the 'No data to display' message added by the no-data-to-display plugin. + * @since 3.0.8 + */ + hideNoData(): void; + + /** + * Display a no-data message. + * @param {String} message An optional message to show in place of the default one + * @since 3.0.8 + */ + showNoData(message?: string): void; +} diff --git a/highcharts/highcharts-more.d.ts b/highcharts/highcharts-more.d.ts new file mode 100644 index 0000000000..1d42764b3c --- /dev/null +++ b/highcharts/highcharts-more.d.ts @@ -0,0 +1,12 @@ +// Type definitions for Highcharts 4.2.6 +// Project: http://www.highcharts.com/ +// Definitions by: Maciej Suchecki +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare var HighchartsMore: (H: HighchartsStatic) => HighchartsStatic; + +declare module "highcharts/highcharts-more" { + export = HighchartsMore; +} diff --git a/highcharts/highcharts.d.ts b/highcharts/highcharts.d.ts index 7185587190..bfe5a70235 100644 --- a/highcharts/highcharts.d.ts +++ b/highcharts/highcharts.d.ts @@ -240,7 +240,7 @@ interface HighchartsPlotBands { * Border color for the plot band. Also requires borderWidth to be set. * @default null */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * Border width for the plot band. Also requires borderColor to be set. * @default 0 @@ -468,6 +468,10 @@ interface HighchartsAxisOptions { * @since 4.0 */ ceiling?: number; + /** + * Configure a crosshair that follows either the mouse pointer or the hovered point. + */ + crosshair?: HighchartsCrosshairObject | boolean; /** * For a datetime axis, the scale will automatically adjust to the appropriate unit. This member gives the default * string representations used for each unit. For an overview of the replacement codes, see dateFormat. @@ -552,7 +556,7 @@ interface HighchartsAxisOptions { * The color of the line marking the axis itself. * @default '#C0D0E0'. */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * The width of the line marking the axis itself. * @default 1 @@ -816,7 +820,7 @@ interface HighchartsAxisOptions { interface HighchartsColorAxisDataClass { from?: number; to?: number; - color?: string; + color?: string | HighchartsGradient; name?: string; } @@ -902,7 +906,7 @@ interface HighchartsColorAxisOptions { * The color of the line marking the axis itself. * @default '#C0D0E0' */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * The width of the line marking the axis itself. * @default 0 @@ -922,7 +926,7 @@ interface HighchartsColorAxisOptions { * The color of the marker. * @default 'gray' */ - color?: string; + color?: string | HighchartsGradient; }; /** * The maximum value of the axis in terms of map point values. If null, the max value is automatically calculated. @@ -1378,7 +1382,7 @@ interface HighchartsShadow { /** * @default 'black' */ - color?: string; + color?: string | HighchartsGradient; /** * @default 1 */ @@ -1487,7 +1491,7 @@ interface HighchartsChartOptions { * The color of the outer chart border. * @default '#4572A7' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The corner radius of the outer chart border. * @default 0 @@ -1717,7 +1721,7 @@ interface HighchartsChartOptions { interface HighchartsCSSObject { background?: string; border?: string; - color?: string; + color?: string | HighchartsGradient; cursor?: string; font?: string; fontFamily?: string; @@ -2425,7 +2429,7 @@ interface HighchartsLegendOptions { * The color of the drawn border around the legend. * @default '#909090' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The border corner radius of the legend. * @default 0 @@ -2720,7 +2724,7 @@ interface HighchartsPaneBackground { /** * @default 'silver' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * @default 1 */ @@ -2799,7 +2803,7 @@ interface HighchartsDataLabels { * The border color for the data label. * @since 2.2.1 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The border radius in pixels for the data label. * @default 0 @@ -2816,7 +2820,7 @@ interface HighchartsDataLabels { * The text color for the data labels. * @default null */ - color?: string; + color?: string | HighchartsGradient; /** * Whether to hide data labels that are outside the plot area. By default, the data label is moved inside the plot * area according to the overflow option. @@ -3062,7 +3066,7 @@ interface HighchartsMarkerState { * The color of the point marker's outline. When null, the series' or point's color is used. * @default '#FFFFFF', '#000000' for select state */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * The width of the point marker's outline. * @default 0 @@ -3272,7 +3276,7 @@ interface HighchartsAreaZone { * Defines the color of the series. * @since 4.1.0 */ - color?: string; + color?: string | HighchartsGradient; /** * A name for the dash style to use for the graph. * @since 4.1.0 @@ -3317,7 +3321,7 @@ interface HighchartsRangeDataLabels { * @default undefined * @since 2.2.1 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The border radius in pixels for the data label. * @default 0 @@ -3334,7 +3338,7 @@ interface HighchartsRangeDataLabels { * The text color for the data labels. * @default null */ - color?: string; + color?: string | HighchartsGradient; /** * Whether to hide data labels that are outside the plot area. By default, the data label is moved inside the plot * area according to the overflow option. @@ -3467,7 +3471,7 @@ interface HighchartsDial { * @default 'black' * @since 2.3.0 */ - backgroundColor?: string; + backgroundColor?: string | HighchartsGradient; /** * The length of the dial's base part, relative to the total radius or length of the dial. * @default '70%'. @@ -3486,7 +3490,7 @@ interface HighchartsDial { * @default 'silver' * @since 2.3.0 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the gauge dial border in pixels. * @default 0 @@ -3520,14 +3524,14 @@ interface HighchartsPivot { * @default 'black' * @since 2.3.0 */ - backgroundColor?: string; + backgroundColor?: string | HighchartsGradient; /** * The border or stroke color of the pivot. In able to change this, the borderWidth must also be set to something * other than the default 0. * @default 'silver' * @since 2.3.0 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The border or stroke width of the pivot. * @default 0 @@ -3550,7 +3554,7 @@ interface HighchartsTreeMapLevel { * Can set borderColor on all points which lies on the same level. * @since 4.1.0 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * et the dash style of the border of all the point which lies on the level. * @since 4.1.0 @@ -3565,7 +3569,7 @@ interface HighchartsTreeMapLevel { * Can set a color on all points which lies on the same level. * @since 4.1.0 */ - color?: string; + color?: string | HighchartsGradient; /** * Can set the options of dataLabels on each point which lies on the level. * @default undefined @@ -3590,7 +3594,7 @@ interface HighchartsTreeMapLevel { } /** - * General options for all series types + * General options for all series types. */ interface HighchartsSeriesChart { /** @@ -3611,7 +3615,7 @@ interface HighchartsSeriesChart { * specified. In bar type series it applies to the bars unless a color is specified per point. The default value is * pulled from the options.colors array. */ - color?: string; + color?: string | HighchartsGradient; /** * Polar charts only. Whether to connect the ends of a line series plot across the extremes. * @default true @@ -3856,7 +3860,7 @@ interface HighchartsAreaChart extends HighchartsSeriesChart { * A separate color for the graph line. By default the line takes the color of the series, but the lineColor setting * allows setting a separate color for the line without altering the fillColor. */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * A separate color for the negative part of the area. * @since 3.0 @@ -3898,7 +3902,7 @@ interface HighchartsBarChart extends HighchartsSeriesChart { * The color of the border surrounding each column or bar. * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The corner radius of the border surrounding each column or bar. * @default 0 @@ -4259,7 +4263,7 @@ interface HighchartsFunnelChart extends HighchartsSeriesChart { * The color of the border surrounding each column or bar. * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the border surrounding each column or bar. * @default 1 @@ -4381,7 +4385,7 @@ interface HighchartsHeatMapChart extends HighchartsSeriesChart { * The color of the border surrounding each column or bar. * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The corner radius of the border surrounding each column or bar. * @default 0 @@ -4464,7 +4468,7 @@ interface HighchartsPieChart extends HighchartsSeriesChart { * borderless pies. * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the border surrounding each column or bar. * @default 1 @@ -4569,7 +4573,7 @@ interface HighchartsPyramidChart extends HighchartsSeriesChart { * The color of the border surrounding each slice * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the border surrounding each slice * @default 1 @@ -4684,7 +4688,7 @@ interface HighchartsTreeMapChart extends HighchartsSeriesChart { * The color of the border surrounding each tree map item. * @default '#E0E0E0' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the border surrounding each column or bar. * @default 1 @@ -4779,7 +4783,7 @@ interface HighchartsWaterFallChart extends HighchartsBarChart { * @default '#333333' * @since 3.0 */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * The color used specifically for positive point columns. When not specified, the general series color is used. */ @@ -4830,7 +4834,7 @@ interface HighchartsIndividualSeriesOptions { * specified. In bar type series it applies to the bars unless a color is specified per point. The default * value is pulled from the options.colors array. */ - color?: string; + color?: string | HighchartsGradient; /** * You can set the cursor to "pointer" if you have click events attached to the series, to signal to the user * that the points and lines can be clicked. @@ -4945,7 +4949,7 @@ interface HighchartsDataPoint { * Individual color for the point. By default the color is pulled from the global colors array. * @default undefined */ - color?: string; + color?: string | HighchartsGradient; /** * Serves a purpose only if a colorAxis object is defined in the chart options. This value will decide which color * the point gets from the scale of the colorAxis. @@ -5169,7 +5173,7 @@ interface HighchartsTitleOptions { } interface HighchartsCrosshairObject { - color?: string; + color?: string | HighchartsGradient; width?: number; dashStyle?: string; //Solid ShortDash ShortDot ShortDashDot ShortDashDotDot Dot Dash LongDash DashDot LongDashDot LongDashDotDot zIndex?: number; @@ -5196,7 +5200,7 @@ interface HighchartsTooltipOptions extends HighchartsSeriesTooltipOptions { * The color of the tooltip border. When null, the border takes the color of the corresponding series or point. * @default null */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The radius of the rounded border corners. * @default 3 @@ -5598,7 +5602,7 @@ interface HighchartsAxisObject { * @param {boolean | HighchartsAnimation} animation When true, the resize will be animated with default animation options. The animation can also be a configuration object with properties duration and easing. * @since 1.2.0 */ - setExtremes(min?: number, max?: number, redraw?: boolean, animation?: boolean | HighchartsAnimation): void; + setExtremes(min?: number, max?: number, redraw?: boolean, animation?: boolean | HighchartsAnimation, eventArguments?: any): void; /** * Update the title of the axis after render time. * @param {HighchartsAxisTitle} title The new title options on the same format as given in xAxis.title. diff --git a/html-pdf/html-pdf-tests.ts b/html-pdf/html-pdf-tests.ts new file mode 100644 index 0000000000..6a214ef231 --- /dev/null +++ b/html-pdf/html-pdf-tests.ts @@ -0,0 +1,13 @@ +/// +/// + +import * as fs from 'fs'; +import * as pdf from 'html-pdf'; + +var html = fs.readFileSync('./test/businesscard.html', 'utf8'); +var options: pdf.CreateOptions = { format: 'Letter' }; + +pdf.create(html, options).toFile('./businesscard.pdf', (err: Error, res: pdf.FileInfo) => { + if (err) return console.log(err); + console.log(res); // { filename: '/app/businesscard.pdf' } +}); diff --git a/html-pdf/html-pdf.d.ts b/html-pdf/html-pdf.d.ts new file mode 100644 index 0000000000..07c4be9f71 --- /dev/null +++ b/html-pdf/html-pdf.d.ts @@ -0,0 +1,80 @@ +// Type definitions for html-pdf v2.1.0 +// Project: https://github.com/marcbachmann/node-html-pdf +// Definitions by: Seth Westphal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'html-pdf' { + + import * as fs from 'fs'; + + export interface CreateOptions { + + // Export options + directory?: string; + + // Papersize Options: http://phantomjs.org/api/webpage/property/paper-size.html + height?: string; + width?: string; + format?: 'A3' | 'A4' | 'A5' | 'Legal' | 'Letter' | 'Tabloid'; + orientation?: 'portrait' | 'landscape'; + + // Page options + border?: string | { + top?: string; + right?: string; + bottom?: string; + left?: string; + }; + + header?: { + height?: string; + contents?: string; + }; + footer?: { + height?: string; + contents?: { + first?: string; + [page: number]: string; + default?: string; + last?: string; + }; + }; + + // Rendering options + base?: string; + + // Zooming option, can be used to scale images if `options.type` is not pdf + zoomFactor?: string; + + // File options + type?: 'png' | 'jpeg' | 'pdf'; + quality?: string; + + // Script options + phantomPath?: string; + phantomArgs?: string[]; + script?: string; + timeout?: number; + + // HTTP Headers that are used for requests + httpHeaders?: { + [header: string]: string; + }; + + } + + export interface FileInfo { + filename: string; + } + + export interface CreateResult { + toBuffer(callback: (err: Error, buffer: Buffer) => void): void; + toFile(callback: (err: Error, res: FileInfo) => void): void; + toFile(filename?: string, callback?: (err: Error, res: FileInfo) => void): void; + toStream(callback: (err: Error, stream: fs.ReadStream) => void): void; + } + + export function create(html: string, options?: CreateOptions): CreateResult; +} diff --git a/imap/imap.d.ts b/imap/imap.d.ts index 1531035152..07a7c8fe9a 100644 --- a/imap/imap.d.ts +++ b/imap/imap.d.ts @@ -236,7 +236,7 @@ declare namespace IMAP { serverSupports(capability: string): boolean; } - export class Connection implements NodeJS.EventEmitter, MessageFunctions { + export class Connection extends NodeJS.EventEmitter implements MessageFunctions { /** @constructor */ constructor(config: Config); diff --git a/inline-css/inline-css.d.ts b/inline-css/inline-css.d.ts index 478f25226b..41511097c7 100644 --- a/inline-css/inline-css.d.ts +++ b/inline-css/inline-css.d.ts @@ -3,7 +3,7 @@ // Definitions by: Philip Spain // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module 'inline-css' { import Promise = require('bluebird'); diff --git a/inversify-binding-decorators/inversify-binding-decorators-tests.ts b/inversify-binding-decorators/inversify-binding-decorators-tests.ts index 9b0dff520e..8ca0acc551 100644 --- a/inversify-binding-decorators/inversify-binding-decorators-tests.ts +++ b/inversify-binding-decorators/inversify-binding-decorators-tests.ts @@ -4,51 +4,52 @@ import { inject, Kernel } from "inversify"; import { autoProvide, makeProvideDecorator, makeFluentProvideDecorator } from "inversify-binding-decorators"; module decorator { + let kernel = new Kernel(); let provide = makeProvideDecorator(kernel); - interface INinja { + interface Warrior { fight(): string; sneak(): string; } - interface IKatana { + interface Weapon { hit(): string; } - interface IShuriken { + interface ThrowableWeapon { throw(): string; } let TYPE = { - IKatana: "IKatana", - INinja: "INinja", - IShuriken: "IShuriken" + ThrowableWeapon: "ThrowableWeapon", + Warrior: "Warrior", + Weapon: "Weapon" }; - @provide(TYPE.IKatana) - class Katana implements IKatana { + @provide(TYPE.Weapon) + class Katana implements Weapon { public hit() { return "cut!"; } } - @provide(TYPE.IShuriken) - class Shuriken implements IShuriken { + @provide(TYPE.ThrowableWeapon) + class Shuriken implements ThrowableWeapon { public throw() { return "hit!"; } } - @provide(TYPE.INinja) - class Ninja implements INinja { + @provide(TYPE.Warrior) + class Ninja implements Warrior { - private _katana: IKatana; - private _shuriken: IShuriken; + private _katana: Weapon; + private _shuriken: ThrowableWeapon; public constructor( - @inject("IKatana") katana: IKatana, - @inject("IShuriken") shuriken: IShuriken + @inject(TYPE.Weapon) katana: Weapon, + @inject(TYPE.ThrowableWeapon) shuriken: ThrowableWeapon ) { this._katana = katana; this._shuriken = shuriken; @@ -59,12 +60,13 @@ module decorator { } - let ninja = kernel.get(TYPE.INinja); + let ninja = kernel.get(TYPE.Warrior); console.log(ninja); } module fluent_decorator { + let kernel = new Kernel(); let provide = makeFluentProvideDecorator(kernel); @@ -76,27 +78,27 @@ module fluent_decorator { return provide(identifier).done(); }; - interface INinja { + interface Warrior { fight(): string; sneak(): string; } - interface IKatana { + interface Weapon { hit(): string; } - interface IShuriken { + interface ThrowableWeapon { throw(): string; } let TYPE = { - IKatana: "IKatana", - INinja: "INinja", - IShuriken: "IShuriken" + ThrowableWeapon: "ThrowableWeapon", + Warrior: "Warrior", + Weapon: "Weapon" }; - @provideSingleton(TYPE.IKatana) - class Katana implements IKatana { + @provideSingleton(TYPE.Weapon) + class Katana implements Weapon { private _mark: any; public constructor() { this._mark = Math.random(); @@ -106,8 +108,8 @@ module fluent_decorator { } } - @provideTransient(TYPE.IShuriken) - class Shuriken implements IShuriken { + @provideTransient(TYPE.ThrowableWeapon) + class Shuriken implements ThrowableWeapon { private _mark: any; public constructor() { this._mark = Math.random(); @@ -117,15 +119,15 @@ module fluent_decorator { } } - @provideTransient(TYPE.INinja) - class Ninja implements INinja { + @provideTransient(TYPE.Warrior) + class Ninja implements Warrior { - private _katana: IKatana; - private _shuriken: IShuriken; + private _katana: Weapon; + private _shuriken: ThrowableWeapon; public constructor( - @inject("IKatana") katana: IKatana, - @inject("IShuriken") shuriken: IShuriken + @inject(TYPE.Weapon) katana: Weapon, + @inject(TYPE.ThrowableWeapon) shuriken: ThrowableWeapon ) { this._katana = katana; this._shuriken = shuriken; @@ -136,7 +138,7 @@ module fluent_decorator { } - let ninja = kernel.get(TYPE.INinja); + let ninja = kernel.get(TYPE.Warrior); console.log(ninja); } diff --git a/inversify-binding-decorators/inversify-binding-decorators.d.ts b/inversify-binding-decorators/inversify-binding-decorators.d.ts index 623b6c32c7..d5f92132a3 100644 --- a/inversify-binding-decorators/inversify-binding-decorators.d.ts +++ b/inversify-binding-decorators/inversify-binding-decorators.d.ts @@ -1,4 +1,4 @@ -// Type definitions for inversify 1.0.0-beta.5 +// Type definitions for inversify-binding-decorators 1.0.0 // Project: https://github.com/inversify/inversify-binding-decorators // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -7,46 +7,50 @@ declare namespace inversifyBindingDecorators { - interface IProvideInSyntax extends IProvideDoneSyntax { - inSingletonScope(): IProvideWhenOnSyntax; - } + namespace interfaces { - interface IProvideDoneSyntax { - done(): (target: any) => any; - } + export interface ProvideInSyntax extends ProvideDoneSyntax { + inSingletonScope(): ProvideWhenOnSyntax; + } - interface IProvideOnSyntax extends IProvideDoneSyntax { - onActivation(fn: (context: inversify.interfaces.Context, injectable: T) => T): IProvideWhenSyntax; - } + export interface ProvideDoneSyntax { + done(): (target: any) => any; + } - interface IProvideInWhenOnSyntax extends IProvideInSyntax, IProvideWhenSyntax, IProvideOnSyntax {} + export interface ProvideOnSyntax extends ProvideDoneSyntax { + onActivation(fn: (context: inversify.interfaces.Context, injectable: T) => T): ProvideWhenSyntax; + } - interface IProvideWhenOnSyntax extends IProvideWhenSyntax, IProvideOnSyntax {} + export interface ProvideInWhenOnSyntax extends ProvideInSyntax, ProvideWhenSyntax, ProvideOnSyntax {} + + export interface ProvideWhenOnSyntax extends ProvideWhenSyntax, ProvideOnSyntax {} + + export interface ProvideWhenSyntax extends ProvideDoneSyntax { + when(constraint: (request: inversify.interfaces.Request) => boolean): ProvideOnSyntax; + whenTargetNamed(name: string): ProvideOnSyntax; + whenTargetTagged(tag: string, value: any): ProvideOnSyntax; + whenInjectedInto(parent: (Function|string)): ProvideOnSyntax; + whenParentNamed(name: string): ProvideOnSyntax; + whenParentTagged(tag: string, value: any): ProvideOnSyntax; + whenAnyAncestorIs(ancestor: (Function|string)): ProvideOnSyntax; + whenNoAncestorIs(ancestor: (Function|string)): ProvideOnSyntax; + whenAnyAncestorNamed(name: string): ProvideOnSyntax; + whenAnyAncestorTagged(tag: string, value: any): ProvideOnSyntax; + whenNoAncestorNamed(name: string): ProvideOnSyntax; + whenNoAncestorTagged(tag: string, value: any): ProvideOnSyntax; + whenAnyAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): ProvideOnSyntax; + whenNoAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): ProvideOnSyntax; + } - interface IProvideWhenSyntax extends IProvideDoneSyntax { - when(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax; - whenTargetNamed(name: string): IProvideOnSyntax; - whenTargetTagged(tag: string, value: any): IProvideOnSyntax; - whenInjectedInto(parent: (Function|string)): IProvideOnSyntax; - whenParentNamed(name: string): IProvideOnSyntax; - whenParentTagged(tag: string, value: any): IProvideOnSyntax; - whenAnyAncestorIs(ancestor: (Function|string)): IProvideOnSyntax; - whenNoAncestorIs(ancestor: (Function|string)): IProvideOnSyntax; - whenAnyAncestorNamed(name: string): IProvideOnSyntax; - whenAnyAncestorTagged(tag: string, value: any): IProvideOnSyntax; - whenNoAncestorNamed(name: string): IProvideOnSyntax; - whenNoAncestorTagged(tag: string, value: any): IProvideOnSyntax; - whenAnyAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax; - whenNoAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax; } export function autoProvide(kernel: inversify.interfaces.Kernel, ...modules: any[]): void; export function makeProvideDecorator(kernel: inversify.interfaces.Kernel): - (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => (target: any) => any; + (serviceIdentifier: inversify.interfaces.ServiceIdentifier) => (target: any) => any; export function makeFluentProvideDecorator(kernel: inversify.interfaces.Kernel): - (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => IProvideInWhenOnSyntax; + (serviceIdentifier: inversify.interfaces.ServiceIdentifier) => interfaces.ProvideInWhenOnSyntax; } diff --git a/inversify-devtools/inversify-devtools-test.ts b/inversify-devtools/inversify-devtools-test.ts new file mode 100644 index 0000000000..3b99d7df93 --- /dev/null +++ b/inversify-devtools/inversify-devtools-test.ts @@ -0,0 +1,8 @@ +/// + +import render from "inversify-devtools"; +import { Kernel } from "inversify"; + +let connectKernel = render("root"); +let kernel = new Kernel(); +connectKernel(kernel); diff --git a/inversify-devtools/inversify-devtools.d.ts b/inversify-devtools/inversify-devtools.d.ts new file mode 100644 index 0000000000..841ae228c5 --- /dev/null +++ b/inversify-devtools/inversify-devtools.d.ts @@ -0,0 +1,15 @@ +// Type definitions for inversify-devtools 1.0.0 +// Project: https://github.com/inversify/inversify-devtools +// Definitions by: inversify +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface ConnectKernel extends Function { + (kernel: inversify.interfaces.Kernel): void; +} + +declare module "inversify-devtools" { + let render: (container: string) => ConnectKernel; + export default render; +} diff --git a/inversify-express-utils/inversify-express-utils-tests.ts b/inversify-express-utils/inversify-express-utils-tests.ts index 1d421e397a..b082546448 100644 --- a/inversify-express-utils/inversify-express-utils-tests.ts +++ b/inversify-express-utils/inversify-express-utils-tests.ts @@ -1,21 +1,23 @@ /// -import { InversifyExpressServer, Controller, Get, All, Delete, Head, Put, Patch, Post, Method } from "inversify-express-utils"; +import { InversifyExpressServer, Controller, Get, All, Delete, Head, Put, Patch, Post, Method, TYPE } from "inversify-express-utils"; import * as express from "express"; import { Kernel } from "inversify"; +let kernel = new Kernel(); + module server { - let kernel = new Kernel(); + let server = new InversifyExpressServer(kernel); server - .setConfig((app) => { + .setConfig((app: express.Application) => { app.use((req: express.Request, res: express.Response, next: express.NextFunction) => { console.log("hello world"); next(); }); }) - .setErrorConfig((app) => { + .setErrorConfig((app: express.Application) => { app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => { console.error(err.stack); res.status(500).send("Something broke!"); @@ -55,6 +57,8 @@ module decorators { public testMethod() { return "METHOD:FOO"; } } + kernel.bind(TYPE.Controller).to(TestController); + function m1(req: express.Request, res: express.Response, next: express.NextFunction) { next(); } function m2(req: express.Request, res: express.Response, next: express.NextFunction) { next(); } function m3(req: express.Request, res: express.Response, next: express.NextFunction) { next(); } diff --git a/inversify-express-utils/inversify-express-utils.d.ts b/inversify-express-utils/inversify-express-utils.d.ts index aa9a20d23c..f90b0cac88 100644 --- a/inversify-express-utils/inversify-express-utils.d.ts +++ b/inversify-express-utils/inversify-express-utils.d.ts @@ -1,4 +1,4 @@ -// Type definitions for inversify 1.0.0-alpha.4 +// Type definitions for inversify-express-utils 1.0.0 // Project: https://github.com/inversify/inversify-express-utils // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -11,40 +11,50 @@ declare module "inversify-express-utils" { import * as express from "express"; import * as inversify from "inversify"; - interface IInversifyExpressServerConstructor { - new(kernel: inversify.interfaces.Kernel): IInversifyExpressServer; + export namespace interfaces { + + export interface InversifyExpressServerConstructor { + new(kernel: inversify.interfaces.Kernel): InversifyExpressServer; + } + + export interface InversifyExpressServer { + setConfig(fn: ConfigFunction): InversifyExpressServer; + setErrorConfig(fn: ConfigFunction): InversifyExpressServer; + build(): express.Application; + } + + export interface ConfigFunction { + (app: express.Application): void; + } + + export interface HandlerDecoratorFactory { + (path: string, ...middleware: express.RequestHandler[]): HandlerDecorator; + } + + export interface HandlerDecorator { + (target: any, key: string, value: any): void; + } + } - interface IInversifyExpressServer { - setConfig(fn: IConfigFunction): IInversifyExpressServer; - setErrorConfig(fn: IConfigFunction): IInversifyExpressServer; - build(): express.Application; + export interface Controller {} + + interface ServiceIdentifiers { + Controller: Symbol; } - interface IConfigFunction { - (app: express.Application): void; - } - - interface IHandlerDecoratorFactory { - (path: string, ...middleware: express.RequestHandler[]): IHandlerDecorator; - } - - interface IHandlerDecorator { - (target: any, key: string, value: any): void; - } - - export interface IController {} - - export var InversifyExpressServer: IInversifyExpressServerConstructor; + export var InversifyExpressServer: interfaces.InversifyExpressServerConstructor; export var Controller: (path: string, ...middleware: express.RequestHandler[]) => (target: any) => void; - export var All: IHandlerDecoratorFactory; - export var Get: IHandlerDecoratorFactory; - export var Post: IHandlerDecoratorFactory; - export var Put: IHandlerDecoratorFactory; - export var Patch: IHandlerDecoratorFactory; - export var Head: IHandlerDecoratorFactory; - export var Delete: IHandlerDecoratorFactory; - export var Method: (method: string, path: string, ...middleware: express.RequestHandler[]) => IHandlerDecorator; + export var All: interfaces.HandlerDecoratorFactory; + export var Get: interfaces.HandlerDecoratorFactory; + export var Post: interfaces.HandlerDecoratorFactory; + export var Put: interfaces.HandlerDecoratorFactory; + export var Patch: interfaces.HandlerDecoratorFactory; + export var Head: interfaces.HandlerDecoratorFactory; + export var Delete: interfaces.HandlerDecoratorFactory; + export var Method: (method: string, path: string, ...middleware: express.RequestHandler[]) => interfaces.HandlerDecorator; + export var TYPE: ServiceIdentifiers; + } diff --git a/inversify-inject-decorators/inversify-inject-decorators.d.ts b/inversify-inject-decorators/inversify-inject-decorators.d.ts index 032ed40cdd..34244c6d5e 100644 --- a/inversify-inject-decorators/inversify-inject-decorators.d.ts +++ b/inversify-inject-decorators/inversify-inject-decorators.d.ts @@ -1,4 +1,4 @@ -// Type definitions for inversify-inject-decorators 1.0.0-beta.1 +// Type definitions for inversify-inject-decorators 1.0.0 // Project: https://github.com/inversify/inversify-inject-decorators // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -7,26 +7,25 @@ declare namespace inversifyInjectDecorators { - interface InjectDecorators { + export interface InjectDecorators { - lazyInject: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => + lazyInject: (serviceIdentifier: inversify.interfaces.ServiceIdentifier) => (proto: any, key: string) => void; - lazyInjectNamed: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable), named: string) => + lazyInjectNamed: (serviceIdentifier: inversify.interfaces.ServiceIdentifier, named: string) => (proto: any, key: string) => void; - lazyInjectTagged: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable), key: string, value: any) => + lazyInjectTagged: (serviceIdentifier: inversify.interfaces.ServiceIdentifier, key: string, value: any) => (proto: any, propertyName: string) => void; - lazyMultiInject: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => + lazyMultiInject: (serviceIdentifier: inversify.interfaces.ServiceIdentifier) => (proto: any, key: string) => void; } - export function getDecorators(kernel: inversify.interfaces.Kernel): InjectDecorators; - } declare module "inversify-inject-decorators" { - export default inversifyInjectDecorators.getDecorators; + let getDecorators: (kernel: inversify.interfaces.Kernel) => inversifyInjectDecorators.InjectDecorators; + export default getDecorators; } diff --git a/inversify-logger-middleware/inversify-logger-middleware-tests.ts b/inversify-logger-middleware/inversify-logger-middleware-tests.ts index c9c7d5c8a8..3b2119911a 100644 --- a/inversify-logger-middleware/inversify-logger-middleware-tests.ts +++ b/inversify-logger-middleware/inversify-logger-middleware-tests.ts @@ -4,23 +4,23 @@ declare var kernel: inversify.interfaces.Kernel; import { makeLoggerMiddleware, textSerializer } from "inversify-logger-middleware"; -interface ILoggerOutput { +interface LoggerOutput { entry: T; } -let makeStringRenderer = function (loggerOutput: ILoggerOutput) { - return function (entry: inversifyLoggerMiddleware.ILogEntry) { +let makeStringRenderer = function (loggerOutput: LoggerOutput) { + return function (entry: inversifyLoggerMiddleware.interfaces.LogEntry) { loggerOutput.entry = textSerializer(entry); }; }; -let makeObjRenderer = function (loggerOutput: ILoggerOutput) { - return function (entry: inversifyLoggerMiddleware.ILogEntry) { +let makeObjRenderer = function (loggerOutput: LoggerOutput) { + return function (entry: inversifyLoggerMiddleware.interfaces.LogEntry) { loggerOutput.entry = entry; }; }; -let options: inversifyLoggerMiddleware.ILoggerSettings = { +let options: inversifyLoggerMiddleware.interfaces.LoggerSettings = { request: { bindings: { activated: true, @@ -48,12 +48,12 @@ let options: inversifyLoggerMiddleware.ILoggerSettings = { let logger = makeLoggerMiddleware(); kernel.applyMiddleware(logger); -let loggerOutput1: ILoggerOutput = { entry: null }; +let loggerOutput1: LoggerOutput = { entry: null }; let stringRenderer1 = makeStringRenderer(loggerOutput1); let logger1 = makeLoggerMiddleware(options, stringRenderer1); kernel.applyMiddleware(logger1); -let loggerOutput2: ILoggerOutput = { entry: null }; +let loggerOutput2: LoggerOutput = { entry: null }; let objRenderer2 = makeObjRenderer(loggerOutput2); let logger2 = makeLoggerMiddleware(options, objRenderer2); kernel.applyMiddleware(logger2); diff --git a/inversify-logger-middleware/inversify-logger-middleware.d.ts b/inversify-logger-middleware/inversify-logger-middleware.d.ts index 3aa4ccca18..cd0037f432 100644 --- a/inversify-logger-middleware/inversify-logger-middleware.d.ts +++ b/inversify-logger-middleware/inversify-logger-middleware.d.ts @@ -1,4 +1,4 @@ -// Type definitions for inversify 1.0.0-beta.6 +// Type definitions for inversify-logger-middleware 1.0.0 // Project: https://github.com/inversify/inversify-logger-middleware // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -7,50 +7,61 @@ declare namespace inversifyLoggerMiddleware { - export interface ILoggerSettings { - request?: IRequestLoggerSettings; - time?: boolean; + export namespace interfaces { + + export interface LoggerSettings { + request?: RequestLoggerSettings; + time?: boolean; + } + + export interface RequestLoggerSettings { + serviceIdentifier?: boolean; + bindings?: BindingLoggerSettings; + target?: TargetLoggerSettings; + } + + export interface BindingLoggerSettings { + activated?: boolean; + serviceIdentifier?: boolean; + implementationType?: boolean; + factory?: boolean; + provider?: boolean; + constraint?: boolean; + onActivation?: boolean; + cache?: boolean; + dynamicValue?: boolean; + scope?: boolean; + type?: boolean; + } + + export interface TargetLoggerSettings { + serviceIdentifier?: boolean; + name?: boolean; + metadata?: boolean; + } + + export interface LogEntry { + error: boolean; + exception: any; + guid: string; + multiInject: boolean; + results: any[]; + rootRequest: inversify.interfaces.Request; + serviceIdentifier: any; + target: any; + time: string; + } + } - export interface IRequestLoggerSettings { - serviceIdentifier?: boolean; - bindings?: IBindingLoggerSettings; - target?: ITargetLoggerSettings; - } + export function makeLoggerMiddleware( + settings?: interfaces.LoggerSettings, + renderer?: (out: interfaces.LogEntry) => void + ): inversify.interfaces.Middleware; - export interface IBindingLoggerSettings { - activated?: boolean; - serviceIdentifier?: boolean; - implementationType?: boolean; - factory?: boolean; - provider?: boolean; - constraint?: boolean; - onActivation?: boolean; - cache?: boolean; - dynamicValue?: boolean; - scope?: boolean; - type?: boolean; - } - - export interface ITargetLoggerSettings { - serviceIdentifier?: boolean; - name?: boolean; - metadata?: boolean; - } - - export interface ILogEntry { - error: boolean; - exception: any; - multiInject: boolean; - results: any[]; - rootRequest: inversify.interfaces.Request; - serviceIdentifier: any; - target: any; - time: string; - } - - export function makeLoggerMiddleware(settings?: ILoggerSettings, renderer?: (out: ILogEntry) => void): inversify.interfaces.Middleware; - export function textSerializer(entry: ILogEntry): string; + export function textSerializer(entry: interfaces.LogEntry): string; + export function bindingTypeFormatter(type: number): string; + export function scopeFormatter(scope: number): string; } diff --git a/inversify-restify-utils/inversify-restify-utils-tests.ts b/inversify-restify-utils/inversify-restify-utils-tests.ts new file mode 100644 index 0000000000..5ff3ddc633 --- /dev/null +++ b/inversify-restify-utils/inversify-restify-utils-tests.ts @@ -0,0 +1,91 @@ +/// + +import { + InversifyRestifyServer, Controller, Get, Options, + Delete, Head, Put, Patch, Post, Method, TYPE +} from "inversify-restify-utils"; + +import * as restify from "restify"; +import { Kernel } from "inversify"; + +let kernel = new Kernel(); + +module server { + + let server = new InversifyRestifyServer(kernel); + + server + .setConfig((app: restify.Server) => { + app.use((req: restify.Request, res: restify.Response, next: restify.Next) => { + console.log("hello world"); + next(); + }); + }) + .build() + .listen(3000, "localhost"); +} + +module decorators { + + @Controller("/") + class TestController { + + @Get("/") + public testGet() { return "GET"; } + + @Options("/") + public testAll() { return "OPTIONS"; } + + @Delete("/") + public testDelete() { return "DELETE"; } + + @Head("/") + public testHead() { return "HEAD"; } + + @Put("/") + public testPut() { return "PUT"; } + + @Patch("/") + public testPatch() { return "PATCH"; } + + @Post("/") + public testPost() { return "POST"; } + + @Method("opts", "/") + public testMethod() { return "METHOD:OPTS"; } + } + + kernel.bind(TYPE.Controller).to(TestController); + + function m1(req: restify.Request, res: restify.Response, next: restify.Next) { next(); } + function m2(req: restify.Request, res: restify.Response, next: restify.Next) { next(); } + function m3(req: restify.Request, res: restify.Response, next: restify.Next) { next(); } + + @Controller("/", m1, m2, m3) + class TestMiddlewareController { + + @Get("/", m1, m2, m3) + public testGet() { return "GET"; } + + @Options("/", m1, m2, m3) + public testAll() { return "OPTIONS"; } + + @Delete("/", m1, m2, m3) + public testDelete() { return "DELETE"; } + + @Head("/", m1, m2, m3) + public testHead() { return "HEAD"; } + + @Put("/", m1, m2, m3) + public testPut() { return "PUT"; } + + @Patch("/", m1, m2, m3) + public testPatch() { return "PATCH"; } + + @Post("/", m1, m2, m3) + public testPost() { return "POST"; } + + @Method("opts", "/", m1, m2, m3) + public testMethod() { return "METHOD:OPTS"; } + } +} diff --git a/inversify-restify-utils/inversify-restify-utils.d.ts b/inversify-restify-utils/inversify-restify-utils.d.ts new file mode 100644 index 0000000000..4f2aab5510 --- /dev/null +++ b/inversify-restify-utils/inversify-restify-utils.d.ts @@ -0,0 +1,59 @@ +// Type definitions for inversify-restify-utils 1.0.0 +// Project: https://github.com/inversify/inversify-restify-utils +// Definitions by: inversify +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "inversify-restify-utils" { + + import * as restify from "restify"; + import * as inversify from "inversify"; + + export namespace interfaces { + + export interface InversifyRestifyServerConstructor { + new(kernel: inversify.interfaces.Kernel): InversifyRestifyServer; + } + + export interface InversifyRestifyServer { + setConfig(fn: ConfigFunction): InversifyRestifyServer; + build(): restify.Server; + } + + export interface ConfigFunction { + (app: restify.Server): void; + } + + export interface HandlerDecoratorFactory { + (path: string, ...middleware: restify.RequestHandler[]): HandlerDecorator; + } + + export interface HandlerDecorator { + (target: any, key: string, value: any): void; + } + + } + + export interface Controller {} + + interface ServiceIdentifiers { + Controller: Symbol; + } + + export var InversifyRestifyServer: interfaces.InversifyRestifyServerConstructor; + + export var Controller: (path: string, ...middleware: restify.RequestHandler[]) => (target: any) => void; + + export var Options: interfaces.HandlerDecoratorFactory; + export var Get: interfaces.HandlerDecoratorFactory; + export var Post: interfaces.HandlerDecoratorFactory; + export var Put: interfaces.HandlerDecoratorFactory; + export var Patch: interfaces.HandlerDecoratorFactory; + export var Head: interfaces.HandlerDecoratorFactory; + export var Delete: interfaces.HandlerDecoratorFactory; + export var Method: (method: string, path: string, ...middleware: restify.RequestHandler[]) => interfaces.HandlerDecorator; + export var TYPE: ServiceIdentifiers; + +} diff --git a/inversify/inversify-global-tests.ts b/inversify/inversify-global-tests.ts index e2ead555d4..53b1a522bf 100644 --- a/inversify/inversify-global-tests.ts +++ b/inversify/inversify-global-tests.ts @@ -1,6 +1,8 @@ /// /// +import * as Proxy from "harmony-proxy"; + let injectable = inversify.injectable; let inject = inversify.inject; let tagged = inversify.tagged; @@ -13,10 +15,7 @@ let traverseAncerstors = inversify.traverseAncerstors; let taggedConstraint = inversify.taggedConstraint; let namedConstraint = inversify.namedConstraint; let typeConstraint = inversify.typeConstraint; -let makePropertyMultiInjectDecorator = inversify.makePropertyMultiInjectDecorator; -let makePropertyInjectTaggedDecorator = inversify.makePropertyInjectTaggedDecorator; -let makePropertyInjectNamedDecorator = inversify.makePropertyInjectNamedDecorator; -let makePropertyInjectDecorator = inversify.makePropertyInjectDecorator; +let unmanaged = inversify.unmanaged; module external_module_test { @@ -112,7 +111,7 @@ module external_module_test { // binding types kernel.bind("Weapon").to(Katana); kernel.bind("Weapon").toConstantValue(new Katana()); - kernel.bind("Weapon").toDynamicValue(() => { return new Katana(); }); + kernel.bind("Weapon").toDynamicValue((context: inversify.interfaces.Context) => { return new Katana(); }); kernel.bind>("Weapon").toConstructor(Katana); @@ -145,6 +144,7 @@ module external_module_test { return new Proxy(katanaToBeInjected, handler); }); + @injectable() class Samurai implements Warrior { public katana: Weapon; @@ -161,8 +161,9 @@ module external_module_test { } kernel.bind("Samurai").to(Samurai); - kernel.bind("IWeapon").to(Katana).whenTargetTagged("canThrow", false); + kernel.bind("Weapon").to(Katana).whenTargetTagged("canThrow", false); kernel.bind("ThrowableWeapon").to(Shuriken).whenTargetTagged("canThrow", true); + kernel.getAllTagged("Weapon", "canThrow", false); let throwable = tagged("canThrow", true); let notThrowable = tagged("canThrow", false); @@ -200,6 +201,7 @@ module external_module_test { kernel.bind("Warrior").to(Samurai3); kernel.bind("Weapon").to(Katana).whenTargetNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenTargetNamed("weak"); + kernel.getAllNamed("Weapon", "weak"); @injectable() class Samurai4 implements Samurai { @@ -245,18 +247,18 @@ module external_module_test { // Constraint helpers kernel.bind("Weapon").to(Shuriken).whenInjectedInto(Ninja); - kernel.bind("Weapon").to(Shuriken).whenInjectedInto("INinja"); + kernel.bind("Weapon").to(Shuriken).whenInjectedInto("Ninja"); kernel.bind("Weapon").to(Shuriken).whenParentNamed("chinese"); kernel.bind("Weapon").to(Shuriken).whenParentTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenTargetNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenTargetTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs(Ninja); - kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs("Ninja"); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorMatches(whenParentNamedCanThrowConstraint); kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs(Ninja); - kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs("Ninja"); kernel.bind("Weapon").to(Shuriken).whenNoAncestorNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenNoAncestorTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenNoAncestorMatches(whenParentNamedCanThrowConstraint); @@ -341,103 +343,42 @@ module external_module_test { } -module property_injection { +module snapshot { let kernel = new Kernel(); - let TYPES = { Weapon: "Weapon" }; - - interface Weapon { - durability: number; - use(): void; - } - - @injectable() - class Sword implements Weapon { - public durability: number; - public constructor() { - this.durability = 100; - } - public use() { - this.durability = this.durability - 10; - } - } - - @injectable() - class WarHammer implements Weapon { - public durability: number; - public constructor() { - this.durability = 100; - } - public use() { - this.durability = this.durability - 10; - } - } - - let propertyMultiInject = makePropertyMultiInjectDecorator(kernel); - - class Warrior1 { - @propertyMultiInject(TYPES.Weapon) - public weapons: Weapon[]; - } - - let propertyInject = makePropertyInjectDecorator(kernel); - - interface Service { - count: number; - increment(): void; - } - - @injectable() - class SomeService implements Service { - public count: number; - public constructor() { - this.count = 0; - } - public increment() { - this.count = this.count + 1; - } - } - - class SomeWebComponent { - @propertyInject("Service") - private _service: Service; - public doSomething() { - let count = this._service.count; - this._service.increment(); - return count; - } - } - - let propertyInjectNammed = makePropertyInjectNamedDecorator(kernel); - - class Warrior2 { - - @propertyInjectNammed(TYPES.Weapon, "not-throwwable") - @named("not-throwwable") - public primaryWeapon: Weapon; - - @propertyInjectNammed(TYPES.Weapon, "throwwable") - @named("throwwable") - public secondaryWeapon: Weapon; - - } - - let propertyInjectTagged = makePropertyInjectTaggedDecorator(kernel); - - class Warrior3 { - - @propertyInjectTagged(TYPES.Weapon, "throwwable", false) - @tagged("throwwable", false) - public primaryWeapon: Weapon; - - @propertyInjectTagged(TYPES.Weapon, "throwwable", true) - @tagged("throwwable", true) - public secondaryWeapon: Weapon; - - } - kernel.snapshot(); kernel.restore(); + @injectable() + class Test { } + + kernel.bind(Test).toSelf(); + kernel.bind(Test).toSelf().inSingletonScope(); +} + +module unmanaged_injection { + + let kernel = new Kernel(); + + const BaseId = "Base"; + + @injectable() + class Base { + public prop: string; + public constructor(@unmanaged() arg: string) { // injected by user + this.prop = arg; + } + } + + @injectable() + class Derived extends Base { + public constructor() { + super("unmanaged-injected-value"); // user injection + } + } + + kernel.bind(BaseId).to(Derived); + console.log(kernel.get(BaseId) instanceof Base); // true + } diff --git a/inversify/inversify-tests.ts b/inversify/inversify-tests.ts index 9b5de8fa0e..6b0d4a5f12 100644 --- a/inversify/inversify-tests.ts +++ b/inversify/inversify-tests.ts @@ -6,11 +6,7 @@ import { injectable, tagged, named, targetName, inject, multiInject, traverseAncerstors, taggedConstraint, namedConstraint, typeConstraint, - makePropertyMultiInjectDecorator, - makePropertyInjectTaggedDecorator, - makePropertyInjectNamedDecorator, - makePropertyInjectDecorator, - KernelModule, interfaces + KernelModule, interfaces, unmanaged } from "inversify"; import * as Proxy from "harmony-proxy"; @@ -109,7 +105,7 @@ module external_module_test { // binding types kernel.bind("Weapon").to(Katana); kernel.bind("Weapon").toConstantValue(new Katana()); - kernel.bind("Weapon").toDynamicValue(() => { return new Katana(); }); + kernel.bind("Weapon").toDynamicValue((context: interfaces.Context) => { return new Katana(); }); kernel.bind>("Weapon").toConstructor(Katana); @@ -159,8 +155,9 @@ module external_module_test { } kernel.bind("Samurai").to(Samurai); - kernel.bind("IWeapon").to(Katana).whenTargetTagged("canThrow", false); + kernel.bind("Weapon").to(Katana).whenTargetTagged("canThrow", false); kernel.bind("ThrowableWeapon").to(Shuriken).whenTargetTagged("canThrow", true); + kernel.getAllTagged("Weapon", "canThrow", false); let throwable = tagged("canThrow", true); let notThrowable = tagged("canThrow", false); @@ -198,6 +195,7 @@ module external_module_test { kernel.bind("Warrior").to(Samurai3); kernel.bind("Weapon").to(Katana).whenTargetNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenTargetNamed("weak"); + kernel.getAllNamed("Weapon", "weak"); @injectable() class Samurai4 implements Samurai { @@ -243,18 +241,18 @@ module external_module_test { // Constraint helpers kernel.bind("Weapon").to(Shuriken).whenInjectedInto(Ninja); - kernel.bind("Weapon").to(Shuriken).whenInjectedInto("INinja"); + kernel.bind("Weapon").to(Shuriken).whenInjectedInto("Ninja"); kernel.bind("Weapon").to(Shuriken).whenParentNamed("chinese"); kernel.bind("Weapon").to(Shuriken).whenParentTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenTargetNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenTargetTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs(Ninja); - kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs("Ninja"); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorMatches(whenParentNamedCanThrowConstraint); kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs(Ninja); - kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs("Ninja"); kernel.bind("Weapon").to(Shuriken).whenNoAncestorNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenNoAncestorTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenNoAncestorMatches(whenParentNamedCanThrowConstraint); @@ -339,103 +337,42 @@ module external_module_test { } -module property_injection { +module snapshot { let kernel = new Kernel(); - let TYPES = { Weapon: "Weapon" }; - - interface Weapon { - durability: number; - use(): void; - } - - @injectable() - class Sword implements Weapon { - public durability: number; - public constructor() { - this.durability = 100; - } - public use() { - this.durability = this.durability - 10; - } - } - - @injectable() - class WarHammer implements Weapon { - public durability: number; - public constructor() { - this.durability = 100; - } - public use() { - this.durability = this.durability - 10; - } - } - - let propertyMultiInject = makePropertyMultiInjectDecorator(kernel); - - class Warrior1 { - @propertyMultiInject(TYPES.Weapon) - public weapons: Weapon[]; - } - - let propertyInject = makePropertyInjectDecorator(kernel); - - interface Service { - count: number; - increment(): void; - } - - @injectable() - class SomeService implements Service { - public count: number; - public constructor() { - this.count = 0; - } - public increment() { - this.count = this.count + 1; - } - } - - class SomeWebComponent { - @propertyInject("Service") - private _service: Service; - public doSomething() { - let count = this._service.count; - this._service.increment(); - return count; - } - } - - let propertyInjectNammed = makePropertyInjectNamedDecorator(kernel); - - class Warrior2 { - - @propertyInjectNammed(TYPES.Weapon, "not-throwwable") - @named("not-throwwable") - public primaryWeapon: Weapon; - - @propertyInjectNammed(TYPES.Weapon, "throwwable") - @named("throwwable") - public secondaryWeapon: Weapon; - - } - - let propertyInjectTagged = makePropertyInjectTaggedDecorator(kernel); - - class Warrior3 { - - @propertyInjectTagged(TYPES.Weapon, "throwwable", false) - @tagged("throwwable", false) - public primaryWeapon: Weapon; - - @propertyInjectTagged(TYPES.Weapon, "throwwable", true) - @tagged("throwwable", true) - public secondaryWeapon: Weapon; - - } - kernel.snapshot(); kernel.restore(); + @injectable() + class Test { } + + kernel.bind(Test).toSelf(); + kernel.bind(Test).toSelf().inSingletonScope(); +} + +module unmanaged_injection { + + let kernel = new Kernel(); + + const BaseId = "Base"; + + @injectable() + class Base { + public prop: string; + public constructor(@unmanaged() arg: string) { // injected by user + this.prop = arg; + } + } + + @injectable() + class Derived extends Base { + public constructor() { + super("unmanaged-injected-value"); // user injection + } + } + + kernel.bind(BaseId).to(Derived); + console.log(kernel.get(BaseId) instanceof Base); // true + } diff --git a/inversify/inversify.d.ts b/inversify/inversify.d.ts index 41200ae470..2f07d203e1 100644 --- a/inversify/inversify.d.ts +++ b/inversify/inversify.d.ts @@ -1,9 +1,9 @@ -// Type definitions for inversify 2.0.0-beta.9 +// Type definitions for inversify 2.0.0-rc.12 // Project: https://github.com/inversify/InversifyJS // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// interface Symbol { toString(): string; @@ -31,9 +31,9 @@ declare namespace inversify { export interface Newable { new(...args: any[]): T; } - + export type ServiceIdentifier = (string|Symbol|Newable); - + export interface Binding extends Clonable> { guid: string; moduleId: string; @@ -45,70 +45,70 @@ declare namespace inversify { constraint: (request: Request) => boolean; onActivation: (context: Context, injectable: T) => T; cache: T; - dynamicValue: () => T; + dynamicValue: (context: Context) => T; scope: number; // BindingScope type: number; // BindingType } - + export interface Factory extends Function { (...args: any[]): (((...args: any[]) => T)|T); } - + export interface FactoryCreator extends Function { (context: Context): Factory; } - + export interface Provider extends Function { (): Promise; } - + export interface ProviderCreator extends Function { (context: Context): Provider; } - + export interface PlanAndResolve { (args: PlanAndResolveArgs): T[]; } - + export interface PlanAndResolveArgs { multiInject: boolean; serviceIdentifier: ServiceIdentifier; target: Target; contextInterceptor: (contexts: Context) => Context; } - + export interface Middleware extends Function { (next: PlanAndResolve): PlanAndResolve; } - + export interface Context { guid: string; kernel: Kernel; plan: Plan; addPlan(plan: Plan): void; } - + export interface ReflectResult { [key: string]: Metadata[]; } - + export interface Metadata { key: string; value: any; } - + export interface Plan { parentContext: Context; rootRequest: Request; } - + export interface Planner { createContext(kernel: Kernel): Context; createPlan(parentContext: Context, binding: Binding, target: Target): Plan; getBindings(kernel: Kernel, serviceIdentifier: ServiceIdentifier): Binding[]; getActiveBindings(parentRequest: Request, target: Target): Binding[]; } - + export interface QueryableString { startsWith(searchString: string): boolean; endsWith(searchString: string): boolean; @@ -116,7 +116,7 @@ declare namespace inversify { equals(compareString: string): boolean; value(): string; } - + export interface Request { guid: string; serviceIdentifier: ServiceIdentifier; @@ -131,10 +131,11 @@ declare namespace inversify { target: Target ): Request; } - + export interface Target { guid: string; serviceIdentifier: ServiceIdentifier; + type: number; // TargetType name: QueryableString; metadata: Array; hasTag(key: string): boolean; @@ -145,13 +146,14 @@ declare namespace inversify { matchesNamedTag(name: string): boolean; matchesTag(key: string): (value: any) => boolean; } - + export interface Resolver { resolve(context: Context): T; } - + export interface Kernel { guid: string; + parent: Kernel; bind(serviceIdentifier: ServiceIdentifier): BindingToSyntax; unbind(serviceIdentifier: ServiceIdentifier): void; unbindAll(): void; @@ -160,6 +162,8 @@ declare namespace inversify { getNamed(serviceIdentifier: ServiceIdentifier, named: string): T; getTagged(serviceIdentifier: ServiceIdentifier, key: string, value: any): T; getAll(serviceIdentifier: ServiceIdentifier): T[]; + getAllNamed(serviceIdentifier: ServiceIdentifier, named: string): T[]; + getAllTagged(serviceIdentifier: ServiceIdentifier, key: string, value: any): T[]; load(...modules: KernelModule[]): void; unload(...modules: KernelModule[]): void; applyMiddleware(...middleware: Middleware[]): void; @@ -167,25 +171,25 @@ declare namespace inversify { snapshot(): void; restore(): void; } - + export interface Bind extends Function { (serviceIdentifier: ServiceIdentifier): BindingToSyntax; } - + export interface KernelModule { guid: string; registry: (bind: Bind) => void; } - + export interface KernelSnapshot { bindings: Lookup>; middleware: PlanAndResolve; } - + export interface Clonable { clone(): T; } - + export interface Lookup extends Clonable> { add(serviceIdentifier: ServiceIdentifier, value: T): void; get(serviceIdentifier: ServiceIdentifier): Array; @@ -193,35 +197,38 @@ declare namespace inversify { removeByModuleId(moduleId: string): void; hasKey(serviceIdentifier: ServiceIdentifier): boolean; } - + export interface KeyValuePair { serviceIdentifier: ServiceIdentifier; value: Array; + guid: string; } - + export interface BindingInSyntax { inSingletonScope(): BindingWhenOnSyntax; + inTransientScope(): BindingWhenOnSyntax; } - + export interface BindingInWhenOnSyntax extends BindingInSyntax, BindingWhenOnSyntax {} - + export interface BindingOnSyntax { onActivation(fn: (context: Context, injectable: T) => T): BindingWhenSyntax; } - + export interface BindingToSyntax { to(constructor: { new(...args: any[]): T; }): BindingInWhenOnSyntax; + toSelf(): BindingInWhenOnSyntax; toConstantValue(value: T): BindingWhenOnSyntax; - toDynamicValue(func: () => T): BindingWhenOnSyntax; + toDynamicValue(func: (context: Context) => T): BindingWhenOnSyntax; toConstructor(constructor: Newable): BindingWhenOnSyntax; toFactory(factory: FactoryCreator): BindingWhenOnSyntax; toFunction(func: T): BindingWhenOnSyntax; toAutoFactory(serviceIdentifier: ServiceIdentifier): BindingWhenOnSyntax; toProvider(provider: ProviderCreator): BindingWhenOnSyntax; } - + export interface BindingWhenOnSyntax extends BindingWhenSyntax, BindingOnSyntax {} - + export interface BindingWhenSyntax { when(constraint: (request: Request) => boolean): BindingOnSyntax; whenTargetNamed(name: string): BindingOnSyntax; @@ -238,7 +245,7 @@ declare namespace inversify { whenAnyAncestorMatches(constraint: (request: Request) => boolean): BindingOnSyntax; whenNoAncestorMatches(constraint: (request: Request) => boolean): BindingOnSyntax; } - + } export var Kernel: interfaces.KernelConstructor; @@ -248,30 +255,19 @@ declare namespace inversify { export function tagged(metadataKey: string, metadataValue: any): (target: any, targetKey: string, index?: number) => any; export function named(name: string): (target: any, targetKey: string, index?: number) => any; export function targetName(name: string): (target: any, targetKey: string, index: number) => any; + export function unmanaged(): (target: any, targetKey: string, index: number) => any; export function inject(serviceIdentifier: interfaces.ServiceIdentifier): (target: any, targetKey: string, index?: number) => any; + export function guid(): string; export function multiInject( serviceIdentifier: interfaces.ServiceIdentifier ): (target: any, targetKey: string, index?: number) => any; - export function makePropertyInjectDecorator(kernel: interfaces.Kernel): - (serviceIdentifier: (string|Symbol|interfaces.Newable)) => (proto: any, key: string) => void; - - export function makePropertyInjectNamedDecorator(kernel: interfaces.Kernel): - (serviceIdentifier: (string|Symbol|interfaces.Newable), named: string) => (proto: any, key: string) => void; - - export function makePropertyInjectTaggedDecorator(kernel: interfaces.Kernel): - (serviceIdentifier: (string|Symbol|interfaces.Newable), key: string, value: any) => (proto: any, propertyName: string) => void; - - export function makePropertyMultiInjectDecorator(kernel: interfaces.Kernel): - (serviceIdentifier: (string|Symbol|interfaces.Newable)) => (proto: any, key: string) => void; - // constraint helpers export var traverseAncerstors: (request: interfaces.Request, constraint: (request: interfaces.Request) => boolean) => boolean; export var taggedConstraint: (tag: string) => (value: any) => (request: interfaces.Request) => boolean; export var namedConstraint: (value: any) => (request: interfaces.Request) => boolean; export var typeConstraint: (type: (Function|string)) => (request: interfaces.Request) => boolean; - } declare module "inversify" { diff --git a/isomorphic-fetch/isomorphic-fetch-tests.ts b/isomorphic-fetch/isomorphic-fetch-tests.ts index ddf11f84fe..fefabf2080 100644 --- a/isomorphic-fetch/isomorphic-fetch-tests.ts +++ b/isomorphic-fetch/isomorphic-fetch-tests.ts @@ -1,4 +1,5 @@ /// +/// import fetchImportedViaCommonJS = require('isomorphic-fetch'); import * as fetchImportedViaES6Module from 'isomorphic-fetch'; diff --git a/isomorphic-fetch/isomorphic-fetch.d.ts b/isomorphic-fetch/isomorphic-fetch.d.ts index 19754db0f1..41b63970b3 100644 --- a/isomorphic-fetch/isomorphic-fetch.d.ts +++ b/isomorphic-fetch/isomorphic-fetch.d.ts @@ -3,48 +3,53 @@ // Definitions by: Todd Lucas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare enum RequestContext { - "audio", "beacon", "cspreport", "download", "embed", "eventsource", - "favicon", "fetch", "font", "form", "frame", "hyperlink", "iframe", - "image", "imageset", "import", "internal", "location", "manifest", - "object", "ping", "plugin", "prefetch", "script", "serviceworker", - "sharedworker", "subresource", "style", "track", "video", "worker", - "xmlhttprequest", "xslt" -} -declare enum RequestMode { "same-origin", "no-cors", "cors" } -declare enum RequestCredentials { "omit", "same-origin", "include" } -declare enum RequestCache { - "default", "no-store", "reload", "no-cache", "force-cache", - "only-if-cached" -} -declare enum ResponseType { "basic", "cors", "default", "error", "opaque" } +type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | + "track" | "video"; +type RequestDestination = "" | "document" | "embed" | "font" | "image" | + "manifest" | "media" | "object" | "report" | "script" | "serviceworker" | + "sharedworker" | "style" | "worker" | "xslt"; +type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; +type RequestCredentials = "omit" | "same-origin" | "include"; +type RequestCache = + "default" | "no-store" | "reload" | "no-cache" | "force-cache" | + "only-if-cached"; +type RequestRedirect = "follow" | "error" | "manual"; -declare type HeaderInit = Headers | Array; -declare type BodyInit = ArrayBuffer | ArrayBufferView | Blob | FormData | string; -declare type RequestInfo = Request | string; +type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | + "opaqueredirect"; -interface RequestInit { - method?: string; - headers?: HeaderInit | { [index: string]: string }; - body?: BodyInit; - mode?: string | RequestMode; - credentials?: string | RequestCredentials; - cache?: string | RequestCache; -} +type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | + "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | + "strict-origin-when-cross-origin" | "unsafe-url"; interface IHeaders { - get(name: string): string; - getAll(name: string): Array; - has(name: string): boolean; -} - -declare class Headers implements IHeaders { append(name: string, value: string): void; - delete(name: string):void; + delete(name: string): void; get(name: string): string; getAll(name: string): Array; has(name: string): boolean; set(name: string, value: string): void; + + // TODO: iterable; + forEach(callback: (value: string, index: number, headers: IHeaders) => void, thisArg?: any): void; + // NOTE: The following are supported by whatwg-fetch but not node-fetch. + // entries(): IterableIterator<[string, string]>; + // keys(): IterableIterator; + // values(): IterableIterator; +} + +type HeadersInit = Headers | Array | { [index: string]: string }; + +declare class Headers implements IHeaders { + constructor(init?: HeadersInit); + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string; + getAll(name: string): Array; + has(name: string): boolean; + set(name: string, value: string): void; + + forEach(callback: (value: string, index: number, headers: IHeaders) => void, thisArg?: any): void; } interface IBody { @@ -70,49 +75,109 @@ declare class Body implements IBody { interface IRequest extends IBody { method: string; url: string; - headers: Headers; - context: string | RequestContext; - referrer: string; - mode: string | RequestMode; - credentials: string | RequestCredentials; - cache: string | RequestCache; + headers: IHeaders; + + type: RequestType; + destination: RequestDestination; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + mode: RequestMode; + credentials: RequestCredentials; + cache: RequestCache; + redirect?: RequestRedirect; + integrity?: string; + + clone(): IRequest; } +type BodyInit = Blob | ArrayBufferView | ArrayBuffer | FormData /* | URLSearchParams */ | string; + +interface RequestInit { + method?: string; + headers?: HeadersInit; + body?: BodyInit; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + mode?: RequestMode; + credentials?: RequestCredentials; + cache?: RequestCache; + redirect?: RequestRedirect; + integrity?: string; + window?: any; // can only be set to null +} + +type RequestInfo = IRequest | string; + declare class Request extends Body implements IRequest { - constructor(input: string | Request, init?: RequestInit); + constructor(input: RequestInfo, init?: RequestInit); + method: string; url: string; - headers: Headers; - context: string | RequestContext; + headers: IHeaders; + + type: RequestType + destination: RequestDestination; referrer: string; - mode: string | RequestMode; - credentials: string | RequestCredentials; - cache: string | RequestCache; + referrerPolicy: ReferrerPolicy; + mode: RequestMode; + credentials: RequestCredentials; + cache: RequestCache; + redirect: RequestRedirect; + integrity: string; + + clone(): IRequest; } interface IResponse extends IBody { + type: ResponseType; + url: string; + redirected: boolean; status: number; statusText: string; ok: boolean; headers: IHeaders; - type: string | ResponseType; - size: number; - timeout: number; - redirect(url: string, status: number): IResponse; - error(): IResponse; + // size: number; + // timeout: number; + body: any; + trailer: Promise; + clone(): IResponse; } -interface IFetchStatic { - Promise: any; - Headers: IHeaders - Request: IRequest; - Response: IResponse; - (url: string | IRequest, init?: RequestInit): Promise; +type ResponseBodyInit = BodyInit; + +interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; } -declare var fetch: IFetchStatic; +declare class Response extends Body implements IResponse { + constructor(body?: ResponseBodyInit, init?: ResponseInit); + + static redirect(url: string, status?: number): IResponse; + static error(): IResponse; + + type: ResponseType + + url: string; + redirected: boolean; + status: number; + statusText: string; + ok: boolean; + headers: IHeaders; + body: any; + trailer: Promise; + + clone(): IResponse; +} + +interface Window { + fetch(url: RequestInfo, init?: RequestInit): Promise; +} + +declare var fetch: typeof window.fetch; declare module "isomorphic-fetch" { export = fetch; diff --git a/jake/jake.d.ts b/jake/jake.d.ts index 3174a7b94c..5766b64093 100644 --- a/jake/jake.d.ts +++ b/jake/jake.d.ts @@ -207,7 +207,7 @@ declare namespace jake{ * * @event complete */ - export class Task implements NodeJS.EventEmitter { + export class Task extends NodeJS.EventEmitter { /** * @name name The name of the Task * @param prereqs Prerequisites to be run before this task diff --git a/jasmine-node/jasmine-node.d.ts b/jasmine-node/jasmine-node.d.ts index f547f844f6..f535d8c3e3 100644 --- a/jasmine-node/jasmine-node.d.ts +++ b/jasmine-node/jasmine-node.d.ts @@ -7,6 +7,12 @@ declare function it(expectation:string, assertion:(done:(err?:any) => void) => void, timeout?:number):void; +declare namespace jasmine { + interface Env { + defaultTimeoutInterval: number; + } +} + declare module "jasmine-node" { interface ExecuteSpecsOptions { specFolders: string[], diff --git a/java/java-tests.ts b/java/java-tests.ts index 568bd35a8c..7f5ff7874a 100644 --- a/java/java-tests.ts +++ b/java/java-tests.ts @@ -1,5 +1,5 @@ /// -/// +/// import java = require('java'); import BluePromise = require('bluebird'); diff --git a/js-beautify/js-beautify-tests.ts b/js-beautify/js-beautify-tests.ts index bcd431c2bd..6bef16e042 100644 --- a/js-beautify/js-beautify-tests.ts +++ b/js-beautify/js-beautify-tests.ts @@ -1,7 +1,16 @@ /// -var simple: string = js_beautify("console.log('Hello world!');"); +let bCss = js_beautify.css("body{display:none;}"); +bCss = js_beautify.css_beautify("body{display:none;}"); +let bHtml = js_beautify.html("
"); +bHtml = js_beautify.html_beautify("
"); + +let optHtml = {}; +let optCss = {}; +let optjs = {}; + +var simple: string = js_beautify("console.log('Hello world!');"); var full: string = js_beautify( "console.log('Hello world!');", { diff --git a/js-beautify/js-beautify.d.ts b/js-beautify/js-beautify.d.ts index 16cbbed679..ea67ddbad2 100644 --- a/js-beautify/js-beautify.d.ts +++ b/js-beautify/js-beautify.d.ts @@ -1,10 +1,6 @@ // Type definitions for js_beautify // Project: https://github.com/beautify-web/js-beautify/ -// Definitions by: Josh Goldberg -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Type definitions for js_beautify -// Project: https://github.com/beautify-web/js-beautify/ -// Definitions by: Josh Goldberg +// Definitions by: Josh Goldberg , Hans Windhoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface JsBeautifyOptions { @@ -17,7 +13,7 @@ interface JsBeautifyOptions { max_preserve_newlines?: number; jslint_happy?: boolean; space_after_anon_function?: boolean; - brace_style?: string; + brace_style?: 'collapse-preserve-inline'|'collapse'|'expand'|'end-expand'|'none'; keep_array_indentation?: boolean; keep_function_indentation?: boolean; space_before_conditional?: boolean; @@ -25,11 +21,54 @@ interface JsBeautifyOptions { eval_code?: boolean; unescape_strings?: boolean; wrap_line_length?: number; - wrap_attributes?: string; + wrap_attributes?: 'auto'|'force' ; wrap_attributes_indent_size?: number; end_with_newline?: boolean; } -declare var js_beautify: { - (js_source_text: string, options?: JsBeautifyOptions): string; -}; +interface HTMLBeautifyOptions { + indent_size?: number; + indent_char?: string; + indent_with_tabs?: boolean; + eol?: string; + end_with_newline?: boolean; + preserve_newlines?: boolean; + max_preserve_newlines?: number; + indent_inner_html?: boolean; + brace_style?: 'collapse-preserve-inline'|'collapse'|'expand'|'end-expand'|'none'; + indent_scripts?: boolean; + wrap_line_length?: number; + wrap_attributes?: 'auto'|'force' ; + wrap_attributes_indent_size?: number; + unformatted?: string; + extra_liners?: string; +} + +interface CSSBeautifyOptions { + indent_size?: number; + indent_char?: string; + indent_with_tabs?: boolean; + eol?: string; + end_with_newline?: boolean; + selector_separator_newline?: boolean; + newline_between_rules?: boolean; +} + +interface jsb{ + (js_source_text: string, options?: JsBeautifyOptions) : string ; + js:(js_source_text: string, options?: JsBeautifyOptions) => string ; + beautify_js:(js_source_text: string, options?: JsBeautifyOptions) => string ; + + css:(js_source_text: string, options?: CSSBeautifyOptions) => string ; + css_beautify:(js_source_text: string, options?: CSSBeautifyOptions) => string ; + + html:(js_source_text: string, options?: HTMLBeautifyOptions) => string ; + html_beautify:(js_source_text: string, options?: HTMLBeautifyOptions) => string ; +} + +declare var js_beautify:jsb; +declare module "js-beautify" +{ + export = js_beautify; +} + diff --git a/js-data/js-data.d.ts b/js-data/js-data.d.ts index da87e81ccc..f7fc785c82 100644 --- a/js-data/js-data.d.ts +++ b/js-data/js-data.d.ts @@ -57,7 +57,7 @@ declare namespace JSData { scopes?:Object; strategy?: string; upsert?: boolean; - useClass?: boolean; + useClass?: boolean | any; useFilter?: boolean; watchChanges?:boolean; } diff --git a/json-editor/json-editor.d.ts b/json-editor/json-editor.d.ts index cbb0c9c29c..280c17e70f 100644 --- a/json-editor/json-editor.d.ts +++ b/json-editor/json-editor.d.ts @@ -39,7 +39,7 @@ type JSONEditorOptions = { /** * The icon library to use for the editor. */ - iconlib?: boolean; + iconlib?: "bootstrap2" | "bootstrap3" | "foundation2" | "foundation3" | "jqueryui" | "fontawesome3" | "fontawesome4"; /** * If true, objects can only contain properties defined with the properties keyword. */ @@ -75,7 +75,7 @@ type JSONEditorOptions = { /** * The CSS theme to use. */ - theme?: string; + theme?: "barebones" | "html" | "bootstrap2" | "bootstrap3" | "foundation3" | "foundation4" | "foundation5" | "foundation6" | "jqueryui"; /** * If true, only required properties will be included by default. */ diff --git a/jsoneditor/jsoneditor-tests.ts b/jsoneditor/jsoneditor-tests.ts new file mode 100644 index 0000000000..99bbb51b92 --- /dev/null +++ b/jsoneditor/jsoneditor-tests.ts @@ -0,0 +1,50 @@ +/// + +import JSONEditor, {JSONEditorMode, JSONEditorNode, JSONEditorOptions} from 'jsoneditor'; + +let options: JSONEditorOptions; +options = { + ace: ace, + //ajv: Ajv({allErrors: true, verbose: true}) + onChange() {}, + onEditable(node: JSONEditorNode) { + return true; + }, + onError(error: Error) {}, + onModeChange(newMode: JSONEditorMode, oldMode: JSONEditorMode) {}, + escapeUnicode: false, + sortObjectKeys: true, + history: true, + mode: 'tree', + modes: ['tree', 'view', 'form', 'code', 'text'], + name: 'foo', + schema: {}, + search: false, + indentation: 2, + theme: 'default' +}; +options = { + onEditable(node: JSONEditorNode) { + return {field: true, value: false}; + } +}; + +let jsonEditor: JSONEditor; +jsonEditor = new JSONEditor(document.body); +jsonEditor = new JSONEditor(document.body, {}); +jsonEditor = new JSONEditor(document.body, options, {foo: 'bar'}); + +jsonEditor.collapseAll(); +jsonEditor.destroy(); +jsonEditor.expandAll(); +jsonEditor.focus(); +jsonEditor.set({foo: 'bar'}); +jsonEditor.setMode('text'); +jsonEditor.setName('foo'); +jsonEditor.setName(); +jsonEditor.setSchema({}); +jsonEditor.setText('{foo: 1}'); + +const json: any = jsonEditor.get(); +const name: string = jsonEditor.getName(); +const jsonString: string = jsonEditor.getText(); diff --git a/jsoneditor/jsoneditor.d.ts b/jsoneditor/jsoneditor.d.ts new file mode 100644 index 0000000000..ea68a751a4 --- /dev/null +++ b/jsoneditor/jsoneditor.d.ts @@ -0,0 +1,52 @@ +// Type definitions for jsoneditor v5.5.7 +// Project: https://github.com/josdejong/jsoneditor +// Definitions by: Alejandro Sánchez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'jsoneditor' { + export interface JSONEditorNode { + field: string; + value: string; + path: Array; + } + + export type JSONEditorMode = 'tree' | 'view' | 'form' | 'code' | 'text'; + + export interface JSONEditorOptions { + ace?: AceAjax.Ace; + ajv?: any; // Any for now, since ajv typings aren't A-Ok + onChange?: () => void; + onEditable?: (node: JSONEditorNode) => boolean | {field: boolean, value: boolean}; + onError?: (error: Error) => void; + onModeChange?: (newMode: JSONEditorMode, oldMode: JSONEditorMode) => void; + escapeUnicode?: boolean; + sortObjectKeys?: boolean; + history?: boolean; + mode?: JSONEditorMode; + modes?: Array; + name?: string; + schema?: Object; + search?: boolean; + indentation?: number; + theme?: string; + } + + export default class JSONEditor { + constructor(container: HTMLElement, options?: JSONEditorOptions, json?: Object); + collapseAll(): void; + destroy(): void; + expandAll(): void; + focus(): void; + set(json: Object): void; + setMode(mode: JSONEditorMode): void; + setName(name?: string): void; + setSchema(schema: Object): void; + setText(jsonString: string): void; + get(): any; + getMode(): JSONEditorMode; + getName(): string; + getText(): string; + } +} diff --git a/jspdf/jspdf-tests.ts b/jspdf/jspdf-tests.ts index 385eb7fc4a..7a104554b6 100644 --- a/jspdf/jspdf-tests.ts +++ b/jspdf/jspdf-tests.ts @@ -2,6 +2,8 @@ // From: https://mrrio.github.io/jsPDF/examples/basic.html +import * as jsPDF from 'jspdf'; + function test_simple_two_page_document() { var doc = new jsPDF(); doc.text(20, 20, 'Hello world!'); diff --git a/jspdf/jspdf.d.ts b/jspdf/jspdf.d.ts index 3b0b6cd99b..60246f04a1 100644 --- a/jspdf/jspdf.d.ts +++ b/jspdf/jspdf.d.ts @@ -3,201 +3,207 @@ // Definitions by: Amber Schühmacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare class jsPDF { - constructor(orientation?:any, - unit?:string, - format?:string, - compressPdf?:number); +declare module 'jspdf' { + class jsPDF { + constructor(orientation?:any, + unit?:string, + format?:string, + compressPdf?:number); - CapJoinStyles:any; - version:string; + CapJoinStyles:any; + version:string; - internal: { - 'pdfEscape'(text:string, flags:any): any; - 'getStyle'(style:string) : any; - 'getFont'(): any; - 'getFontSize'():number; - 'getLineHeight'():number; - 'write'(string1:string):any; - 'getCoordinateString'(value:number):number; - 'getVerticalCoordinateString'(value:number):number; - 'collections':any; - 'newObject'():number; - 'newAdditionalObject'():any; - 'newObjectDeferred'():number; - 'newObjectDeferredBegin'(oid:number):void; - 'putStream'(str:string):void; - 'events':any; - 'scaleFactor':number; - 'pageSize': { - width:number; - height:number; + internal: { + 'pdfEscape'(text:string, flags:any): any; + 'getStyle'(style:string) : any; + 'getFont'(): any; + 'getFontSize'():number; + 'getLineHeight'():number; + 'write'(string1:string):any; + 'getCoordinateString'(value:number):number; + 'getVerticalCoordinateString'(value:number):number; + 'collections':any; + 'newObject'():number; + 'newAdditionalObject'():any; + 'newObjectDeferred'():number; + 'newObjectDeferredBegin'(oid:number):void; + 'putStream'(str:string):void; + 'events':any; + 'scaleFactor':number; + 'pageSize': { + width:number; + height:number; + }; + 'output'(type:any, options:any):any; + 'getNumberOfPages'():number; + 'pages':number[]; + 'out'(string:string):void; + 'f2'(number:number):number; + 'getPageInfo'(pageNumberOneBased:number):any; + 'getCurrentPageInfo'():any; }; - 'output'(type:any, options:any):any; - 'getNumberOfPages'():number; - 'pages':number[]; - 'out'(string:string):void; - 'f2'(number:number):number; - 'getPageInfo'(pageNumberOneBased:number):any; - 'getCurrentPageInfo'():any; - }; - addPage():jsPDF; - setPage(n:number):jsPDF; - insertPage(beforePage:number):jsPDF; - movePage(targetPage:number, beforePage:number):jsPDF; - deletePage(n:number):jsPDF; - setDisplayMode(zoom?:string, layout?:string, pmode?:string):jsPDF; - text(text:any, x:any, y:any, flags?:any, angle?:any, align?:any):jsPDF; - lstext(text:string, x:number, y:number, spacing:number):jsPDF; - line(x1:number, y1:number, x2:number, y2:number):any; - clip():void; - lines(lines:any, x:any, y:any, scale?:any, style?:string, closed?:boolean):jsPDF; - rect(x:number, y:number, w:number, h:number, style?:string):jsPDF; - triangle(x1:number, y1:number, x2:number, y2:number, x3:number, y3:number, style:string):jsPDF; - roundedRect(x:number, y:number, w:number, h:number, rx:number, ry:number, style:string):jsPDF; - ellipse(x:number, y:number, rx:number, ry:number, style?:string):jsPDF; - circle(x:number, y:number, r:number, style:string):jsPDF; - setProperties(properties:any):jsPDF; - setFontSize(size:number):jsPDF; - setFont(fontName?:string, fontStyle?:string):jsPDF; - setFontStyle(style:string):jsPDF; - setFontType(style:string):jsPDF; - getFontList():any; - addFont(postScriptName:string, fontName:string, fontStyle:string):string; - setLineWidth(width:number):jsPDF; - setDrawColor(ch1:number|string, ch2?:number, ch3?:number, ch4?:number):jsPDF; - setFillColor(ch1:number|string, ch2?:number, ch3?:number, ch4?:number):jsPDF; - setTextColor(r?:number, g?:number, b?:number):jsPDF; - setLineCap(style:string|number):jsPDF; - setLineJoin(style:string|number):jsPDF; - output(type?:string, options?:any):any; - save(filename:string):jsPDF; + addPage():jsPDF; + setPage(n:number):jsPDF; + insertPage(beforePage:number):jsPDF; + movePage(targetPage:number, beforePage:number):jsPDF; + deletePage(n:number):jsPDF; + setDisplayMode(zoom?:string, layout?:string, pmode?:string):jsPDF; + text(text:any, x:any, y:any, flags?:any, angle?:any, align?:any):jsPDF; + lstext(text:string, x:number, y:number, spacing:number):jsPDF; + line(x1:number, y1:number, x2:number, y2:number):any; + clip():void; + lines(lines:any, x:any, y:any, scale?:any, style?:string, closed?:boolean):jsPDF; + rect(x:number, y:number, w:number, h:number, style?:string):jsPDF; + triangle(x1:number, y1:number, x2:number, y2:number, x3:number, y3:number, style:string):jsPDF; + roundedRect(x:number, y:number, w:number, h:number, rx:number, ry:number, style:string):jsPDF; + ellipse(x:number, y:number, rx:number, ry:number, style?:string):jsPDF; + circle(x:number, y:number, r:number, style:string):jsPDF; + setProperties(properties:any):jsPDF; + setFontSize(size:number):jsPDF; + setFont(fontName?:string, fontStyle?:string):jsPDF; + setFontStyle(style:string):jsPDF; + setFontType(style:string):jsPDF; + getFontList():any; + addFont(postScriptName:string, fontName:string, fontStyle:string):string; + setLineWidth(width:number):jsPDF; + setDrawColor(ch1:number|string, ch2?:number, ch3?:number, ch4?:number):jsPDF; + setFillColor(ch1:number|string, ch2?:number, ch3?:number, ch4?:number):jsPDF; + setTextColor(r?:number, g?:number, b?:number):jsPDF; + setLineCap(style:string|number):jsPDF; + setLineJoin(style:string|number):jsPDF; + output(type?:string, options?:any):any; + save(filename:string):jsPDF; - /** - * jsPDF plugins below: - * - * - AddHTML - * - AddImage - * - Annotations - * - AutoPrint - * - Canvas - * - Cell - * - Context2D - * - FromHTML - * - JavaScript - * - PNG - * - split_text_to_size - * - SVG - * - total_pages - */ + /** + * jsPDF plugins below: + * + * - AddHTML + * - AddImage + * - Annotations + * - AutoPrint + * - Canvas + * - Cell + * - Context2D + * - FromHTML + * - JavaScript + * - PNG + * - split_text_to_size + * - SVG + * - total_pages + */ - // jsPDF plugin: addHTML - addHTML(element:any, x:number, y:number, options:any, callback:Function):jsPDF; - addHTML(element:any, callback:Function):jsPDF; + // jsPDF plugin: addHTML + addHTML(element:any, x:number, y:number, options:any, callback:Function):jsPDF; + addHTML(element:any, callback:Function):jsPDF; - // jsPDF plugin: addImage - color_spaces:any; - decode:any; - image_compression:any; + // jsPDF plugin: addImage + color_spaces:any; + decode:any; + image_compression:any; - sHashCode(str:string):any; - isString(object:any):boolean; - extractInfoFromBase64DataURI(dataURI:string):any[]; - supportsArrayBuffer():boolean; - isArrayBuffer(object:any):boolean; - isArrayBufferView(object:any):boolean; - binaryStringToUint8Array(binary_string:string):Uint8Array; - arrayBufferToBinaryString(buffer:any):string; - arrayBufferToBase64(arrayBuffer:ArrayBuffer):string; - createImageInfo(data:any, wd:any, ht:any, cs:any, bpc:any, imageIndex:number, alias:any, f?:any, dp?:any, trns?:any, pal?:any, smask?:any):any; - addImage(imageData?:any, format?:any, x?:number, y?:number, w?:number, h?:number, alias?:any, compression?:any, rotation?:any):jsPDF; - processJPEG(data:any, index:number, alias:any, compression?:any, dataAsBinaryString?:string):any; - processJPG():any; + sHashCode(str:string):any; + isString(object:any):boolean; + extractInfoFromBase64DataURI(dataURI:string):any[]; + supportsArrayBuffer():boolean; + isArrayBuffer(object:any):boolean; + isArrayBufferView(object:any):boolean; + binaryStringToUint8Array(binary_string:string):Uint8Array; + arrayBufferToBinaryString(buffer:any):string; + arrayBufferToBase64(arrayBuffer:ArrayBuffer):string; + createImageInfo(data:any, wd:any, ht:any, cs:any, bpc:any, imageIndex:number, alias:any, f?:any, dp?:any, trns?:any, pal?:any, smask?:any):any; + addImage(imageData?:any, format?:any, x?:number, y?:number, w?:number, h?:number, alias?:any, compression?:any, rotation?:any):jsPDF; + processJPEG(data:any, index:number, alias:any, compression?:any, dataAsBinaryString?:string):any; + processJPG():any; - // jsPDF plugin: Annotations - annotationPlugin:any; - createAnnotation(options:any):void; - link(x:number, y:number, w:number, h:number, options:any):void; - textWithLink(text:string, x:number, y:number, options:any):number; - getTextWidth(text:string):number; - getLineHeight():number; + // jsPDF plugin: Annotations + annotationPlugin:any; + createAnnotation(options:any):void; + link(x:number, y:number, w:number, h:number, options:any):void; + textWithLink(text:string, x:number, y:number, options:any):number; + getTextWidth(text:string):number; + getLineHeight():number; - // jsPDF plugin: AutoPrint - autoPrint():jsPDF; + // jsPDF plugin: AutoPrint + autoPrint():jsPDF; - // jsPDF plugin: Canvas - canvas: { - getContext():any; - style:any; - }; + // jsPDF plugin: Canvas + canvas: { + getContext():any; + style:any; + }; - // jsPDF plugin: Cell - setHeaderFunction(func:Function):void; - getTextDimensions(txt:string):any; - cellAddPage():void; - cellInitialize():void; - cell(x:number, y:number, w:number, h:number, txt:string, ln:number, align:string):jsPDF; - arrayMax(array:any[], comparisonFn?:Function):number; - table(x:number, y:number, data:any, headers:string[], config:any):jsPDF; - calculateLineHeight(headerNames:string[], columnWidths:number[], model:any[]):number; - setTableHeaderRow(config:any[]):void; - printHeaderRow(lineNumber:number, new_page?:boolean):void; + // jsPDF plugin: Cell + setHeaderFunction(func:Function):void; + getTextDimensions(txt:string):any; + cellAddPage():void; + cellInitialize():void; + cell(x:number, y:number, w:number, h:number, txt:string, ln:number, align:string):jsPDF; + arrayMax(array:any[], comparisonFn?:Function):number; + table(x:number, y:number, data:any, headers:string[], config:any):jsPDF; + calculateLineHeight(headerNames:string[], columnWidths:number[], model:any[]):number; + setTableHeaderRow(config:any[]):void; + printHeaderRow(lineNumber:number, new_page?:boolean):void; - // jsPDF plugin: Context2D - context2d: { - pageWrapXEnabled: boolean; - pageWrapYEnabled: boolean; - pageWrapX: number; - pageWrapY: number; - f2(number:number):number; - fillRect(x:number, y:number, w:number, h:number):void; - strokeRect(x:number, y:number, w:number, h:number):void; - clearRect(x:number, y:number, w:number, h:number):void; - save():void; - restore():void; - beginPath():void; - closePath():void; - setFillStyle(style:string):void; - setStrokeStyle(style:string):void; - fillText(text:string|string[], x:number, y:number, maxWidth:number):void; - strokeText(text:string|string[], x:number, y:number, maxWidth:number):void; - setFont(font:string):void; - setTextBaseline(baseline:string):void; - getTextBaseline():string; - setLineWidth(width:number):void; - setLineCap(style:string):void; - setLineJoin(style:string):void; - moveTo(x:number, y:number):void; - lastBreak: number; - pageBreaks: any[]; - lineTo(x:number, y:number):void; - bezierCurveTo(x1:number, y1:number, x2:number, y2:number, x:number, y:number):void; - quadraticCurveTo(x1:number, y1:number, x:number, y:number):void; - arc(x:number, y:number, radius:number, startAngle:number, endAngle:number, anticlockwise:any):void; - drawImage(img:string, x:number, y:number, w:number, h:number, x2?:number, y2?:number, w2?:number, h2?:number):void; - stroke():void; - fill():void; - translate(x:number, y:number):void; - measureText(text:string):number; - }; + // jsPDF plugin: Context2D + context2d: { + pageWrapXEnabled: boolean; + pageWrapYEnabled: boolean; + pageWrapX: number; + pageWrapY: number; + f2(number:number):number; + fillRect(x:number, y:number, w:number, h:number):void; + strokeRect(x:number, y:number, w:number, h:number):void; + clearRect(x:number, y:number, w:number, h:number):void; + save():void; + restore():void; + beginPath():void; + closePath():void; + setFillStyle(style:string):void; + setStrokeStyle(style:string):void; + fillText(text:string|string[], x:number, y:number, maxWidth:number):void; + strokeText(text:string|string[], x:number, y:number, maxWidth:number):void; + setFont(font:string):void; + setTextBaseline(baseline:string):void; + getTextBaseline():string; + setLineWidth(width:number):void; + setLineCap(style:string):void; + setLineJoin(style:string):void; + moveTo(x:number, y:number):void; + lastBreak: number; + pageBreaks: any[]; + lineTo(x:number, y:number):void; + bezierCurveTo(x1:number, y1:number, x2:number, y2:number, x:number, y:number):void; + quadraticCurveTo(x1:number, y1:number, x:number, y:number):void; + arc(x:number, y:number, radius:number, startAngle:number, endAngle:number, anticlockwise:any):void; + drawImage(img:string, x:number, y:number, w:number, h:number, x2?:number, y2?:number, w2?:number, h2?:number):void; + stroke():void; + fill():void; + translate(x:number, y:number):void; + measureText(text:string):number; + }; - // jsPDF plugin: fromHTML - fromHTML(HTML:string | HTMLElement, x:number, y:number, settings?:any, callback?:Function, margins?:any):jsPDF; + // jsPDF plugin: fromHTML + fromHTML(HTML:string | HTMLElement, x:number, y:number, settings?:any, callback?:Function, margins?:any):jsPDF; - // jsPDF plugin: JavaScript - addJS(txt:string):jsPDF; + // jsPDF plugin: JavaScript + addJS(txt:string):jsPDF; - // jsPDF plugin: PNG - processPNG(imageData:any, imageIndex:number, alias:string, compression:any, dataAsBinaryString:string):any; + // jsPDF plugin: PNG + processPNG(imageData:any, imageIndex:number, alias:string, compression:any, dataAsBinaryString:string):any; - // jsPDF plugin: split_text_to_size - getCharWidthsArray(text:string, options?:any):any[]; - getStringUnitWidth(text:string, options?:any):number; - splitTextToSize(text:string, maxlen:number, options?:any):any; + // jsPDF plugin: split_text_to_size + getCharWidthsArray(text:string, options?:any):any[]; + getStringUnitWidth(text:string, options?:any):number; + splitTextToSize(text:string, maxlen:number, options?:any):any; - // jsPDF plugin: SVG - addSVG(svgtext:string, x:number, y:number, w?:number, h?:number):jsPDF; + // jsPDF plugin: SVG + addSVG(svgtext:string, x:number, y:number, w?:number, h?:number):jsPDF; - // jsPDF plugin: total_pages - putTotalPages(pageExpression:string):jsPDF; + // jsPDF plugin: total_pages + putTotalPages(pageExpression:string):jsPDF; + } + + namespace jsPDF {} + + export = jsPDF; } diff --git a/jstree/jstree.d.ts b/jstree/jstree.d.ts index dde9a24b67..2292da7f9c 100644 --- a/jstree/jstree.d.ts +++ b/jstree/jstree.d.ts @@ -1,8 +1,8 @@ -// Type definitions for jsTree v3.3.1 +// Type definitions for jsTree v3.3.2 // Project: http://www.jstree.com/ // Definitions by: Adam Pluciński // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// 1 commit 3b8f55d3797cd299eb36695b62d75c2313a3e3b3 2016-05-10 +// 1 commit bb0473ae8cfc205585b6404ef86f650df2f6996e 2016-08-15 /// @@ -465,6 +465,7 @@ interface JSTreeStaticDefaultsContextMenu { * * `separator_after` - a boolean indicating if there should be a separator after this item * * `_disabled` - a boolean indicating if this action should be disabled * * `label` - a string - the name of the action (could be a function returning a string) + * * `title` - a string - an optional tooltip for the item * * `action` - a function to be executed if this item is chosen, the function will receive * * `icon` - a string, can be a path to an icon or a className, if using an image that is in the current directory use a `./` prefix, otherwise it will be detected as a class * * `shortcut` - keyCode which will trigger the action if the menu is open (for example `113` for rename, which equals F2) @@ -1339,6 +1340,8 @@ interface JSTree extends JQuery { * @param {Boolean} options.no_id do not return ID * @param {Boolean} options.no_children do not include children * @param {Boolean} options.no_data do not include node data + * @param {Boolean} options.no_li_attr do not include LI attributes + * @param {Boolean} options.no_a_attr do not include A attributes * @param {Boolean} options.flat return flat JSON instead of nested * @return {Object} */ @@ -1882,6 +1885,16 @@ interface JSTreeGetJsonOptions { */ no_data: boolean; + /** + * do not include LI attributes + */ + no_li_attr: boolean; + + /** + * do not include A attributes + */ + no_a_attr: boolean; + /** * return flat JSON instead of nested */ diff --git a/jwt-client/jwt-client-tests.ts b/jwt-client/jwt-client-tests.ts new file mode 100644 index 0000000000..c686800078 --- /dev/null +++ b/jwt-client/jwt-client-tests.ts @@ -0,0 +1,6 @@ +/// + +import * as JWT from "jwt-client"; +var token = 'eyJpc3MiOiJ0b3B0YWwuY29tIiwiZXhwIjoxNDI2NDIwODAwLCJodHRwOi8vdG9wdGFsLmNvbS9qd3RfY2xhaW1zL2lzX2FkbWluIjp0cnVlLCJjb21wYW55IjoiVG9wdGFsIiwiYXdlc29tZSI6dHJ1ZX0'; +var session = JWT.read(token); +console.log('session is', session); diff --git a/jwt-client/jwt-client.d.ts b/jwt-client/jwt-client.d.ts new file mode 100644 index 0000000000..4f6ca95d88 --- /dev/null +++ b/jwt-client/jwt-client.d.ts @@ -0,0 +1,42 @@ +// Type definitions for jwt-client v0.2.1 +// Project: https://github.com/pauldijou/jwt-client +// Definitions by: Timoteo Ponce +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare module "jwt-client"{ + + interface JWTHeader{ + typ: string; + alg: string; + } + + interface JWTObject{ + header: JWTHeader; + claim: any; + signature: string; + } + + /** + * Read a string value (normally an HTTP header) + * from JSON Web Token to an Object + */ + function read(header:string):JWTObject; + + /** + * Given a JWT object, stringify it back to + * its JWT representation. + */ + function write(value:JWTObject):string; + + function keep(value:JWTObject, key?:any, storate?: any):void; + + function remember():void; + + function forget():void; + + function get():string; + + function validate(value:JWTObject, issuer?:any, audience?: any):boolean; +} + diff --git a/karma-fixture/karma-fixture-tests.ts b/karma-fixture/karma-fixture-tests.ts new file mode 100644 index 0000000000..b3a1d8e51c --- /dev/null +++ b/karma-fixture/karma-fixture-tests.ts @@ -0,0 +1,10 @@ +/// + +fixture.setBase('fixtures/base/path'); +fixture.load('test1.html', 'test1.json', false); +fixture.load('test1.html', 'test2.html', 'test1.json'); +fixture.set('', true); +fixture.set('', ''); +fixture.cleanup(); +fixture.el.firstChild; +JSON.stringify(fixture.json[0]); diff --git a/karma-fixture/karma-fixture.d.ts b/karma-fixture/karma-fixture.d.ts new file mode 100644 index 0000000000..bc89b1b723 --- /dev/null +++ b/karma-fixture/karma-fixture.d.ts @@ -0,0 +1,27 @@ +// Type definitions for karma-fixture 0.2.6 +// Project: https://github.com/billtrik/karma-fixture +// Definitions by: Ezekiel Victor +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace fixture { + export var el: HTMLElement; + export var json: any[]; + + export function load(...files: string[]): any; + export function load(file1: string, append?: boolean): any; + export function load(file1: string, file2: string, append?: boolean): any; + export function load(file1: string, file2: string, file3: string, append?: boolean): any; + export function load(file1: string, file2: string, file3: string, file4: string, append?: boolean): any; + export function load(file1: string, file2: string, file3: string, file4: string, file5: string, append?: boolean): any; + + export function set(...htmlStrs: string[]): HTMLElement|HTMLElement[]; + export function set(htmlStr1: string, append?: boolean): HTMLElement|HTMLElement[]; + export function set(htmlStr1: string, htmlStr2: string, append?: boolean): HTMLElement|HTMLElement[]; + export function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, append?: boolean): HTMLElement|HTMLElement[]; + export function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, htmlStr4: string, append?: boolean): HTMLElement|HTMLElement[]; + export function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, htmlStr4: string, htmlStr5: string, append?: boolean): HTMLElement|HTMLElement[]; + + export function cleanup(): void; + + export function setBase(fixtureBasePath: string): void; +} diff --git a/karma/karma.d.ts b/karma/karma.d.ts index 95c1baede4..c6f9bc0043 100644 --- a/karma/karma.d.ts +++ b/karma/karma.d.ts @@ -3,7 +3,7 @@ // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /// /// diff --git a/kendo-ui/kendo-ui.d.ts b/kendo-ui/kendo-ui.d.ts index d90c5f2356..e8f02f1776 100644 --- a/kendo-ui/kendo-ui.d.ts +++ b/kendo-ui/kendo-ui.d.ts @@ -89,40 +89,10 @@ declare namespace kendo { }; }; - var cultures: {[culture: string] : { - name?: string; - calendar?: { - AM: string[]; - PM: string[]; - days: { - names: string[]; - namesAbbr: string[]; - namesShort: string[]; - firstDay: number; - }; - months: { - names: string[]; - namesAbbr: string[]; - }; - patterns: { - D: string; - F: string; - G: string; - M: string; - T: string; - Y: string; - d: string; - g: string; - m: string; - s: string; - t: string; - u: string; - y: string; - }; - twoDigitYearMax: number; - }; - calendars?: { - standard: { + var cultures: { + [culture: string]: { + name?: string; + calendar?: { AM: string[]; PM: string[]; days: { @@ -152,25 +122,57 @@ declare namespace kendo { }; twoDigitYearMax: number; }; - }; - numberFormat?: { - currency: { + calendars?: { + standard: { + AM: string[]; + PM: string[]; + days: { + names: string[]; + namesAbbr: string[]; + namesShort: string[]; + firstDay: number; + }; + months: { + names: string[]; + namesAbbr: string[]; + }; + patterns: { + D: string; + F: string; + G: string; + M: string; + T: string; + Y: string; + d: string; + g: string; + m: string; + s: string; + t: string; + u: string; + y: string; + }; + twoDigitYearMax: number; + }; + }; + numberFormat?: { + currency: { + decimals: number; + groupSize: number[]; + pattern: string[]; + symbol: string; + }; decimals: number; groupSize: number[]; pattern: string[]; - symbol: string; + percent: { + decimals: number; + groupSize: number[]; + pattern: string[]; + symbol: string; + }; }; - decimals: number; - groupSize: number[]; - pattern: string[]; - percent: { - decimals: number; - groupSize: number[]; - pattern: string[]; - symbol: string; - }; - }; - }}; + } + }; function format(format: string, ...values: any[]): string; @@ -488,8 +490,8 @@ declare namespace kendo.data { change(e: Object): void; start(source: kendo.Observable): void; stop(source: kendo.Observable): void; - get (): any; - set (value: any): void; + get(): any; + set(value: any): void; destroy(): void; } @@ -500,7 +502,7 @@ declare namespace kendo.data { } class EventBinding extends Binding { - get (): void; + get(): void; } class TemplateBinding extends Binding { @@ -531,7 +533,7 @@ declare namespace kendo.data { interface BinderOptions { } - class ObservableObject extends Observable{ + class ObservableObject extends Observable { constructor(value?: any); uid: string; init(value?: any): void; @@ -571,6 +573,7 @@ declare namespace kendo.data { isAllDay?: boolean; id?: any; start?: Date; + taskId?: number; startTimezone?: string; recurrenceId?: any; recurrenceRule?: string; @@ -583,7 +586,7 @@ declare namespace kendo.data { static fields: DataSourceSchemaModelFields; constructor(data?: SchedulerEventData); - + taskId: number; description: string; end: Date; endTimezone: string; @@ -2653,7 +2656,7 @@ declare namespace kendo.ui { separator?: string; suggest?: boolean; headerTemplate?: string|Function; - template?: string|Function; + template?: string | Function; valuePrimitive?: boolean; virtual?: boolean|AutoCompleteVirtual; change?(e: AutoCompleteChangeEvent): void; @@ -4471,6 +4474,7 @@ declare namespace kendo.ui { width?: string|number; values?: any; menu?: boolean; + type?: any; } interface GridEditable { @@ -5890,6 +5894,7 @@ declare namespace kendo.ui { destroy(): void; enable(enable: boolean): void; value(): any; + values(): any; value(selectionStart: number, selectionEnd: number): void; resize(): void; @@ -8834,6 +8839,7 @@ declare namespace kendo.dataviz.ui { type?: string; visible?: boolean; weekStartDay?: number; + axisCrossingValues?: number[]; notes?: ChartCategoryAxisItemNotes; } @@ -10599,6 +10605,7 @@ declare namespace kendo.dataviz.ui { autoBind?: boolean; axisDefaults?: ChartAxisDefaults; categoryAxis?: ChartCategoryAxisItem[]; + valueAxis?: ChartValueAxisItem[]; chartArea?: ChartChartArea; dataSource?: any|any|kendo.data.DataSource; legend?: ChartLegend; @@ -10614,7 +10621,6 @@ declare namespace kendo.dataviz.ui { title?: ChartTitle; tooltip?: ChartTooltip; transitions?: boolean; - valueAxis?: ChartValueAxisItem[]; xAxis?: ChartXAxisItem[]; yAxis?: ChartYAxisItem[]; zoomable?: boolean|ChartZoomable; diff --git a/knex/knex-tests.ts b/knex/knex-tests.ts index 3a00c32551..e894a6be47 100644 --- a/knex/knex-tests.ts +++ b/knex/knex-tests.ts @@ -380,6 +380,8 @@ knex.transaction(function(trx) { // Using trx as a transaction object: knex.transaction(function(trx) { + + trx.raw('') var info: any; var books: any[] = [ diff --git a/knex/knex.d.ts b/knex/knex.d.ts index 64d530ed49..ec6403ed2c 100644 --- a/knex/knex.d.ts +++ b/knex/knex.d.ts @@ -3,7 +3,7 @@ // Definitions by: Qubo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /// declare module "knex" { @@ -12,7 +12,7 @@ declare module "knex" { type Callback = Function; type Client = Function; - type Value = string|number|boolean|Date|Array|Array|Array|Array; + type Value = string|number|boolean|Date|Array|Array|Array|Array|Buffer; type ColumnName = string|Knex.Raw|Knex.QueryBuilder; type TableName = string|Knex.Raw|Knex.QueryBuilder; @@ -330,6 +330,7 @@ declare module "knex" { interface Transaction extends QueryBuilder { commit: any; rollback: any; + raw: Knex.RawBuilder; } // @@ -370,6 +371,7 @@ declare module "knex" { enum(columnName: string, values: Value[]): ColumnBuilder; enu(columnName: string, values: Value[]): ColumnBuilder; json(columnName: string): ColumnBuilder; + jsonb(columnName: string): ColumnBuilder; uuid(columnName: string): ColumnBuilder; comment(val: string): TableBuilder; specificType(columnName: string, type: string): ColumnBuilder; diff --git a/koa-hbs/koa-hbs-tests.ts b/koa-hbs/koa-hbs-tests.ts new file mode 100644 index 0000000000..373c3ab8b9 --- /dev/null +++ b/koa-hbs/koa-hbs-tests.ts @@ -0,0 +1,21 @@ +/// +/// + +import * as Hbs from 'koa-hbs'; +import * as Koa from 'koa'; +import * as Path from 'path'; + +const app = new Koa(); +const hbs = new Hbs(); + +app.use(hbs.middleware({ + viewPath: Path.join(__dirname, './views') +})); + +app.use(function *(next: any) { + yield this.render('index', { + title: 'Hello World!' + }); +}); + +app.listen(3000); diff --git a/koa-hbs/koa-hbs.d.ts b/koa-hbs/koa-hbs.d.ts new file mode 100644 index 0000000000..cd8fc9c5b4 --- /dev/null +++ b/koa-hbs/koa-hbs.d.ts @@ -0,0 +1,55 @@ +// Type definitions for koa-favicon v2.x +// Project: https://github.com/gilt/koa-hbs +// Definitions by: Jacob Malone +// Definitions: https://github.com/jcbmln/DefinitelyTyped + +/* =================== USAGE =================== + + import * as Hbs from "koa-hbs"; + import * as Koa from "koa"; + + var hbs = new Hbs(); + var app = new Koa(); + + app.use(hbs.middleware({ + viewPath: __dirname + '/views' + })); + + app.use(function *() { + yield this.render('main', { + title: 'koa-hbs' + }); + }); + + =============================================== */ + +/// + +declare module "koa-hbs" { + + import * as Koa from "koa"; + + namespace Hbs { + export interface Middleware { + viewPath: Array | string, + handlebars?: Function, + templateOptions?: {}, + extname?: string, + partialsPath?: Array | string, + defaultLayout?: string, + layoutsPath?: string, + contentHelperName?: string, + blockHelperName?: string, + disableCache?: boolean + } + } + + class Hbs { + constructor(); + + middleware(opts: Hbs.Middleware): any; + } + + namespace Hbs {} + export = Hbs; +} diff --git a/koa-router/koa-router-tests.ts b/koa-router/koa-router-tests.ts index deaa7e083d..36d3e6c1c8 100644 --- a/koa-router/koa-router-tests.ts +++ b/koa-router/koa-router-tests.ts @@ -11,6 +11,9 @@ const router = new Router({ }); router + .param('id', function(id, ctx, next) { + next(); + }) .get('/', function (ctx, next) { ctx.body = 'Hello World!'; }) @@ -23,7 +26,7 @@ router .del('/users/:id', function (ctx, next) { // ... }); - + router.get('user', '/users/:id', function (ctx, next) { ctx.body = "sdsd"; }); diff --git a/koa-router/koa-router.d.ts b/koa-router/koa-router.d.ts index d289657c84..25ec962dad 100644 --- a/koa-router/koa-router.d.ts +++ b/koa-router/koa-router.d.ts @@ -30,7 +30,7 @@ declare module "koa-router" { export interface IRouterOptions { /** - * Router prefixes + * Router prefixes */ prefix?: string; /** @@ -52,6 +52,10 @@ declare module "koa-router" { (ctx: Router.IRouterContext, next?: () => any): any; } + export interface IParamMiddleware { + (param: string, ctx: Router.IRouterContext, next?: () => any): any; + } + export interface IRouterAllowedMethodsOptions { /** * throw error instead of setting status and header @@ -141,13 +145,13 @@ declare module "koa-router" { */ get(name: string, path: string, ...middleware: Array): Router; get(path: string, ...middleware: Array): Router; - + /** * HTTP post method */ post(name: string, path: string, ...middleware: Array): Router; post(path: string, ...middleware: Array): Router; - + /** * HTTP put method */ @@ -214,7 +218,7 @@ declare module "koa-router" { /** * Redirect `source` to `destination` URL with optional 30x status `code`. - * + * * Both `source` and `destination` can be route names. */ redirect(source: string, destination: string, code?: number): Router; @@ -245,7 +249,7 @@ declare module "koa-router" { /** * Run middleware for named route parameters. Useful for auto-loading or validation. */ - param(param: string, middleware: Router.IMiddleware): Router; + param(param: string, middleware: Router.IParamMiddleware): Router; /** * Generate URL from url pattern and given `params`. diff --git a/libxmljs/libxmljs-tests.ts b/libxmljs/libxmljs-tests.ts index fbc8628185..8a11481bee 100644 --- a/libxmljs/libxmljs-tests.ts +++ b/libxmljs/libxmljs-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// var libxmljs = require("libxmljs"); diff --git a/localForage/localForage.d.ts b/localForage/localForage.d.ts index 803bde9e57..c727d93b3a 100644 --- a/localForage/localForage.d.ts +++ b/localForage/localForage.d.ts @@ -96,6 +96,6 @@ interface LocalForage { } declare module "localforage" { - export var localforage: LocalForage; - export default localforage; + var localforage: LocalForage; + export = localforage; } diff --git a/lodash/lodash-3.10-tests.ts b/lodash/lodash-3.10-tests.ts index 2616822f6e..3eeff29221 100644 --- a/lodash/lodash-3.10-tests.ts +++ b/lodash/lodash-3.10-tests.ts @@ -9658,6 +9658,25 @@ namespace TestSnakeCase { } } +// _.split +namespace TestSplit { + { + let result: _.LoDashImplicitArrayWrapper; + + result = _('a-b-c').split(); + result = _('a-b-c').split('-'); + result = _('a-b-c').split('-', 2); + } + + { + let result: _.LoDashImplicitArrayWrapper; + + result = _('a-b-c').chain().split(); + result = _('a-b-c').chain().split('-'); + result = _('a-b-c').chain().split('-', 2); + } +} + // _.startCase namespace TestStartCase { { diff --git a/lodash/lodash-3.10.d.ts b/lodash/lodash-3.10.d.ts index aea06a8362..a63d92d0f0 100644 --- a/lodash/lodash-3.10.d.ts +++ b/lodash/lodash-3.10.d.ts @@ -14720,6 +14720,27 @@ declare module _ { snakeCase(): LoDashExplicitWrapper; } + //_.split + interface LoDashImplicitWrapper { + /** + * Splits string by separator. + * + * Note: This method is based on String#split. + * + * @param separator The separator pattern to split by. + * @param limit The length to truncate results to. + * @return Returns the new array with the terms splitted. + */ + split(separator?: RegExp|string, limit?: number): LoDashImplicitArrayWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.split + */ + split(separator?: RegExp|string, limit?: number): LoDashImplicitArrayWrapper; + } + //_.startCase interface LoDashStatic { /** diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 8ec22e98de..42fce74b8b 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -3674,33 +3674,51 @@ namespace TestFind { result = _.find(array); result = _.find(array, listIterator); + result = _.find(array, listIterator, 1); result = _.find(array, ''); + result = _.find(array, '', 1); result = _.find<{a: number}, TResult>(array, {a: 42}); + result = _.find<{a: number}, TResult>(array, {a: 42}, 1); result = _.find(list); result = _.find(list, listIterator); + result = _.find(list, listIterator, 1); result = _.find(list, ''); + result = _.find(list, '', 1); result = _.find<{a: number}, TResult>(list, {a: 42}); + result = _.find<{a: number}, TResult>(list, {a: 42}, 1); result = _.find(dictionary); result = _.find(dictionary, dictionaryIterator); + result = _.find(dictionary, dictionaryIterator, 1); result = _.find(dictionary, ''); + result = _.find(dictionary, '', 1); result = _.find<{a: number}, TResult>(dictionary, {a: 42}); + result = _.find<{a: number}, TResult>(dictionary, {a: 42}, 1); result = _(array).find(); result = _(array).find(listIterator); + result = _(array).find(listIterator, 1); result = _(array).find(''); + result = _(array).find('', 1); result = _(array).find<{a: number}>({a: 42}); + result = _(array).find<{a: number}>({a: 42}, 1); result = _(list).find(); result = _(list).find(listIterator); + result = _(list).find(listIterator, 1); result = _(list).find(''); + result = _(list).find('', 1); result = _(list).find<{a: number}, TResult>({a: 42}); + result = _(list).find<{a: number}, TResult>({a: 42}, 1); result = _(dictionary).find(); result = _(dictionary).find(dictionaryIterator); + result = _(dictionary).find(dictionaryIterator, 1); result = _(dictionary).find(''); + result = _(dictionary).find('', 1); result = _(dictionary).find<{a: number}, TResult>({a: 42}); + result = _(dictionary).find<{a: number}, TResult>({a: 42}, 1); } result = _.findLast([1, 2, 3, 4], function (num) { @@ -4661,32 +4679,38 @@ result = <{a: number}[][]>_({0: {a: 1}, 1: {a: 2}}).partition<{a: number}>('a', // result = _(dictionary).chain().map(['d', 0, 'b']); // } // } +namespace TestReduce { + interface ABC { + [index: string]: number; + a: number; + b: number; + c: number; + } -interface ABC { - [index: string]: number; - a: number; - b: number; - c: number; + result = _.reduce([1, 2, 3], function (sum: number, num: number) { + return sum + num; + }); + + // chained + result = _.chain([1, 2 ,3]).reduce(function (sum: number, num: number) { + return sum + num; + }).value(); + + result = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function (r: ABC, num: number, key: string) { + r[key] = num * 3; + return r; + }, {}); + + result = _([1, 2, 3]).reduce(function (sum: number, num: number) { + return sum + num; + }); + result = _({ 'a': 1, 'b': 2, 'c': 3 }).reduce(function (r: ABC, num: number, key: string) { + r[key] = num * 3; + return r; + }, {}); + + result = _.reduceRight([[0, 1], [2, 3], [4, 5]], function (a: number[], b: number[]) { return a.concat(b); }, []); } - -result = _.reduce([1, 2, 3], function (sum: number, num: number) { - return sum + num; -}); -result = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function (r: ABC, num: number, key: string) { - r[key] = num * 3; - return r; -}, {}); - -result = _([1, 2, 3]).reduce(function (sum: number, num: number) { - return sum + num; -}); -result = _({ 'a': 1, 'b': 2, 'c': 3 }).reduce(function (r: ABC, num: number, key: string) { - r[key] = num * 3; - return r; -}, {}); - -result = _.reduceRight([[0, 1], [2, 3], [4, 5]], function (a: number[], b: number[]) { return a.concat(b); }, []); - // _.reject namespace TestReject { let array: TResult[]; @@ -5733,11 +5757,11 @@ namespace TestFlow { let Fn2: (m: number, n: number) => number; let Fn3: (a: number) => string; let Fn4: (a: string) => number; - + { // type infer test let result: (m: number, n: number) => number; - + result = _.flow(Fn2, Fn1); result = _.flow(Fn2, Fn1, Fn1); result = _.flow(Fn2, Fn1, Fn1, Fn1); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 52f274fd3c..eb24793955 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -172,6 +172,7 @@ Other changes - [x] Ensured _.range preserves the sign of start of -0 - [x] Ensured _.reduce & _.reduceRight use getIteratee in their array branch - [x] Fixed rounding issue with the precision param of _.floor +- [x] Added flush method to debounced & throttled functions ** LATER ** Misc: @@ -185,7 +186,6 @@ Misc: - [ ] _.extend as an alias of _.assignIn - [ ] _.extendWith as an alias of _.assignInWith - [ ] Added clear method to _.memoize.Cache -- [ ] Added flush method to debounced & throttled functions - [ ] Added support for ES6 maps, sets, & symbols to _.clone, _.isEqual, & _.toArray - [ ] Enabled _.flow & _.flowRight to accept an array of functions - [ ] Ensured “Collection” methods treat functions as objects @@ -6787,12 +6787,13 @@ declare module _ { * * @param collection The collection to search. * @param predicate The function invoked per iteration. - * @param thisArg The this binding of predicate. + * @param fromIndex The index to search from. * @return Returns the matched element, else undefined. */ find( collection: List, - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): T; /** @@ -6800,7 +6801,8 @@ declare module _ { */ find( collection: Dictionary, - predicate?: DictionaryIterator + predicate?: DictionaryIterator, + fromIndex?: number ): T; /** @@ -6808,7 +6810,8 @@ declare module _ { */ find( collection: List|Dictionary, - predicate?: string + predicate?: string, + fromIndex?: number ): T; /** @@ -6816,7 +6819,8 @@ declare module _ { */ find( collection: List|Dictionary, - predicate?: TObject + predicate?: TObject, + fromIndex?: number ): T; } @@ -6825,21 +6829,24 @@ declare module _ { * @see _.find */ find( - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): T; /** * @see _.find */ find( - predicate?: string + predicate?: string, + fromIndex?: number ): T; /** * @see _.find */ find( - predicate?: TObject + predicate?: TObject, + fromIndex?: number ): T; } @@ -6848,21 +6855,24 @@ declare module _ { * @see _.find */ find( - predicate?: ListIterator|DictionaryIterator + predicate?: ListIterator|DictionaryIterator, + fromIndex?: number ): TResult; /** * @see _.find */ find( - predicate?: string + predicate?: string, + fromIndex?: number ): TResult; /** * @see _.find */ find( - predicate?: TObject + predicate?: TObject, + fromIndex?: number ): TResult; } @@ -8574,6 +8584,21 @@ declare module _ { callback: MemoIterator): LoDashExplicitObjectWrapper; } + interface LoDashExplicitArrayWrapper { + /**LoDashExplicitWrapper + * @see _.reduce + */ + reduce( + callback: MemoIterator, + accumulator: TResult): LoDashExplicitWrapper; + + /** + * @see _.reduce + */ + reduce( + callback: MemoIterator): LoDashExplicitWrapper; + } + //_.reduceRight interface LoDashStatic { /** @@ -10132,9 +10157,9 @@ declare module _ { /** * Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since * the last time the debounced function was invoked. The debounced function comes with a cancel method to - * cancel delayed invocations. Provide an options object to indicate that func should be invoked on the - * leading and/or trailing edge of the wait timeout. Subsequent calls to the debounced function return the - * result of the last func invocation. + * cancel delayed invocations and a flush method to immediately invoke them. Provide an options object to + * indicate that func should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent + * calls to the debounced function return the result of the last func invocation. * * Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only * if the the debounced function is invoked more than once during the wait timeout. @@ -10755,9 +10780,9 @@ declare module _ { interface LoDashStatic { /** * Creates a throttled function that only invokes func at most once per every wait milliseconds. The throttled - * function comes with a cancel method to cancel delayed invocations. Provide an options object to indicate - * that func should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent calls to - * the throttled function return the result of the last func call. + * function comes with a cancel method to cancel delayed invocations and a flush method to immediately invoke + * them. Provide an options object to indicate that func should be invoked on the leading and/or trailing edge + * of the wait timeout. Subsequent calls to the throttled function return the result of the last func call. * * Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only if * the the throttled function is invoked more than once during the wait timeout. @@ -19159,6 +19184,7 @@ declare module _ { interface Cancelable { cancel(): void; + flush(): void; } } diff --git a/lru-cache/lru-cache.d.ts b/lru-cache/lru-cache.d.ts index 25b9b8cf52..0f92df2f68 100644 --- a/lru-cache/lru-cache.d.ts +++ b/lru-cache/lru-cache.d.ts @@ -1,4 +1,4 @@ -// Type definitions for lru-cache v2.5.0 +// Type definitions for lru-cache v4.0.1 // Project: https://github.com/isaacs/node-lru-cache // Definitions by: Bart van der Schoor // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -12,20 +12,22 @@ declare module 'lru-cache' { max?: number; maxAge?: number; length?: (value: T) => number; - dispose?: (key: string, value: T) => void; + dispose?: (key: any, value: T) => void; stale?: boolean; } interface Cache { - set(key: string, value: T): void; - get(key: string): T; - peek(key: string): T; - has(key: string): boolean - del(key: string): void; + set(key: any, value: T, maxAge?: number): void; + get(key: any): T; + peek(key: any): T; + has(key: any): boolean + del(key: any): void; reset(): void; - forEach(iter: (value: T, key: string, cache: Cache) => void, thisp?: any): void; - - keys(): string[]; + prune(): void; + forEach(iter: (value: T, key: any, cache: Cache) => void, thisp?: any): void; + itemCount: number; + length: number + keys(): any[]; values(): T[]; } } diff --git a/mailparser/mailparser.d.ts b/mailparser/mailparser.d.ts index bc50dcc509..d265d30b16 100644 --- a/mailparser/mailparser.d.ts +++ b/mailparser/mailparser.d.ts @@ -60,7 +60,7 @@ declare module 'mailparser' { - class MailParser implements WritableStream { + class MailParser extends StreamModule.Writable { constructor(options?: Options); on(event: string, callback: (any: any) => void): this; diff --git a/maquette/maquette.d.ts b/maquette/maquette.d.ts index 7ad5081ed0..b1ee5bc9c7 100644 --- a/maquette/maquette.d.ts +++ b/maquette/maquette.d.ts @@ -325,6 +325,14 @@ declare namespace maquette { * @param {function} renderMaquetteFunction - Function with zero arguments that returns a {@link VNode} tree. */ append(parentNode: Element, renderMaquetteFunction: () => VNode): void; + /** + * Stops running the `renderMaquetteFunction` to update the DOM. The `renderMaquetteFunction` must have been + * registered using [[append]], [[merge]], [[insertBefore]] or [[replace]]. + * + * @returns The [[Projection]] which was created using this `renderMaquetteFunction`. + * The [[Projection]] contains a reference to the DOM Node that was rendered. + */ + detach(renderMaquetteFunction: () => VNode): Projection; /** * Scans the document for `