diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 7ebdcc514f..44f0d8e9a0 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -401,6 +401,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](egg.js/egg.js.d.ts) [Egg.js](https://github.com/mikeflynn/egg.js) by [Markus Peloso](https://github.com/ToastHawaii) * [:link:](ejs-locals/ejs-locals.d.ts) [ejs-locals](https://github.com/randometc/ejs-locals) by [jt000](https://github.com/jt000) * [:link:](ejs/ejs.d.ts) [ejs.js](http://ejs.co) by [Ben Liddicott](https://github.com/benliddicott/DefinitelyTyped) +* [:link:](elasticsearch/elasticsearch.d.ts) [elasticsearch](https://www.elastic.co) by [Casper Skydt](https://github.com/CasperSkydt/DefinitelyTyped), [Blake Smith](https://github.com/bfsmith/DefinitelyTyped) * [:link:](jquery.elang/jquery.elang.d.ts) [eLang](https://github.com/sumegizoltan/ELang) by [Zoltan Sumegi](https://github.com/sumegizoltan) * [:link:](github-electron/github-electron.d.ts) [Electron](http://electron.atom.io) by [jedmao](https://github.com/jedmao), [rhysd](https://rhysd.github.io), [Milan Burda](https://github.com/miniak) * [:link:](electron-builder/electron-builder.d.ts) [electron-builder](https://github.com/loopline-systems/electron-builder) by [Maxime LUCE](https://github.com/SomaticIT) diff --git a/angular-feature-flags/angular-feature-flags-tests.ts b/angular-feature-flags/angular-feature-flags-tests.ts new file mode 100644 index 0000000000..a36eaba3d0 --- /dev/null +++ b/angular-feature-flags/angular-feature-flags-tests.ts @@ -0,0 +1,31 @@ +/// + +let myApp = angular.module('myApp', ['feature-flags']); + +const flagsData: Array = [ + { + key: '1', + active: true, + name: 'flag1', + description: 'This is the first flag' + }, + { + key: '2', + active: false, + name: 'flag2', + description: 'This is the second flag' + } +]; + +myApp.config(function (featureFlagsProvider: angular.featureflags.FeatureFlagsProvider) { + featureFlagsProvider.setInitialFlags(flagsData); +}); + +myApp.run(function ($q: angular.IQService, $http: angular.IHttpService, featureFlags: angular.featureflags.FeatureFlagsService) { + let deferred = $q.defer(); + deferred.resolve(flagsData); + + featureFlags.set(deferred.promise); + + featureFlags.set($http.get('/data/flags.json')); +}); \ No newline at end of file diff --git a/angular-feature-flags/angular-feature-flags.d.ts b/angular-feature-flags/angular-feature-flags.d.ts new file mode 100644 index 0000000000..99ef300976 --- /dev/null +++ b/angular-feature-flags/angular-feature-flags.d.ts @@ -0,0 +1,38 @@ +// Type definitions for angular-feature-flags 1.4.0 +// Project: https://github.com/mjt01/angular-feature-flags +// Definitions by: Borislav Zhivkov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.featureflags { + export interface FlagData { + /** + * Unique key that is used from the markup to resolve whether a flag is active or not. + */ + key: string; + + /** + * Boolean value for enabling/disabling the feature + */ + active: boolean; + + /** + * A short name of the flag (only visible in the list of flags) + */ + name: string; + + /** + * A long description of the flag to further explain the feature being toggled (only visible in the list of flags) + */ + description: string; + } + + export interface FeatureFlagsProvider { + setInitialFlags(flags: Array): void; + } + + export interface FeatureFlagsService { + set(flagsPromise: angular.IPromise | angular.IHttpPromise): void; + } +} \ No newline at end of file diff --git a/angular-material/angular-material-tests.ts b/angular-material/angular-material-tests.ts index c3ebcbaf99..552ba7a95e 100644 --- a/angular-material/angular-material-tests.ts +++ b/angular-material/angular-material-tests.ts @@ -132,7 +132,10 @@ myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.materia }); myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IToastService) => { - $scope['openToast'] = () => $mdToast.show($mdToast.simple().textContent('Hello!')); + $scope['openToast'] = () => { + $mdToast.show($mdToast.simple().textContent('Hello!')); + $mdToast.updateTextContent('New Content'); + } $scope['customToast'] = () => { var options = { diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts index 66852586da..3fa0290904 100644 --- a/angular-material/angular-material.d.ts +++ b/angular-material/angular-material.d.ts @@ -177,7 +177,8 @@ declare namespace angular.material { showSimple(content: string): angular.IPromise; simple(): ISimpleToastPreset; build(): IToastPreset; - updateContent(): void; + updateContent(newContent: string): void; + updateTextContent(newContent: string): void hide(response?: any): void; cancel(response?: any): void; } diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts index dd129d141d..d6c389146b 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts @@ -400,6 +400,17 @@ declare namespace angular.ui.bootstrap { * @default 'body' */ appendTo?: angular.IAugmentedJQuery; + + /** + * A string reference to the component to be rendered that is registered with Angular's compiler. If using a directive, the directive must have `restrict: 'E'` and a template or templateUrl set. + * + * It supports these bindings: + * - `close` - A method that can be used to close a modal, passing a result. The result must be passed in this format: `{$value: myResult}` + * - `dismiss` - A method that can be used to dismiss a modal, passing a result. The result must be passed in this format: `{$value: myRejectedResult}` + * - `modalInstance` - The modal instance. This is the same `$uibModalInstance` injectable found when using `controller`. + * - `resolve` - An object of the modal resolve values. See [UI Router resolves] for details. + */ + component?: string; } interface IModalStackService { diff --git a/angular-ui-scroll/angular-ui-scroll.d.ts b/angular-ui-scroll/angular-ui-scroll.d.ts index 168c6ba271..5f24c8ec38 100644 --- a/angular-ui-scroll/angular-ui-scroll.d.ts +++ b/angular-ui-scroll/angular-ui-scroll.d.ts @@ -42,9 +42,10 @@ declare namespace angular.ui { */ topVisibleScope: ng.IRepeatScope; /** - * calling this method reinitializes and reloads the scroller content. + * calling this method reinitializes and reloads the scroller content. + * @param startIndex is an integer indicating what item index the scroller will use to start the load process. */ - reload(): void; + reload(startIndex?: number): void; /** * Replaces the item in the buffer at the given index with the new items. * diff --git a/angularjs/angular-resource.d.ts b/angularjs/angular-resource.d.ts index 441a7e1d3d..f7e803c1c8 100644 --- a/angularjs/angular-resource.d.ts +++ b/angularjs/angular-resource.d.ts @@ -42,15 +42,20 @@ declare namespace angular.resource { (url: string, paramDefaults?: any, /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } where deleteDescriptor : IActionDescriptor */ - actions?: any, options?: IResourceOptions): IResourceClass>; + actions?: IActionHash, options?: IResourceOptions): IResourceClass>; (url: string, paramDefaults?: any, /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } where deleteDescriptor : IActionDescriptor */ - actions?: any, options?: IResourceOptions): U; + actions?: IActionHash, options?: IResourceOptions): U; (url: string, paramDefaults?: any, /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } where deleteDescriptor : IActionDescriptor */ - actions?: any, options?: IResourceOptions): IResourceClass; + actions?: IActionHash, options?: IResourceOptions): IResourceClass; + } + + // Hash of action descriptors allows custom action names + interface IActionHash { + [action: string]: IActionDescriptor } // Just a reference to facilitate describing new actions @@ -186,6 +191,12 @@ declare namespace angular { /** creating a resource service factory */ factory(name: string, resourceServiceFactoryFunction: angular.resource.IResourceServiceFactoryFunction): IModule; } + + namespace auto { + interface IInjectorService { + get(name: '$resource'): ng.resource.IResourceService; + } + } } interface Array diff --git a/atom/atom.d.ts b/atom/atom.d.ts index 389d6ef16e..ac899ba5ac 100644 --- a/atom/atom.d.ts +++ b/atom/atom.d.ts @@ -946,9 +946,14 @@ declare namespace AtomCore { registry: any; repository: Object; scopeName: string; + tokenizeLines: (text: string) => any; // TBD } + + interface IGrammars { + grammarForScopeName(scope: string): IGrammar; + } interface IPane /* extends Theorist.Model */ { itemForURI: (uri:string)=>IEditor; @@ -1302,6 +1307,7 @@ declare namespace AtomCore { deserializers:IDeserializerManager; config: IConfig; commands: ICommandRegistry; + grammars: IGrammars; keymaps: IKeymapManager; keymap: IKeymapManager; packages: IPackageManager; diff --git a/auth0.lock/auth0.lock.d.ts b/auth0.lock/auth0.lock.d.ts index 43d842aecc..2d74f6e6a5 100644 --- a/auth0.lock/auth0.lock.d.ts +++ b/auth0.lock/auth0.lock.d.ts @@ -92,7 +92,7 @@ interface Auth0LockConstructorOptions { initialScreen?: "login" | "signUp" | "forgotPassword"; language?: string; languageDictionary?: any; - loginAfterSignup?: boolean; + loginAfterSignUp?: boolean; mustAcceptTerms?: boolean; popupOptions?: Auth0LockPopupOptions; prefill?: { email?: string, username?: string}; diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index b950790058..09ec2f6267 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -236,6 +236,11 @@ declare module "aws-sdk" { listObjects(params: s3.ListObjectRequest, callback: (err: Error, data: s3.ListObjectResponse) => void): void; listObjectsV2(params: s3.ListObjectV2Request, callback: (err: Error, data: s3.ListObjectV2Response) => void): void; waitFor(state: string, params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void; + + createMultipartUpload(params: any, callback: (err: Error, data: any) => void): void; + uploadPart(params: any, callback: (err: Error, data: any) => void): void; + listParts(params: any, callback: (err: Error, data: any) => void): void; + completeMultipartUpload(params: any, callback: (err: Error, data: any) => void): void; } export class STS { diff --git a/axe-core/axe-core-tests.ts b/axe-core/axe-core-tests.ts new file mode 100644 index 0000000000..7decb865c2 --- /dev/null +++ b/axe-core/axe-core-tests.ts @@ -0,0 +1,91 @@ +/// + +var context:any = document +var $fixture:any = {} + +// axe.a11yCheck config +axe.a11yCheck(context, {}, (results) => { + // axe's results object + console.log(results.passes.length) + console.log(results.violations.length) +}); +// axe.a11yCheck include/exclude +axe.a11yCheck({include: [['#id1'], ['#id2']]}, {}, (results) => { + console.log(results) +}) +axe.a11yCheck({exclude: [$fixture[0]]}, {}, (results) => { + console.log(results) +}) +var tagConfigRunOnly: axe.RunOnly = { + type: 'tag', + values: ['wcag2a'] +} +var tagConfig = { + runOnly: tagConfigRunOnly +} +axe.a11yCheck(context, tagConfig, (results) => { + console.log(results) +}) +var includeExcludeTagsRunOnly: axe.RunOnly = { + type: 'tags', + value: { + include: ['wcag2a', 'wcag2aa'], + exclude: ['experimental'] + } +} +var includeExcludeTagsConfig = { + runOnly: includeExcludeTagsRunOnly +} +axe.a11yCheck(context, includeExcludeTagsConfig, (results) => { + console.log(results) +}) +var someRulesConfig = { + rules: { + "color-contrast": {enabled: 'false'}, + "heading-order": {enabled: 'true'} + } +} +axe.a11yCheck(context, someRulesConfig, (results) => { + console.log(results) +}) + +// axe.configure +var spec: axe.Spec = { + branding: { + brand: 'foo', + application: 'bar' + }, + reporter: 'v1', + checks: [{ + id: 'custom-check', + evaluate: function() { + return true + } + }], + rules: [{ + id: 'custom-rule', + any: ['custom-check'] + }] +} +axe.configure(spec) + +axe.reset() + +axe.getRules(['wcag2aa']) +typeof axe.getRules() === 'object' + +// Plugins +var pluginSrc: axe.AxePlugin = { + id: 'doStuff', + run: (data:any, callback:Function) => { + callback() + }, + commands: [{ + id: 'run-doStuff', + callback: (data:any, callback:Function) => { + axe.plugins['doStuff'].run(data, callback) + } + }] +} +axe.registerPlugin(pluginSrc) +axe.cleanup() diff --git a/axe-core/axe-core.d.ts b/axe-core/axe-core.d.ts new file mode 100644 index 0000000000..98818e75cc --- /dev/null +++ b/axe-core/axe-core.d.ts @@ -0,0 +1,159 @@ +// Type definitions for axe-core 2.0.5 +// Project: https://github.com/dequelabs/axe-core +// Definitions by: Marcy Sutton +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace axe { + + export type ImpactValue = "minor" | "moderate" | "serious" | "critical"; + + export type TagValue = "wcag2a" | "wcag2aa" | "section508" | "best-practice"; + + export type ReporterVersion = "v1" | "v2"; + + export type RunOnlyType = "rule" | "rules" | "tag" | "tags"; + + export interface ElementContext { + node?: Object, + selector?: string, + include?: any[], + exclude?: any[] + } + export interface RunOnly { + type: RunOnlyType, + value?: { + include?: string[], + exclude?: string[] + } + values?: TagValue[] + } + export interface AxeResults { + url: string, + timestamp: string, + passes: Pass[], + violations: Violation[] + } + export interface Pass { + description: string, + help: string, + helpUrl: string, + id: string, + impact: ImpactValue, + tags: TagValue[], + nodes: NodeResult[] + } + export interface Violation { + description: string, + help: string, + helpUrl: string, + id: string, + impact: ImpactValue, + tags: TagValue[], + nodes: NodeResult[] + } + export interface NodeResult { + html: string, + impact: ImpactValue, + target: string[], + any: CheckResult[], + all: CheckResult[], + none: CheckResult[] + } + export interface CheckResult { + id: string, + impact: string, + message: string, + data: any, + relatedNodes?: RelatedNode[] + } + export interface RelatedNode { + target: string[], + html: string + } + export interface Spec { + branding?: { + brand: string, + application: string + }, + reporter?: ReporterVersion, + checks?: Check[], + rules?: Rule[] + } + export interface Check { + id: string, + evaluate: Function, + after?: Function, + options?: any, + matches?: string, + enabled?: boolean + } + export interface Rule { + id: string, + selector?: string, + excludeHidden?: boolean, + enabled?: boolean, + pageLevel?: boolean, + any?: string[], + all?: string[], + none?: string[], + tags?: string[], + matches?: string + } + export interface AxePlugin { + id: string, + run(...args:any[]): any, + commands: { + id: string, + callback(...args:any[]): void + }[], + cleanup?(callback:Function): void + } + + export let plugins: any + + /** + * Starts analysis on the current document and its subframes + * + * @param {Object} context The `Context` specification object @see Context + * @param {Array} options Options passed into rules or checks, temporarily modifyint them. + * @param {Function} callback The function to invoke when analysis is complete. + * @returns {Object} results The aXe results object + */ + export function a11yCheck(context: ElementContext, options: {runOnly?: RunOnly, rules?: Object}, callback: (results:AxeResults) => void): AxeResults + + /** + * Method for configuring the data format used by aXe. Helpful for adding new + * rules, which must be registered with the library to execute. + * @param {Spec} Spec Object with valid `branding`, `reporter`, `checks` and `rules` data + */ + export function configure(spec: Spec): void + + /** + * Searches and returns rules that contain a tag in the list of tags. + * @param {Array} tags Optional array of tags + * @return {Array} Array of rules + */ + export function getRules(tags?: string[]): Object[] + + /** + * Restores the default axe configuration + */ + export function reset(): void + + /** + * Function to register a plugin configuration in document and its subframes + * @param {Object} plugin A plugin configuration object + */ + export function registerPlugin(plugin: AxePlugin): void + + /** + * Function to clean up plugin configuration in document and its subframes + */ + export function cleanup(): void + +} + +// axe is also available as a module +declare module "axe-core" { + export = axe; +} diff --git a/azure-mobile-apps/azure-mobile-apps-tests.ts b/azure-mobile-apps/azure-mobile-apps-tests.ts index 6b994b4f05..302f732889 100644 --- a/azure-mobile-apps/azure-mobile-apps-tests.ts +++ b/azure-mobile-apps/azure-mobile-apps-tests.ts @@ -72,6 +72,13 @@ table.read.use([function () {}, function () {}]); table.read.use(function () {}, function () {}); table.use(function () {}).use(function () {}).read(function () {}).use(function () {}) +table.access = undefined; +table.access = 'authenticated'; +table.read.access = 'anonymous'; +table.update.access = 'disabled'; +table.delete.access = 'authenticated'; +table.insert.access = 'authenticated'; + // Express.Table, instantiated from the static require('azure-mobile-apps').table() // This is going to be interesting if we ever support more than one provider var table2 = mobileApps.table(); diff --git a/azure-mobile-apps/azure-mobile-apps.d.ts b/azure-mobile-apps/azure-mobile-apps.d.ts index 436d88b3cb..a17e41e2d6 100644 --- a/azure-mobile-apps/azure-mobile-apps.d.ts +++ b/azure-mobile-apps/azure-mobile-apps.d.ts @@ -47,6 +47,7 @@ declare namespace Azure.MobileApps { interface Table { authorize?: boolean; + access?: AccessType; autoIncrement?: boolean; dynamicSchema?: boolean; name: string; @@ -66,8 +67,11 @@ declare namespace Azure.MobileApps { (operationHandler: (context: Context) => void): Table; use(...middleware: Middleware[]): Table; use(middleware: Middleware[]): Table; + access: AccessType; } + type AccessType = 'anonymous' | 'authenticated' | 'disabled'; + interface Tables { configuration: Configuration; add(name: string, definition?: Table | TableDefinition): void; diff --git a/bunnymq/bunnymq-tests.ts b/bunnymq/bunnymq-tests.ts new file mode 100644 index 0000000000..208eb7e992 --- /dev/null +++ b/bunnymq/bunnymq-tests.ts @@ -0,0 +1,36 @@ +/// + +import * as bunnymq from "bunnymq"; + +// Basic usage +var instance = bunnymq({ host: 'amqp://localhost' }); + +// Publisher +instance.producer.produce('queue:name', 'Hello World!'); +// Subscriber +instance.consumer.consume('queue:name', message => { }); + +// RPC Support +instance.producer.produce('queue:name', { message: 'content' }, { rpc: true }) + .then(function (consumerResponse) { + console.log(consumerResponse); + }); + +// Routing keys +instance.producer.produce('queue:name', { message: 'content' }, { routingKey: 'my-routing-key' }); + +// Config +var custom = bunnymq({ + host: 'amqp://localhost', + //number of fetched messages at once on the channel + prefetch: 5, + //requeue put back message into the broker if consumer crashes/trigger exception + requeue: true, + //time between two reconnect (ms) + timeout: 1000, + consumerSuffix: '', + //generate a hostname so we can track this connection on the broker (rabbitmq management plugin) + hostname: "", + //the transport to use to debug. if provided, bunnymq will show some logs + transport: new Object() +}); \ No newline at end of file diff --git a/bunnymq/bunnymq.d.ts b/bunnymq/bunnymq.d.ts new file mode 100644 index 0000000000..1167db21ed --- /dev/null +++ b/bunnymq/bunnymq.d.ts @@ -0,0 +1,120 @@ +// Type definitions for node-bunnymq 2.2.1 +// Project: https://github.com/dial-once/node-bunnymq +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "bunnymq" { + namespace bunnymq { + export type ConsumerCallback = (message: Object) => void; + + /** + * Consumer. + * @interface + */ + export interface Consumer { + /** + * Handle messages from a named queue. + * @param {string} queue A named queue. + * @param {ConsumerCallback} callback A callback. + */ + consume(queue: string, callback: ConsumerCallback): void; + } + + /** + * bunnymq instance. + * @interface + */ + export interface Instance { + /** + * Consumer. + * @type {Consumer} + */ + consumer: Consumer; + + /** + * Producer. + * @type {Producer} + */ + producer: Producer; + } + + /** + * Options. + * @interface + */ + export interface Options { + /** + * Consumer suffix. + * @type {string} + */ + consumerSuffix?: string; + + /** + * Host. + * @type {string} + */ + host?: string; + + /** + * Hostname. + * @type {string} + */ + hostname?: string; + + /** + * Number of fetched messages at once on the channel. + * @type {number} + */ + prefetch?: number; + + /** + * Requeue put back message into the broker if consumer crashes/trigger exception. + * @type {boolean} + */ + requeue?: boolean; + + /** + * Time between two reconnect (in milliseconds). + * @type {number} + */ + timeout?: number; + + /** + * Transport. + * @type {any} + */ + transport?: any; + } + + /** + * Producer. + * @inteface + */ + export interface Producer { + /** + * Send messages to a named queue. + * @param {string} queue A named queue. + * @param {Object} message A message. + * @return {Object} The consumer response. + */ + produce(queue: string, message: Object, options?: ProducerOptions): PromiseLike; + } + + /** + * Options for producer. + * @interface + */ + export interface ProducerOptions { + routingKey?: string; + rpc?: boolean; + } + } + + /** + * Constructor. + * @param {Options} [options] Options. + * @return {Instance} A instance of bunnymq. + */ + function bunnymq(options?: bunnymq.Options): bunnymq.Instance; + export = bunnymq; +} diff --git a/busboy/busboy-tests.ts b/busboy/busboy-tests.ts new file mode 100644 index 0000000000..058b5c92d3 --- /dev/null +++ b/busboy/busboy-tests.ts @@ -0,0 +1,39 @@ +/// +/// + +import * as Busboy from 'busboy'; +import * as http from 'http'; +import * as util from 'util'; + +function serverFn(req: http.ServerRequest, res: http.ServerResponse) { + if (req.method === 'POST') { + var busboy = new Busboy({ headers: req.headers }); + busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { + console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype); + file.on('data', function(data: Buffer) { + console.log('File [' + fieldname + '] got ' + data.length + ' bytes'); + }); + file.on('end', function() { + console.log('File [' + fieldname + '] Finished'); + }); + }); + busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) { + console.log('Field [' + fieldname + ']: value: ' + util.inspect(val)); + }); + busboy.on('finish', function() { + console.log('Done parsing form!'); + res.writeHead(303, { Connection: 'close', Location: '/' }); + res.end(); + }); + req.pipe(busboy); + } else if (req.method === 'GET') { + res.writeHead(200, { Connection: 'close' }); + res.end('\ +
\ +
\ +
\ + \ +
\ + '); + } +} diff --git a/busboy/busboy.d.ts b/busboy/busboy.d.ts new file mode 100644 index 0000000000..3b64f3d112 --- /dev/null +++ b/busboy/busboy.d.ts @@ -0,0 +1,60 @@ +// Type definitions for busboy v0.2.13 +// Project: https://www.npmjs.com/package/busboy +// Definitions by: Jacob Baskin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + +declare namespace busboy { + interface Options { + headers: any; + } + + interface BusboyConfig { + headers?: any; + highWaterMark?: number; + fileHwm?: number; + defCharset?: string; + preservePath?: boolean; + limits?: { + fieldNameSize?: number; + fieldSize?: number; + fields?: number; + fileSize?: number; + files?: number; + parts?: number; + headerPairs?: number; + }; + } + + interface Busboy extends NodeJS.WritableStream { + on(event: 'field', + listener: ( + fieldname: string, + val: any, + fieldnameTruncated: boolean, + valTruncated: boolean, + encoding: string, + mimetype: string) => void): this; + on(event: 'file', + listener: ( + fieldname: string, + file: NodeJS.ReadableStream, + filename: string, + encoding: string, + mimetype: string) => void): this; + on(event: 'finish', callback: () => void): this; + on(event: 'partsLimit', callback: () => void): this; + on(event: 'filesLimit', callback: () => void): this; + on(event: 'fieldsLimit', callback: () => void): this; + on(event: string, listener: Function): this; + } + + interface BusboyConstructor { + new (options: BusboyConfig): Busboy; + } +} + +declare module 'busboy' { + const temp: busboy.BusboyConstructor; + export = temp; +} diff --git a/c3/c3.d.ts b/c3/c3.d.ts index 2838ba2675..e815b44391 100644 --- a/c3/c3.d.ts +++ b/c3/c3.d.ts @@ -681,7 +681,7 @@ declare namespace c3 { * Specified function receives name, ratio, id and index of the data point to show. ratio will be undefined if the chart is not donut/pie/gauge. * If undefined returned, the row of that value will be skipped. */ - value?: (name: string, ratio: number, id: string, index: number) => string; + value?: (value: any, ratio: number, id: string, index: number) => string; }; /** * Set custom position for the tooltip. This option can be used to modify the tooltip position by returning object that has top and left. diff --git a/canvas-gauges/canvas-gauges-tests.ts b/canvas-gauges/canvas-gauges-tests.ts new file mode 100644 index 0000000000..d0f04e1082 --- /dev/null +++ b/canvas-gauges/canvas-gauges-tests.ts @@ -0,0 +1,20 @@ +/// + +import { + LinearGaugeOptions, + RadialGaugeOptions, + LinearGauge, + RadialGauge +} from 'canvas-gauges'; + +let linearOptions: LinearGaugeOptions = { + renderTo: document.createElement('canvas') +}; +let radialOptions: RadialGaugeOptions = { + renderTo: 'gauge-id' +}; + +new LinearGauge(linearOptions); +new RadialGauge(radialOptions); + +console.log(document.gauges.length); diff --git a/canvas-gauges/canvas-gauges.d.ts b/canvas-gauges/canvas-gauges.d.ts new file mode 100644 index 0000000000..53858e566e --- /dev/null +++ b/canvas-gauges/canvas-gauges.d.ts @@ -0,0 +1,263 @@ +// Type definitions for canvas-gauges +// Project: https://github.com/Mikhus/canvas-gauges +// Definitions by: Mikhus +// Definitions: https://github.com/Mikhus/DefinitelyTyped + +declare namespace CanvasGauges { + export type RenderTarget = string|HTMLElement; + + export interface AnimationRule { + (percent: number): number; + } + + export interface Highlight { + from: number, + to: number, + color: string + } + + export type MajorTicks = string[]|number[]; + + export interface GenericOptions { + renderTo: RenderTarget, + width?: number, + height?: number, + minValue?: number, + maxValue?: number, + value?: number, + units?: string|boolean, + majorTicks?: MajorTicks, + minorTicks?: number, + strokeTicks?: boolean, + animatedValue?: boolean, + title?: string|boolean, + borders?: boolean, + valueInt?: number, + valueDec?: number, + majorTicksInt?: number, + majorTicksDec?: number, + animation?: boolean, + animationDuration?: number, + animationRule?: string|AnimationRule, + colorPlate?: string, + colorMajorTicks?: string, + colorMinorTicks?: string, + colorTitle?: string, + colorUnits?: string, + colorNumbers?: string, + colorNeedle?: string, + colorNeedleEnd?: string, + colorValueText?: string, + colorValueTextShadow?: string, + colorBorderShadow?: string, + colorBorderOuter?: string, + colorBorderOuterEnd?: string, + colorBorderMiddle?: string, + colorBorderMiddleEnd?: string, + colorBorderInner?: string, + colorBorderInnerEnd?: string, + colorValueBoxRect?: string, + colorValueBoxRectEnd?: string, + colorValueBoxBackground?: string, + colorValueBoxShadow?: string, + colorNeedleShadowUp?: string, + colorNeedleShadowDown?: string, + needle?: boolean, + needleShadow?: boolean, + needleType?: string, + needleStart?: number, + needleEnd?: number, + needleWidth?: number, + borderOuterWidth?: number, + borderMiddleWidth?: number, + borderInnerWidth?: number, + borderShadowWidth?: number, + valueBox?: boolean, + valueBoxStroke?: number, + valueText?: string, + valueTextShadow?: boolean, + valueBoxBorderRadius?: number, + highlights?: Highlight[], + fontNumbers?: string, + fontTitle?: string, + fontUnits?: string, + fontValue?: string, + fontTitleSize?: number, + fontValueSize?: number, + fontUnitsSize?: number, + fontNumbersSize?: number + } + + export interface RadialGaugeOptions extends GenericOptions { + ticksAngle?: number, + startAngle?: number, + colorNeedleCircleOuter?: string, + colorNeedleCircleOuterEnd?: string, + colorNeedleCircleInner?: string, + colorNeedleCircleInnerEnd?: string, + needleCircleSize?: number, + needleCircleInner?: boolean, + needleCircleOuter?: boolean, + animationTarget?: string + } + + export interface LinearGaugeOptions extends GenericOptions { + borderRadius?: number, + barBeginCircle?: number, + barWidth?: number, + barStrokeWidth?: number, + barProgress?: boolean, + colorBar?: string, + colorBarEnd?: string, + colorBarStroke?: string, + colorBarProgress?: string, + colorBarProgressEnd?: string, + tickSide?: string, + needleSide?: string, + numberSide?: string, + ticksWidth?: number, + ticksWidthMinor?: number, + ticksPadding?: number, + barLength?: number + } + + export interface DrawEventCallback { + (percent: number): any; + } + + export interface EndEventCallback { + (): any; + } + + export interface rules { + linear: AnimationRule, + quad: AnimationRule, + dequad: AnimationRule, + quint: AnimationRule, + dequint: AnimationRule, + cycle: AnimationRule, + decycle: AnimationRule, + bounce: AnimationRule, + debounce: AnimationRule, + elastic: AnimationRule, + delastic: AnimationRule + } + + export class Animation { + public duration: number; + public rule: string|AnimationRule; + public draw: DrawEventCallback; + public end: EndEventCallback; + + public static rules: rules; + + constructor(rule?: string|AnimationRule, duration?: number, + draw?: DrawEventCallback, end?: EndEventCallback); + + public animate(draw?: DrawEventCallback, end?: EndEventCallback): any; + public destroy(): any; + } + + export class SmartCanvas { + public element: HTMLCanvasElement; + public elementClone: HTMLCanvasElement; + public context: CanvasRenderingContext2D; + public contextClone: CanvasRenderingContext2D; + public drawWidth: number; + public drawHeight: number; + public drawX: number; + public drawY: number; + public minSide: number; + public width: number; + public height: number; + + constructor(element: HTMLCanvasElement, + width?: number, + height?: number); + + public init(): any; + public onRedraw(): any; + public destroy(): any; + public commit(): SmartCanvas; + public redraw(): SmartCanvas; + + public pixelRatio: number; + public static redraw(): any; + public static collection: Array; + } + + export class DomObserver { + public Type: BaseGauge; + public mutationsObserved: boolean; + public isObservable: boolean; + public options: GenericOptions; + public element: string; + public type: string; + + constructor(options: GenericOptions, + element: string, + type: string); + + public isValidNode(node: Node|HTMLElement): boolean; + public traverse(): any; + public observe(records: MutationRecord[]): any; + public process(node: Node|HTMLElement): BaseGauge; + + public static parse(value: any): any; + public static toDashed(camelCase: string): string; + public static toAttributeName(str: string): string; + static domReady(handler: Function): any; + } + + export abstract class BaseGauge { + public type: BaseGauge; + public options: GenericOptions; + public canvas: SmartCanvas; + public animation: Animation; + public value: number; + + constructor(options: GenericOptions); + + public update(options: GenericOptions): BaseGauge; + public destroy(): any; + public abstract draw(): BaseGauge; + + public static initialize(type: string, options: GenericOptions): any; + } + + export class RadialGauge extends BaseGauge { + public type: RadialGauge; + public options: RadialGaugeOptions; + + constructor(options: RadialGaugeOptions); + + public draw(): RadialGauge; + } + + export class LinearGauge extends BaseGauge { + public type: LinearGauge; + public options: LinearGaugeOptions; + + constructor(options: LinearGaugeOptions); + + public draw(): LinearGauge; + } + + export interface Collection extends Array { + get: (id: number | string) => BaseGauge; + } +} + +declare module 'canvas-gauges' { + export = CanvasGauges; +} + +interface Document { + gauges: CanvasGauges.Collection; +} + +interface Window { + BaseGauge: CanvasGauges.BaseGauge; + RadialGauge: CanvasGauges.RadialGauge; + LinearGauge: CanvasGauges.LinearGauge; +} diff --git a/chance/chance.d.ts b/chance/chance.d.ts index 290cde8048..6390b57864 100644 --- a/chance/chance.d.ts +++ b/chance/chance.d.ts @@ -114,8 +114,16 @@ declare namespace Chance { capitalize(str: string): string; mixin(desc: MixinDescriptor): any; pad(num: number, width: number, padChar?: string): string; + /** + * @deprecated Use pickone + */ pick(arr: T[]): T; + pickone(arr: T[]): T; + /** + * @deprecated Use pickset + */ pick(arr: T[], count: number): T[]; + pickset(arr: T[], count: number): T[]; set: Setter; shuffle(arr: T[]): T[]; diff --git a/change-emitter/change-emitter-tests.ts b/change-emitter/change-emitter-tests.ts new file mode 100644 index 0000000000..379c7636a5 --- /dev/null +++ b/change-emitter/change-emitter-tests.ts @@ -0,0 +1,124 @@ +/// + +import { createChangeEmitter, ChangeEmitterOf0 } from "change-emitter"; + +function usage() { + // https://github.com/acdlite/change-emitter#usage + + const emitter = createChangeEmitter() + + // Called `listen` instead of `subscribe` to avoid confusion with observable spec + const unlisten = emitter.listen((...args) => { + console.log(args) + }) + + emitter.emit(1, 2, 3) // logs `[1, 2, 3]` + unlisten() + emitter.emit(4, 5, 6) // doesn't log +} + +function largerExample() { + // https://github.com/acdlite/change-emitter#larger-example + + const createStore = (reducer: Function, initialState: any) => { + let state = initialState + const emitter = createChangeEmitter() + + function dispatch(action: any) { + state = reducer(state, action) + emitter.emit() + return action + } + + function getState() { + return state + } + + return { + dispatch, + getState, + subscribe: emitter.listen + } + } +} + +function untypedEmitter() { + const { emit, listen } = createChangeEmitter(); + + const unlisten0 = listen(() => {/* do something */}); + const unlisten1 = listen(value => {/* do something with value */}); + const unlisten2 = listen((value1, value2) => {/* do something with values */}); + const unlistenArgs = listen((...args: any[]) => {/* do something with values */}); + + emit(); + emit("hello"); + emit("hello", "world"); + emit(1, 2, 3, 4, 5); + + unlisten0(); + unlisten1(); + unlisten2(); + unlistenArgs(); +} + +function emitterOf0Args() { + const { emit, listen }: ChangeEmitterOf0 = createChangeEmitter(); + + const unlisten = listen(() => { }); + // const unlisten = listen(value => {}); // SYNTAX ERROR + + emit(); + // emit("hello"); // SYNTAX ERROR + + unlisten(); +} + +function emitterOf1Args() { + const { emit, listen } = createChangeEmitter(); + + const unlisten = listen(value => { value.length }); + + emit("hello"); + + unlisten(); +} + +function emitterOf2Args() { + const { emit, listen } = createChangeEmitter(); + + const unlisten = listen((value, success) => { value.length > 0 === success }); + + emit("hello", true); + + unlisten(); +} + +function emitterOf3Args() { + const { emit, listen } = createChangeEmitter(); + + const unlisten = listen((value, success, count) => { value.length > count === success }); + + emit("hello", true, 3); + + unlisten(); +} + +function emitterOf4Args() { + const { emit, listen } = createChangeEmitter(); + + const unlisten = listen((v1, v2, v3, v4) => { }); + + emit("hello", true, 3, new Date()); + + unlisten(); +} + +function emitterOf5Args() { + const { emit, listen } = createChangeEmitter(); + + const unlisten = listen((v1, v2, v3, v4, v5) => { }); + + emit("hello", true, 3, new Date(), "world"); + + unlisten(); +} diff --git a/change-emitter/change-emitter.d.ts b/change-emitter/change-emitter.d.ts new file mode 100644 index 0000000000..85abf116ed --- /dev/null +++ b/change-emitter/change-emitter.d.ts @@ -0,0 +1,58 @@ +// Type definitions for change-emitter v0.1.2 +// Project: https://github.com/acdlite/change-emitter +// Definitions by: Iskander Sierra +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'change-emitter' { + + type Unlisten = () => void; + type Listener = (...args: any[]) => void; + type ListenerOf0 = () => void; + type ListenerOf1 = (value: T) => void; + type ListenerOf2 = (value1: T1, value2: T2) => void; + type ListenerOf3 = (value1: T1, value2: T2, value3: T3) => void; + type ListenerOf4 = (value1: T1, value2: T2, value3: T3, value4: T4) => void; + type ListenerOf5 = (value1: T1, value2: T2, value3: T3, value4: T4, value5: T5) => void; + + interface ChangeEmitter { + listen(listener: Listener): Unlisten; + emit(...args: any[]): void; + } + + interface ChangeEmitterOf1 { + listen(listener: ListenerOf1): Unlisten; + emit(value: T): void; + } + + interface ChangeEmitterOf0 { + listen(listener: ListenerOf0): Unlisten; + emit(): void; + } + + interface ChangeEmitterOf2 { + listen(listener: ListenerOf2): Unlisten; + emit(value1: T1, value2: T2): void; + } + + interface ChangeEmitterOf3 { + listen(listener: ListenerOf3): Unlisten; + emit(value1: T1, value2: T2, value3: T3): void; + } + + interface ChangeEmitterOf4 { + listen(listener: ListenerOf4): Unlisten; + emit(value1: T1, value2: T2, value3: T3, value4: T4): void; + } + + interface ChangeEmitterOf5 { + listen(listener: ListenerOf5): Unlisten; + emit(value1: T1, value2: T2, value3: T3, value4: T4, value5: T5): void; + } + + export function createChangeEmitter(): ChangeEmitter; + export function createChangeEmitter(): ChangeEmitterOf1; + export function createChangeEmitter(): ChangeEmitterOf2; + export function createChangeEmitter(): ChangeEmitterOf3; + export function createChangeEmitter(): ChangeEmitterOf4; + export function createChangeEmitter(): ChangeEmitterOf5; +} diff --git a/chart.js/chart.js.d.ts b/chart.js/chart.js.d.ts index e05d930d4e..57389ee4ea 100644 --- a/chart.js/chart.js.d.ts +++ b/chart.js/chart.js.d.ts @@ -73,7 +73,7 @@ interface ChartOptions { onClick?: (any?: any) => any; title?: ChartTitleOptions; legend?: ChartLegendOptions; - tooltip?: ChartTooltipOptions; + tooltips?: ChartTooltipOptions; hover?: ChartHoverOptions; animation?: ChartAnimationOptions; elements?: ChartElementsOptions; diff --git a/colors/colors-tests.ts b/colors/colors-tests.ts index 1b9b12834e..ff838da995 100644 --- a/colors/colors-tests.ts +++ b/colors/colors-tests.ts @@ -8,9 +8,11 @@ colors.enabled = true; console.log(colors.black.underline('test')); console.log(colors.rainbow.black.blue.gray('test')); console.log(colors.random.reset.bgWhite.dim('test')); +console.log(colors.random.reset.bgWhite.strip('test')); console.log('test'.black.underline); console.log('test'.rainbow.black.blue.gray); console.log('test'.random.reset.bgWhite.dim); +console.log('test'.random.reset.bgWhite.dim.stripColors); colors.enabled = false; diff --git a/colors/colors.d.ts b/colors/colors.d.ts index 8ce8cca8b7..50e960c416 100644 --- a/colors/colors.d.ts +++ b/colors/colors.d.ts @@ -7,6 +7,9 @@ declare module "colors" { interface Color { (text: string): string; + strip: Color; + stripColors: Color; + black: Color; red: Color; green: Color; @@ -49,6 +52,9 @@ declare module "colors" { export var enabled: boolean; + export var strip: Color; + export var stripColors: Color; + export var black: Color; export var red: Color; export var green: Color; @@ -90,6 +96,9 @@ declare module "colors" { } interface String { + strip: string; + stripColors: string; + black: string; red: string; green: string; diff --git a/concaveman/concaveman-tests.ts b/concaveman/concaveman-tests.ts new file mode 100644 index 0000000000..ddb1e6d125 --- /dev/null +++ b/concaveman/concaveman-tests.ts @@ -0,0 +1,5 @@ +/// +import * as concaveman from 'concaveman'; + +var points = [[10, 20], [30, 12.5]]; +var polygon = concaveman(points); \ No newline at end of file diff --git a/concaveman/concaveman.d.ts b/concaveman/concaveman.d.ts new file mode 100644 index 0000000000..a5b55c8fa3 --- /dev/null +++ b/concaveman/concaveman.d.ts @@ -0,0 +1,24 @@ +// Type definitions for concaveman 1.1.0 +// Project: https://github.com/mapbox/concaveman +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "concaveman" { + /** + * A very fast 2D concave hull algorithm in JavaScript (generates a general outline of a point set). + * + * @name concaveman + * @param {Array>} points is an array of [x, y] points. + * @param {number} [concavity=2] is a relative measure of concavity. 1 results in a relatively detailed shape, Infinity results in a convex hull. You can use values lower than 1, but they can produce pretty crazy shapes. + * @param {number} [lengthThreshold=0] when a segment length is under this threshold, it stops being considered for further detalization. Higher values result in simpler shapes. + * @return {Array>} + * @example + * var points = [[10, 20], [30, 12.5], ...]; + * var polygon = concaveman(points); + * + * //=hull + */ + function concaveman(points: number[][], concavity?: number, lengthThreshold?: number): number[][]; + namespace concaveman {} + export = concaveman; +} diff --git a/core-js/core-js.d.ts b/core-js/core-js.d.ts index c633dc4ef6..1ad88ff41a 100644 --- a/core-js/core-js.d.ts +++ b/core-js/core-js.d.ts @@ -1889,7 +1889,7 @@ declare module "core-js/fn/number/max-safe-integer" { var MAX_SAFE_INTEGER: typeof core.Number.MAX_SAFE_INTEGER; export = MAX_SAFE_INTEGER; } -declare module "core-js/fn/number/min-safe-interger" { +declare module "core-js/fn/number/min-safe-integer" { var MIN_SAFE_INTEGER: typeof core.Number.MIN_SAFE_INTEGER; export = MIN_SAFE_INTEGER; } @@ -2668,7 +2668,7 @@ declare module "core-js/library/fn/number/max-safe-integer" { var MAX_SAFE_INTEGER: typeof core.Number.MAX_SAFE_INTEGER; export = MAX_SAFE_INTEGER; } -declare module "core-js/library/fn/number/min-safe-interger" { +declare module "core-js/library/fn/number/min-safe-integer" { var MIN_SAFE_INTEGER: typeof core.Number.MIN_SAFE_INTEGER; export = MIN_SAFE_INTEGER; } diff --git a/date-fns/date-fns-tests.ts b/date-fns/date-fns-tests.ts new file mode 100644 index 0000000000..4c1dfc2476 --- /dev/null +++ b/date-fns/date-fns-tests.ts @@ -0,0 +1,16 @@ +/// + +import {addDays, closestIndexTo, differenceInCalendarWeeks, max, isDate} from 'date-fns'; +import * as addHours from 'date-fns/add_hours'; + +function test() { + + addDays(new Date(), 5); + closestIndexTo(new Date(), [new Date(), new Date()]); + addHours(new Date(), 5); + differenceInCalendarWeeks(new Date(), new Date()); + differenceInCalendarWeeks(new Date(), new Date(), {weekStartsOn: 1}); + max(new Date(), new Date()); + isDate({}); + +} \ No newline at end of file diff --git a/date-fns/date-fns.d.ts b/date-fns/date-fns.d.ts new file mode 100644 index 0000000000..d0582c2571 --- /dev/null +++ b/date-fns/date-fns.d.ts @@ -0,0 +1,1195 @@ +// Type definitions for date-fns +// Project: https://date-fns.org/ +// Definitions by: Matt Lewis +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type DateOrStringOrNumber = Date | string | number; + +declare module 'date-fns' { + + function addDays(date: DateOrStringOrNumber, amount: number): Date; + namespace addDays {} + + function addHours(date: DateOrStringOrNumber, amount: number): Date; + namespace addHours {} + + function addISOYears(date: DateOrStringOrNumber, amount: number): Date; + namespace addISOYears {} + + function addMilliseconds(date: DateOrStringOrNumber, amount: number): Date; + namespace addMilliseconds {} + + function addMinutes(date: DateOrStringOrNumber, amount: number): Date; + namespace addMinutes {} + + function addMonths(date: DateOrStringOrNumber, amount: number): Date; + namespace addMonths {} + + function addQuarters(date: DateOrStringOrNumber, amount: number): Date; + namespace addQuarters {} + + function addSeconds(date: DateOrStringOrNumber, amount: number): Date; + namespace addSeconds {} + + function addWeeks(date: DateOrStringOrNumber, amount: number): Date; + namespace addWeeks {} + + function addYears(date: DateOrStringOrNumber, amount: number): Date; + namespace addYears {} + + function closestIndexTo(dateToCompare: DateOrStringOrNumber, datesArray: DateOrStringOrNumber[]): number; + namespace closestIndexTo {} + + function closestTo(dateToCompare: DateOrStringOrNumber, datesArray: DateOrStringOrNumber[]): Date; + namespace closestTo {} + + function compareAsc(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace compareAsc {} + + function compareDesc(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace compareDesc {} + + function differenceInCalendarDays(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarDays {} + + function differenceInCalendarISOWeeks(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarISOWeeks {} + + function differenceInCalendarISOYears(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarISOYears {} + + function differenceInCalendarMonths(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarMonths {} + + function differenceInCalendarQuarters(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarQuarters {} + + function differenceInCalendarWeeks(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber, options?: {weekStartsOn: number}): number; + namespace differenceInCalendarWeeks {} + + function differenceInCalendarYears(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarYears {} + + function differenceInDays(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInDays {} + + function differenceInHours(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInHours {} + + function differenceInISOYears(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInISOYears {} + + function differenceInMilliseconds(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInMilliseconds {} + + function differenceInMinutes(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInMinutes {} + + function differenceInMonths(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInMonths {} + + function differenceInQuarters(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInQuarters {} + + function differenceInSeconds(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInSeconds {} + + function differenceInWeeks(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInWeeks {} + + function differenceInYears(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInYears {} + + function distanceInWords(dateFrom: DateOrStringOrNumber, dateTo: DateOrStringOrNumber, options?: {includeSeconds: boolean}): string; + namespace distanceInWords {} + + function distanceInWordsToNow(date: DateOrStringOrNumber, options?: {includeSeconds: boolean}): string; + namespace distanceInWordsToNow {} + + function eachDay(startDate: DateOrStringOrNumber, endDate: DateOrStringOrNumber): Date[]; + namespace eachDay {} + + function endOfDay(date: DateOrStringOrNumber): Date; + namespace endOfDay {} + + function endOfHour(date: DateOrStringOrNumber): Date; + namespace endOfHour {} + + function endOfISOWeek(date: DateOrStringOrNumber): Date; + namespace endOfISOWeek {} + + function endOfISOYear(date: DateOrStringOrNumber): Date; + namespace endOfISOYear {} + + function endOfMinute(date: DateOrStringOrNumber): Date; + namespace endOfMinute {} + + function endOfMonth(date: DateOrStringOrNumber): Date; + namespace endOfMonth {} + + function endOfQuarter(date: DateOrStringOrNumber): Date; + namespace endOfQuarter {} + + function endOfSecond(date: DateOrStringOrNumber): Date; + namespace endOfSecond {} + + function endOfToday(): Date; + namespace endOfToday {} + + function endOfTomorrow(): Date; + namespace endOfTomorrow {} + + function endOfWeek(date: DateOrStringOrNumber, options?: {weekStartsOn: number}): Date; + namespace endOfWeek {} + + function endOfYear(date: DateOrStringOrNumber): Date; + namespace endOfYear {} + + function endOfYesterday(): Date; + namespace endOfYesterday {} + + function format(date: DateOrStringOrNumber, format?: string): string; + namespace format {} + + function getDate(date: DateOrStringOrNumber): number; + namespace getDate {} + + function getDay(date: DateOrStringOrNumber): number; + namespace getDay {} + + function getDayOfYear(date: DateOrStringOrNumber): number; + namespace getDayOfYear {} + + function getDaysInMonth(date: DateOrStringOrNumber): number; + namespace getDaysInMonth {} + + function getDaysInYear(date: DateOrStringOrNumber): number; + namespace getDaysInYear {} + + function getHours(date: DateOrStringOrNumber): number; + namespace getHours {} + + function getISOWeek(date: DateOrStringOrNumber): number; + namespace getISOWeek {} + + function getISOWeeksInYear(date: DateOrStringOrNumber): number; + namespace getISOWeeksInYear {} + + function getISOYear(date: DateOrStringOrNumber): number; + namespace getISOYear {} + + function getMilliseconds(date: DateOrStringOrNumber): number; + namespace getMilliseconds {} + + function getMinutes(date: DateOrStringOrNumber): number; + namespace getMinutes {} + + function getMonth(date: DateOrStringOrNumber): number; + namespace getMonth {} + + function getQuarter(date: DateOrStringOrNumber): number; + namespace getQuarter {} + + function getSeconds(date: DateOrStringOrNumber): number; + namespace getSeconds {} + + function getYear(date: DateOrStringOrNumber): number; + namespace getYear {} + + function isAfter(dateToCompare: DateOrStringOrNumber, date: DateOrStringOrNumber): boolean; + namespace isAfter {} + + function isBefore(dateToCompare: DateOrStringOrNumber, date: DateOrStringOrNumber): boolean; + namespace isBefore {} + + function isDate(argument: any): boolean; + namespace isDate {} + + function isEqual(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isEqual {} + + function isFirstDayOfMonth(date: DateOrStringOrNumber): boolean; + namespace isFirstDayOfMonth {} + + function isFriday(date: DateOrStringOrNumber): boolean; + namespace isFriday {} + + function isFuture(date: DateOrStringOrNumber): boolean; + namespace isFuture {} + + function isLastDayOfMonth(date: DateOrStringOrNumber): boolean; + namespace isLastDayOfMonth {} + + function isLeapYear(date: DateOrStringOrNumber): boolean; + namespace isLeapYear {} + + function isMonday(date: DateOrStringOrNumber): boolean; + namespace isMonday {} + + function isPast(date: DateOrStringOrNumber): boolean; + namespace isPast {} + + function isSameDay(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameDay {} + + function isSameHour(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameHour {} + + function isSameISOWeek(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameISOWeek {} + + function isSameISOYear(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameISOYear {} + + function isSameMinute(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameMinute {} + + function isSameMonth(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameMonth {} + + function isSameQuarter(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameQuarter {} + + function isSameSecond(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameSecond {} + + function isSameWeek(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber, options?: {weekStartsOn: number}): boolean; + namespace isSameWeek {} + + function isSameYear(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameYear {} + + function isSaturday(date: DateOrStringOrNumber): boolean; + namespace isSaturday {} + + function isSunday(date: DateOrStringOrNumber): boolean; + namespace isSunday {} + + function isThisHour(date: DateOrStringOrNumber): boolean; + namespace isThisHour {} + + function isThisISOWeek(date: DateOrStringOrNumber): boolean; + namespace isThisISOWeek {} + + function isThisISOYear(date: DateOrStringOrNumber): boolean; + namespace isThisISOYear {} + + function isThisMinute(date: DateOrStringOrNumber): boolean; + namespace isThisMinute {} + + function isThisMonth(date: DateOrStringOrNumber): boolean; + namespace isThisMonth {} + + function isThisQuarter(date: DateOrStringOrNumber): boolean; + namespace isThisQuarter {} + + function isThisSecond(date: DateOrStringOrNumber): boolean; + namespace isThisSecond {} + + function isThisWeek(date: DateOrStringOrNumber, options?: {weekStartsOn: number}): boolean; + namespace isThisWeek {} + + function isThisYear(date: DateOrStringOrNumber): boolean; + namespace isThisYear {} + + function isThursday(date: DateOrStringOrNumber): boolean; + namespace isThursday {} + + function isToday(date: DateOrStringOrNumber): boolean; + namespace isToday {} + + function isTomorrow(date: DateOrStringOrNumber): boolean; + namespace isTomorrow {} + + function isTuesday(date: DateOrStringOrNumber): boolean; + namespace isTuesday {} + + function isValid(date: DateOrStringOrNumber): boolean; + namespace isValid {} + + function isWednesday(date: DateOrStringOrNumber): boolean; + namespace isWednesday {} + + function isWeekend(date: DateOrStringOrNumber): boolean; + namespace isWeekend {} + + function isWithinRange(date: DateOrStringOrNumber, startDate: DateOrStringOrNumber, endDate: DateOrStringOrNumber): boolean; + namespace isWithinRange {} + + function isYesterday(date: DateOrStringOrNumber): boolean; + namespace isYesterday {} + + function lastDayOfISOWeek(date: DateOrStringOrNumber): Date; + namespace lastDayOfISOWeek {} + + function lastDayOfISOYear(date: DateOrStringOrNumber): Date; + namespace lastDayOfISOYear {} + + function lastDayOfMonth(date: DateOrStringOrNumber): Date; + namespace lastDayOfMonth {} + + function lastDayOfQuarter(date: DateOrStringOrNumber): Date; + namespace lastDayOfQuarter {} + + function lastDayOfWeek(date: DateOrStringOrNumber, options?: {weekStartsOn: number}): Date; + namespace lastDayOfWeek {} + + function lastDayOfYear(date: DateOrStringOrNumber): Date; + namespace lastDayOfYear {} + + function max(...dates: DateOrStringOrNumber[]): Date; + namespace max {} + + function min(...dates: DateOrStringOrNumber[]): Date; + namespace min {} + + function parse(dateString: string): Date; + namespace parse {} + + function setDate(date: DateOrStringOrNumber, dayOfMonth: number): Date; + namespace setDate {} + + function setDay(date: DateOrStringOrNumber, day: number, options?: {weekStartsOn: number}): Date; + namespace setDay {} + + function setDayOfYear(date: DateOrStringOrNumber, dayOfYear: number): Date; + namespace setDayOfYear {} + + function setHours(date: DateOrStringOrNumber, hours: number): Date; + namespace setHours {} + + function setISOWeek(date: DateOrStringOrNumber, isoWeek: number): Date; + namespace setISOWeek {} + + function setISOYear(date: DateOrStringOrNumber, isoYear: number): Date; + namespace setISOYear {} + + function setMilliseconds(date: DateOrStringOrNumber, milliseconds: number): Date; + namespace setMilliseconds {} + + function setMinutes(date: DateOrStringOrNumber, minutes: number): Date; + namespace setMinutes {} + + function setMonth(date: DateOrStringOrNumber, month: number): Date; + namespace setMonth {} + + function setQuarter(date: DateOrStringOrNumber, quarter: number): Date; + namespace setQuarter {} + + function setSeconds(date: DateOrStringOrNumber, seconds: number): Date; + namespace setSeconds {} + + function setYear(date: DateOrStringOrNumber, year: number): Date; + namespace setYear {} + + function startOfDay(date: DateOrStringOrNumber): Date; + namespace startOfDay {} + + function startOfHour(date: DateOrStringOrNumber): Date; + namespace startOfHour {} + + function startOfISOWeek(date: DateOrStringOrNumber): Date; + namespace startOfISOWeek {} + + function startOfISOYear(date: DateOrStringOrNumber): Date; + namespace startOfISOYear {} + + function startOfMinute(date: DateOrStringOrNumber): Date; + namespace startOfMinute {} + + function startOfMonth(date: DateOrStringOrNumber): Date; + namespace startOfMonth {} + + function startOfQuarter(date: DateOrStringOrNumber): Date; + namespace startOfQuarter {} + + function startOfSecond(date: DateOrStringOrNumber): Date; + namespace startOfSecond {} + + function startOfToday(): Date; + namespace startOfToday {} + + function startOfTomorrow(): Date; + namespace startOfTomorrow {} + + function startOfWeek(date: DateOrStringOrNumber, options?: {weekStartsOn: number}): Date; + namespace startOfWeek {} + + function startOfYear(date: DateOrStringOrNumber): Date; + namespace startOfYear {} + + function startOfYesterday(): Date; + namespace startOfYesterday {} + + function subDays(date: DateOrStringOrNumber, amount: number): Date; + namespace subDays {} + + function subHours(date: DateOrStringOrNumber, amount: number): Date; + namespace subHours {} + + function subISOYears(date: DateOrStringOrNumber, amount: number): Date; + namespace subISOYears {} + + function subMilliseconds(date: DateOrStringOrNumber, amount: number): Date; + namespace subMilliseconds {} + + function subMinutes(date: DateOrStringOrNumber, amount: number): Date; + namespace subMinutes {} + + function subMonths(date: DateOrStringOrNumber, amount: number): Date; + namespace subMonths {} + + function subQuarters(date: DateOrStringOrNumber, amount: number): Date; + namespace subQuarters {} + + function subSeconds(date: DateOrStringOrNumber, amount: number): Date; + namespace subSeconds {} + + function subWeeks(date: DateOrStringOrNumber, amount: number): Date; + namespace subWeeks {} + + function subYears(date: DateOrStringOrNumber, amount: number): Date; + namespace subYears {} + +} + +declare module 'date-fns/add_days' { + import {addDays} from 'date-fns'; + export = addDays; +} + +declare module 'date-fns/add_hours' { + import {addHours} from 'date-fns'; + export = addHours; +} + +declare module 'date-fns/add_iso_years' { + import {addISOYears} from 'date-fns'; + export = addISOYears; +} + +declare module 'date-fns/add_milliseconds' { + import {addMilliseconds} from 'date-fns'; + export = addMilliseconds; +} + +declare module 'date-fns/add_minutes' { + import {addMinutes} from 'date-fns'; + export = addMinutes; +} + +declare module 'date-fns/add_months' { + import {addMonths} from 'date-fns'; + export = addMonths; +} + +declare module 'date-fns/add_quarters' { + import {addQuarters} from 'date-fns'; + export = addQuarters; +} + +declare module 'date-fns/add_seconds' { + import {addSeconds} from 'date-fns'; + export = addSeconds; +} + +declare module 'date-fns/add_weeks' { + import {addWeeks} from 'date-fns'; + export = addWeeks; +} + +declare module 'date-fns/add_years' { + import {addYears} from 'date-fns'; + export = addYears; +} + +declare module 'date-fns/closest_index_to' { + import {closestIndexTo} from 'date-fns'; + export = closestIndexTo; +} + +declare module 'date-fns/closest_to' { + import {closestTo} from 'date-fns'; + export = closestTo; +} + +declare module 'date-fns/compare_asc' { + import {compareAsc} from 'date-fns'; + export = compareAsc; +} + +declare module 'date-fns/compare_desc' { + import {compareDesc} from 'date-fns'; + export = compareDesc; +} + +declare module 'date-fns/difference_in_calendar_days' { + import {differenceInCalendarDays} from 'date-fns'; + export = differenceInCalendarDays; +} + +declare module 'date-fns/difference_in_calendar_iso_weeks' { + import {differenceInCalendarISOWeeks} from 'date-fns'; + export = differenceInCalendarISOWeeks; +} + +declare module 'date-fns/difference_in_calendar_iso_years' { + import {differenceInCalendarISOYears} from 'date-fns'; + export = differenceInCalendarISOYears; +} + +declare module 'date-fns/difference_in_calendar_months' { + import {differenceInCalendarMonths} from 'date-fns'; + export = differenceInCalendarMonths; +} + +declare module 'date-fns/difference_in_calendar_quarters' { + import {differenceInCalendarQuarters} from 'date-fns'; + export = differenceInCalendarQuarters; +} + +declare module 'date-fns/difference_in_calendar_weeks' { + import {differenceInCalendarWeeks} from 'date-fns'; + export = differenceInCalendarWeeks; +} + +declare module 'date-fns/difference_in_calendar_years' { + import {differenceInCalendarYears} from 'date-fns'; + export = differenceInCalendarYears; +} + +declare module 'date-fns/difference_in_days' { + import {differenceInDays} from 'date-fns'; + export = differenceInDays; +} + +declare module 'date-fns/difference_in_hours' { + import {differenceInHours} from 'date-fns'; + export = differenceInHours; +} + +declare module 'date-fns/difference_in_iso_years' { + import {differenceInISOYears} from 'date-fns'; + export = differenceInISOYears; +} + +declare module 'date-fns/difference_in_milliseconds' { + import {differenceInMilliseconds} from 'date-fns'; + export = differenceInMilliseconds; +} + +declare module 'date-fns/difference_in_minutes' { + import {differenceInMinutes} from 'date-fns'; + export = differenceInMinutes; +} + +declare module 'date-fns/difference_in_months' { + import {differenceInMonths} from 'date-fns'; + export = differenceInMonths; +} + +declare module 'date-fns/difference_in_quarters' { + import {differenceInQuarters} from 'date-fns'; + export = differenceInQuarters; +} + +declare module 'date-fns/difference_in_seconds' { + import {differenceInSeconds} from 'date-fns'; + export = differenceInSeconds; +} + +declare module 'date-fns/difference_in_weeks' { + import {differenceInWeeks} from 'date-fns'; + export = differenceInWeeks; +} + +declare module 'date-fns/difference_in_years' { + import {differenceInYears} from 'date-fns'; + export = differenceInYears; +} + +declare module 'date-fns/distance_in_words' { + import {distanceInWords} from 'date-fns'; + export = distanceInWords; +} + +declare module 'date-fns/distance_in_words_to_now' { + import {distanceInWordsToNow} from 'date-fns'; + export = distanceInWordsToNow; +} + +declare module 'date-fns/each_day' { + import {eachDay} from 'date-fns'; + export = eachDay; +} + +declare module 'date-fns/end_of_day' { + import {endOfDay} from 'date-fns'; + export = endOfDay; +} + +declare module 'date-fns/end_of_hour' { + import {endOfHour} from 'date-fns'; + export = endOfHour; +} + +declare module 'date-fns/end_of_iso_week' { + import {endOfISOWeek} from 'date-fns'; + export = endOfISOWeek; +} + +declare module 'date-fns/end_of_iso_year' { + import {endOfISOYear} from 'date-fns'; + export = endOfISOYear; +} + +declare module 'date-fns/end_of_minute' { + import {endOfMinute} from 'date-fns'; + export = endOfMinute; +} + +declare module 'date-fns/end_of_month' { + import {endOfMonth} from 'date-fns'; + export = endOfMonth; +} + +declare module 'date-fns/end_of_quarter' { + import {endOfQuarter} from 'date-fns'; + export = endOfQuarter; +} + +declare module 'date-fns/end_of_second' { + import {endOfSecond} from 'date-fns'; + export = endOfSecond; +} + +declare module 'date-fns/end_of_today' { + import {endOfToday} from 'date-fns'; + export = endOfToday; +} + +declare module 'date-fns/end_of_tomorrow' { + import {endOfTomorrow} from 'date-fns'; + export = endOfTomorrow; +} + +declare module 'date-fns/end_of_week' { + import {endOfWeek} from 'date-fns'; + export = endOfWeek; +} + +declare module 'date-fns/end_of_year' { + import {endOfYear} from 'date-fns'; + export = endOfYear; +} + +declare module 'date-fns/end_of_yesterday' { + import {endOfYesterday} from 'date-fns'; + export = endOfYesterday; +} + +declare module 'date-fns/format' { + import {format} from 'date-fns'; + export = format; +} + +declare module 'date-fns/get_date' { + import {getDate} from 'date-fns'; + export = getDate; +} + +declare module 'date-fns/get_day' { + import {getDay} from 'date-fns'; + export = getDay; +} + +declare module 'date-fns/get_day_of_year' { + import {getDayOfYear} from 'date-fns'; + export = getDayOfYear; +} + +declare module 'date-fns/get_days_in_month' { + import {getDaysInMonth} from 'date-fns'; + export = getDaysInMonth; +} + +declare module 'date-fns/get_days_in_year' { + import {getDaysInYear} from 'date-fns'; + export = getDaysInYear; +} + +declare module 'date-fns/get_hours' { + import {getHours} from 'date-fns'; + export = getHours; +} + +declare module 'date-fns/get_iso_week' { + import {getISOWeek} from 'date-fns'; + export = getISOWeek; +} + +declare module 'date-fns/get_iso_weeks_in_year' { + import {getISOWeeksInYear} from 'date-fns'; + export = getISOWeeksInYear; +} + +declare module 'date-fns/get_iso_year' { + import {getISOYear} from 'date-fns'; + export = getISOYear; +} + +declare module 'date-fns/get_milliseconds' { + import {getMilliseconds} from 'date-fns'; + export = getMilliseconds; +} + +declare module 'date-fns/get_minutes' { + import {getMinutes} from 'date-fns'; + export = getMinutes; +} + +declare module 'date-fns/get_month' { + import {getMonth} from 'date-fns'; + export = getMonth; +} + +declare module 'date-fns/get_quarter' { + import {getQuarter} from 'date-fns'; + export = getQuarter; +} + +declare module 'date-fns/get_seconds' { + import {getSeconds} from 'date-fns'; + export = getSeconds; +} + +declare module 'date-fns/get_year' { + import {getYear} from 'date-fns'; + export = getYear; +} + +declare module 'date-fns/is_after' { + import {isAfter} from 'date-fns'; + export = isAfter; +} + +declare module 'date-fns/is_before' { + import {isBefore} from 'date-fns'; + export = isBefore; +} + +declare module 'date-fns/is_date' { + import {isDate} from 'date-fns'; + export = isDate; +} + +declare module 'date-fns/is_equal' { + import {isEqual} from 'date-fns'; + export = isEqual; +} + +declare module 'date-fns/is_first_day_of_month' { + import {isFirstDayOfMonth} from 'date-fns'; + export = isFirstDayOfMonth; +} + +declare module 'date-fns/is_friday' { + import {isFriday} from 'date-fns'; + export = isFriday; +} + +declare module 'date-fns/is_future' { + import {isFuture} from 'date-fns'; + export = isFuture; +} + +declare module 'date-fns/is_last_day_of_month' { + import {isLastDayOfMonth} from 'date-fns'; + export = isLastDayOfMonth; +} + +declare module 'date-fns/is_leap_year' { + import {isLeapYear} from 'date-fns'; + export = isLeapYear; +} + +declare module 'date-fns/is_monday' { + import {isMonday} from 'date-fns'; + export = isMonday; +} + +declare module 'date-fns/is_past' { + import {isPast} from 'date-fns'; + export = isPast; +} + +declare module 'date-fns/is_same_day' { + import {isSameDay} from 'date-fns'; + export = isSameDay; +} + +declare module 'date-fns/is_same_hour' { + import {isSameHour} from 'date-fns'; + export = isSameHour; +} + +declare module 'date-fns/is_same_iso_week' { + import {isSameISOWeek} from 'date-fns'; + export = isSameISOWeek; +} + +declare module 'date-fns/is_same_iso_year' { + import {isSameISOYear} from 'date-fns'; + export = isSameISOYear; +} + +declare module 'date-fns/is_same_minute' { + import {isSameMinute} from 'date-fns'; + export = isSameMinute; +} + +declare module 'date-fns/is_same_month' { + import {isSameMonth} from 'date-fns'; + export = isSameMonth; +} + +declare module 'date-fns/is_same_quarter' { + import {isSameQuarter} from 'date-fns'; + export = isSameQuarter; +} + +declare module 'date-fns/is_same_second' { + import {isSameSecond} from 'date-fns'; + export = isSameSecond; +} + +declare module 'date-fns/is_same_week' { + import {isSameWeek} from 'date-fns'; + export = isSameWeek; +} + +declare module 'date-fns/is_same_year' { + import {isSameYear} from 'date-fns'; + export = isSameYear; +} + +declare module 'date-fns/is_saturday' { + import {isSaturday} from 'date-fns'; + export = isSaturday; +} + +declare module 'date-fns/is_sunday' { + import {isSunday} from 'date-fns'; + export = isSunday; +} + +declare module 'date-fns/is_this_hour' { + import {isThisHour} from 'date-fns'; + export = isThisHour; +} + +declare module 'date-fns/is_this_iso_week' { + import {isThisISOWeek} from 'date-fns'; + export = isThisISOWeek; +} + +declare module 'date-fns/is_this_iso_year' { + import {isThisISOYear} from 'date-fns'; + export = isThisISOYear; +} + +declare module 'date-fns/is_this_minute' { + import {isThisMinute} from 'date-fns'; + export = isThisMinute; +} + +declare module 'date-fns/is_this_month' { + import {isThisMonth} from 'date-fns'; + export = isThisMonth; +} + +declare module 'date-fns/is_this_quarter' { + import {isThisQuarter} from 'date-fns'; + export = isThisQuarter; +} + +declare module 'date-fns/is_this_second' { + import {isThisSecond} from 'date-fns'; + export = isThisSecond; +} + +declare module 'date-fns/is_this_week' { + import {isThisWeek} from 'date-fns'; + export = isThisWeek; +} + +declare module 'date-fns/is_this_year' { + import {isThisYear} from 'date-fns'; + export = isThisYear; +} + +declare module 'date-fns/is_thursday' { + import {isThursday} from 'date-fns'; + export = isThursday; +} + +declare module 'date-fns/is_today' { + import {isToday} from 'date-fns'; + export = isToday; +} + +declare module 'date-fns/is_tomorrow' { + import {isTomorrow} from 'date-fns'; + export = isTomorrow; +} + +declare module 'date-fns/is_tuesday' { + import {isTuesday} from 'date-fns'; + export = isTuesday; +} + +declare module 'date-fns/is_valid' { + import {isValid} from 'date-fns'; + export = isValid; +} + +declare module 'date-fns/is_wednesday' { + import {isWednesday} from 'date-fns'; + export = isWednesday; +} + +declare module 'date-fns/is_weekend' { + import {isWeekend} from 'date-fns'; + export = isWeekend; +} + +declare module 'date-fns/is_within_range' { + import {isWithinRange} from 'date-fns'; + export = isWithinRange; +} + +declare module 'date-fns/is_yesterday' { + import {isYesterday} from 'date-fns'; + export = isYesterday; +} + +declare module 'date-fns/last_day_of_iso_week' { + import {lastDayOfISOWeek} from 'date-fns'; + export = lastDayOfISOWeek; +} + +declare module 'date-fns/last_day_of_iso_year' { + import {lastDayOfISOYear} from 'date-fns'; + export = lastDayOfISOYear; +} + +declare module 'date-fns/last_day_of_month' { + import {lastDayOfMonth} from 'date-fns'; + export = lastDayOfMonth; +} + +declare module 'date-fns/last_day_of_quarter' { + import {lastDayOfQuarter} from 'date-fns'; + export = lastDayOfQuarter; +} + +declare module 'date-fns/last_day_of_week' { + import {lastDayOfWeek} from 'date-fns'; + export = lastDayOfWeek; +} + +declare module 'date-fns/last_day_of_year' { + import {lastDayOfYear} from 'date-fns'; + export = lastDayOfYear; +} + +declare module 'date-fns/max' { + import {max} from 'date-fns'; + export = max; +} + +declare module 'date-fns/min' { + import {min} from 'date-fns'; + export = min; +} + +declare module 'date-fns/parse' { + import {parse} from 'date-fns'; + export = parse; +} + +declare module 'date-fns/set_date' { + import {setDate} from 'date-fns'; + export = setDate; +} + +declare module 'date-fns/set_day' { + import {setDay} from 'date-fns'; + export = setDay; +} + +declare module 'date-fns/set_day_of_year' { + import {setDayOfYear} from 'date-fns'; + export = setDayOfYear; +} + +declare module 'date-fns/set_hours' { + import {setHours} from 'date-fns'; + export = setHours; +} + +declare module 'date-fns/set_iso_week' { + import {setISOWeek} from 'date-fns'; + export = setISOWeek; +} + +declare module 'date-fns/set_iso_year' { + import {setISOYear} from 'date-fns'; + export = setISOYear; +} + +declare module 'date-fns/set_milliseconds' { + import {setMilliseconds} from 'date-fns'; + export = setMilliseconds; +} + +declare module 'date-fns/set_minutes' { + import {setMinutes} from 'date-fns'; + export = setMinutes; +} + +declare module 'date-fns/set_month' { + import {setMonth} from 'date-fns'; + export = setMonth; +} + +declare module 'date-fns/set_quarter' { + import {setQuarter} from 'date-fns'; + export = setQuarter; +} + +declare module 'date-fns/set_seconds' { + import {setSeconds} from 'date-fns'; + export = setSeconds; +} + +declare module 'date-fns/set_year' { + import {setYear} from 'date-fns'; + export = setYear; +} + +declare module 'date-fns/start_of_day' { + import {startOfDay} from 'date-fns'; + export = startOfDay; +} + +declare module 'date-fns/start_of_hour' { + import {startOfHour} from 'date-fns'; + export = startOfHour; +} + +declare module 'date-fns/start_of_iso_week' { + import {startOfISOWeek} from 'date-fns'; + export = startOfISOWeek; +} + +declare module 'date-fns/start_of_iso_year' { + import {startOfISOYear} from 'date-fns'; + export = startOfISOYear; +} + +declare module 'date-fns/start_of_minute' { + import {startOfMinute} from 'date-fns'; + export = startOfMinute; +} + +declare module 'date-fns/start_of_month' { + import {startOfMonth} from 'date-fns'; + export = startOfMonth; +} + +declare module 'date-fns/start_of_quarter' { + import {startOfQuarter} from 'date-fns'; + export = startOfQuarter; +} + +declare module 'date-fns/start_of_second' { + import {startOfSecond} from 'date-fns'; + export = startOfSecond; +} + +declare module 'date-fns/start_of_today' { + import {startOfToday} from 'date-fns'; + export = startOfToday; +} + +declare module 'date-fns/start_of_tomorrow' { + import {startOfTomorrow} from 'date-fns'; + export = startOfTomorrow; +} + +declare module 'date-fns/start_of_week' { + import {startOfWeek} from 'date-fns'; + export = startOfWeek; +} + +declare module 'date-fns/start_of_year' { + import {startOfYear} from 'date-fns'; + export = startOfYear; +} + +declare module 'date-fns/start_of_yesterday' { + import {startOfYesterday} from 'date-fns'; + export = startOfYesterday; +} + +declare module 'date-fns/sub_days' { + import {subDays} from 'date-fns'; + export = subDays; +} + +declare module 'date-fns/sub_hours' { + import {subHours} from 'date-fns'; + export = subHours; +} + +declare module 'date-fns/sub_iso_years' { + import {subISOYears} from 'date-fns'; + export = subISOYears; +} + +declare module 'date-fns/sub_milliseconds' { + import {subMilliseconds} from 'date-fns'; + export = subMilliseconds; +} + +declare module 'date-fns/sub_minutes' { + import {subMinutes} from 'date-fns'; + export = subMinutes; +} + +declare module 'date-fns/sub_months' { + import {subMonths} from 'date-fns'; + export = subMonths; +} + +declare module 'date-fns/sub_quarters' { + import {subQuarters} from 'date-fns'; + export = subQuarters; +} + +declare module 'date-fns/sub_seconds' { + import {subSeconds} from 'date-fns'; + export = subSeconds; +} + +declare module 'date-fns/sub_weeks' { + import {subWeeks} from 'date-fns'; + export = subWeeks; +} + +declare module 'date-fns/sub_years' { + import {subYears} from 'date-fns'; + export = subYears; +} + diff --git a/easeljs/easeljs.d.ts b/easeljs/easeljs.d.ts index 3ddeabdef9..ab8cd5a0e1 100644 --- a/easeljs/easeljs.d.ts +++ b/easeljs/easeljs.d.ts @@ -650,6 +650,7 @@ declare namespace createjs { autoReset: boolean; static buildDate: string; currentFrame: number; + totalFrames: number; currentLabel: string; frameBounds: Rectangle[]; framerate: number; @@ -662,6 +663,7 @@ declare namespace createjs { startPosition: number; static SYNCHED: string; timeline: Timeline; + duration: number; static version: string; // methods diff --git a/elasticsearch/elasticsearch-tests.ts b/elasticsearch/elasticsearch-tests.ts index 14070aa8cc..6d308dc6ed 100644 --- a/elasticsearch/elasticsearch-tests.ts +++ b/elasticsearch/elasticsearch-tests.ts @@ -45,4 +45,44 @@ client.create({ index: 'index', type: 'type' }, (err, repsonse, status) => { +}); + +client.cluster.getSettings({ + masterTimeout: 100 +}, (err, response) => { +}); + +client.cluster.health({ + masterTimeout: 100 +}, (err, response) => { +}); + +client.cluster.pendingTasks({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.putSettings({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.putSettings({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.reroute({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.state({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.stats({ + ignore: 1 +}, (err, response) => { }); \ No newline at end of file diff --git a/elasticsearch/elasticsearch.d.ts b/elasticsearch/elasticsearch.d.ts index ec67e6a59d..d983817869 100644 --- a/elasticsearch/elasticsearch.d.ts +++ b/elasticsearch/elasticsearch.d.ts @@ -1,26 +1,28 @@ // Type definitions for elasticsearch // Project: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html -// Definitions by: Casper Skydt +// Definitions by: Casper Skydt , Blake Smith , Dave Dunkin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module Elasticsearch { export class Client { constructor(params: ConfigOptions); indices: Indices; + cluster: Cluster; + cat: Cat; bulk(params: BulkIndexDocumentsParams): PromiseLike; bulk(params: BulkIndexDocumentsParams, callback: (error: any, response: any) => void): void; create(params: CreateDocumentParams): PromiseLike; 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; + get(params: GetParams, callback: (error: any, response: GetResponse) => void): void; get(params: GetParams): PromiseLike>; index(params: IndexDocumentParams): PromiseLike; index(params: IndexDocumentParams, callback: (error: any, response: any) => void): void; - mget(params: MGetParams, callback: (error: any, response: any) => void): void; - mget(params: MGetParams): PromiseLike>; - msearch(params: MSearchParams, callback: (error: any, response: any) => void): void; - msearch(params: MSearchParams): PromiseLike>; + mget(params: MGetParams, callback: (error: any, response: MGetResponse) => void): void; + mget(params: MGetParams): PromiseLike>; + msearch(params: MSearchParams, callback: (error: any, response: MSearchResponse) => void): void; + msearch(params: MSearchParams): PromiseLike>; ping(params: PingParams): PromiseLike; ping(params: PingParams, callback: (err: any, response: any, status: any) => void): void; scroll(params: ScrollParams): PromiseLike; @@ -194,7 +196,8 @@ declare module Elasticsearch { versionType?: string; } - export interface GetResponse extends GenericParams { + export interface GetResponse { + _index: string; _type: string; _id: string; _version: number; @@ -230,6 +233,7 @@ declare module Elasticsearch { scroll?: string; search_type?: string; fields?: string[]; + from?: number; size?: number; sort?: string | string[] | boolean; _source?: string | string[] | boolean; @@ -276,6 +280,10 @@ declare module Elasticsearch { search_type?: string; } + export interface MSearchResponse { + responses?: SearchResponse[]; + } + export interface MGetParams extends GenericParams { fields?: string | string[] | Boolean; preference?: string; @@ -287,6 +295,10 @@ declare module Elasticsearch { type?: string; } + export interface MGetResponse { + docs?: GetResponse[]; + } + export interface IndicesIndexExitsParams extends GenericParams { index: string | string[] | boolean; ignoreUnavailable?: boolean; @@ -333,6 +345,91 @@ declare module Elasticsearch { body: string | any; index: string | string[] | boolean; } + + export interface Cat { + health(params: CatHealthOptions, callback: (error: any, response: any) => void): void; + health(params: CatHealthOptions): PromiseLike + } + + export interface CatHealthOptions extends GenericParams { + local?: boolean; + masterTimeout?: number | Date; + h?: string | string[] | boolean; + help?: boolean; + ts?: boolean; + v?: boolean; + } + + export interface Cluster { + getSettings(params: ClusterGetSettingsOptions, callback: (error: any, response: any) => void): void; + getSettings(params: ClusterGetSettingsOptions): PromiseLike; + health(params: ClusterHealthOptions, callback: (error: any, response: any) => void): void; + health(params: ClusterHealthOptions): PromiseLike; + pendingTasks(params: ClusterPendingTasksOptions, callback: (error: any, response: any) => void): void; + pendingTasks(params: ClusterPendingTasksOptions): PromiseLike; + putSettings(params: ClusterPutSettingsOptions, callback: (error: any, response: any) => void): void; + putSettings(params: ClusterPutSettingsOptions): PromiseLike; + reroute(params: ClusterRerouteOptions, callback: (error: any, response: any) => void): void; + reroute(params: ClusterRerouteOptions): PromiseLike; + state(params: ClusterStateOptions, callback: (error: any, response: any) => void): void; + state(params: ClusterStateOptions): PromiseLike; + stats(params: ClusterStatsOptions, callback: (error: any, response: any) => void): void; + stats(params: ClusterStatsOptions): PromiseLike; + } + + export interface ClusterGetSettingsOptions extends GenericParams { + flatSettings?: boolean; + masterTimeout?: number | Date; + timeout?: number | Date; + } + + export interface ClusterHealthOptions extends GenericParams { + level?: string; // cluster, indices, shards + local?: boolean; + masterTimeout?: number | Date; + waitForActiveShards?: number; + waitForNodes?: string; + waitForRelocatingShards?: number; + waitForStatus?: string; // green, yellow, red + index?: string | string[] | boolean; + } + + export interface ClusterPendingTasksOptions extends GenericParams { + local?: boolean; + masterTimeout?: number | Date; + } + + export interface ClusterPutSettingsOptions extends GenericParams { + flatSettings?: boolean; + masterTimeout?: number | Date; + timeout?: number | Date; + } + + export interface ClusterRerouteOptions extends GenericParams { + dryRun?: boolean; + explain?: boolean; + metric?: string | string[] | boolean; + masterTimeout?: number | Date; + timeout?: number | Date; + } + + export interface ClusterStateOptions extends GenericParams { + local?: boolean; + masterTimeout?: number | Date; + flatSettings?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: string; // open, closed, none, all (default open) + index?: string | string[] | boolean; + metric?: string | string[] | boolean; + } + + export interface ClusterStatsOptions extends GenericParams { + flatSettings?: boolean; + human?: boolean; + timeout?: number | Date; + nodeId?: string | string[] | boolean; + } } declare module "elasticsearch" { diff --git a/enzyme/enzyme.d.ts b/enzyme/enzyme.d.ts index 4a5bf2beac..31ffce8923 100644 --- a/enzyme/enzyme.d.ts +++ b/enzyme/enzyme.d.ts @@ -458,6 +458,7 @@ declare module "enzyme" { export interface ReactWrapper extends CommonWrapper { unmount(): ReactWrapper; mount(): ReactWrapper; + render(): CheerioWrapper; /** * Returns a wrapper of the node that matches the provided reference name. 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 93551ffece..e80ffa85a9 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -1046,6 +1046,11 @@ declare module "express-serve-static-core" { * simply by removing them from this object. */ routes: any; + + /** + * Using to all registered routes in Express Application + */ + _router: any; } interface Express extends Application { diff --git a/express/express-tests.ts b/express/express-tests.ts index 439ef95012..92cef00b85 100644 --- a/express/express-tests.ts +++ b/express/express-tests.ts @@ -1,101 +1,114 @@ /// /// - import * as express from 'express'; -var app = express(); - -app.engine('jade', require('jade').__express); -app.engine('html', require('ejs').renderFile); - -express.static.mime.define({ - 'application/fx': ['fx'] -}); -app.use('/static', express.static(__dirname + '/public')); - -// simple logger -app.use(function(req, res, next){ - console.log('%s %s', req.method, req.url); - next(); -}); - -app.use(function(err: any, req: express.Request, res: express.Response, next: express.NextFunction) { - console.error(err); - next(err); -}); -app.get('/', function(req, res){ - res.send('hello world'); -}); +namespace express_tests { -const router = express.Router(); + var app = express(); + app.engine('jade', require('jade').__express); + app.engine('html', require('ejs').renderFile); -const pathStr : string = 'test'; -const pathRE : RegExp = /test/; -const path = true? pathStr : pathRE; + express.static.mime.define({ + 'application/fx': ['fx'] + }); + app.use('/static', express.static(__dirname + '/public')); -router.get(path); -router.put(path) -router.post(path); -router.delete(path); -router.get(pathStr); -router.put(pathStr) -router.post(pathStr); -router.delete(pathStr); -router.get(pathRE); -router.put(pathRE) -router.post(pathRE); -router.delete(pathRE); - -router.use((req, res, next) => { next(); }) -router.route('/users') - .get((req, res, next) => { - let types: string[] = req.accepts(); - let type: string | boolean = req.accepts('json'); - type = req.accepts(['json', 'text']); - type = req.accepts('json', 'text'); - - let charsets: string[] = req.acceptsCharsets(); - let charset: string | boolean = req.acceptsCharsets('utf-8'); - charset = req.acceptsCharsets(['utf-8', 'utf-16']); - charset = req.acceptsCharsets('utf-8', 'utf-16'); - - let encodings: string[] = req.acceptsEncodings(); - let encoding: string | boolean = req.acceptsEncodings('gzip'); - encoding = req.acceptsEncodings(['gzip', 'deflate']); - encoding = req.acceptsEncodings('gzip', 'deflate'); - - let languages: string[] = req.acceptsLanguages(); - let language: string | boolean = req.acceptsLanguages('en'); - language = req.acceptsLanguages(['en', 'ja']); - language = req.acceptsLanguages('en', 'ja'); - - res.send(req.query['token']); + // simple logger + app.use(function(req, res, next) { + console.log('%s %s', req.method, req.url); + next(); }); -router.get('/user/:id', function(req, res, next) { - if (req.params.id == 0) next('route'); - else next(); -}, function(req, res, next) { - res.render('regular'); -}); + app.use(function(err: any, req: express.Request, res: express.Response, next: express.NextFunction) { + console.error(err); + next(err); + }); -app.use((req, res, next) => { - // hacky trick, router is just a handler - router(req, res, next); -}); -app.use(router); + app.get('/', function(req, res) { + res.send('hello world'); + }); -app.listen(3000); + const router = express.Router(); -const next: express.NextFunction = () => {}; -const nextWithArgument: express.NextFunction = (err: any) => {}; -/** - * The express.Application is compatible with http.createServer - */ + const pathStr: string = 'test'; + const pathRE: RegExp = /test/; + const path = true ? pathStr : pathRE; + router.get(path); + router.put(path) + router.post(path); + router.delete(path); + router.get(pathStr); + router.put(pathStr) + router.post(pathStr); + router.delete(pathStr); + router.get(pathRE); + router.put(pathRE) + router.post(pathRE); + router.delete(pathRE); + + router.use((req, res, next) => { next(); }) + router.route('/users') + .get((req, res, next) => { + let types: string[] = req.accepts(); + let type: string | boolean = req.accepts('json'); + type = req.accepts(['json', 'text']); + type = req.accepts('json', 'text'); + + let charsets: string[] = req.acceptsCharsets(); + let charset: string | boolean = req.acceptsCharsets('utf-8'); + charset = req.acceptsCharsets(['utf-8', 'utf-16']); + charset = req.acceptsCharsets('utf-8', 'utf-16'); + + let encodings: string[] = req.acceptsEncodings(); + let encoding: string | boolean = req.acceptsEncodings('gzip'); + encoding = req.acceptsEncodings(['gzip', 'deflate']); + encoding = req.acceptsEncodings('gzip', 'deflate'); + + let languages: string[] = req.acceptsLanguages(); + let language: string | boolean = req.acceptsLanguages('en'); + language = req.acceptsLanguages(['en', 'ja']); + language = req.acceptsLanguages('en', 'ja'); + + res.send(req.query['token']); + }); + + router.get('/user/:id', function(req, res, next) { + if (req.params.id == 0) next('route'); + else next(); + }, function(req, res, next) { + res.render('regular'); + }); + + app.use((req, res, next) => { + // hacky trick, router is just a handler + router(req, res, next); + }); + + app.use(router); + + app.listen(3000); + + const next: express.NextFunction = () => { }; +} + +/*************************** + * * + * Test with other modules * + * * + ***************************/ import * as http from 'http'; -http.createServer(app); + + +namespace node_tests { + + { + // http.createServer can take express application + const app: express.Application = express(); + http.createServer(app).listen(5678); + } +} diff --git a/facebook-js-sdk/facebook-js-sdk-tests.ts b/facebook-js-sdk/facebook-js-sdk-tests.ts index 49e615f529..41c0eaff40 100644 --- a/facebook-js-sdk/facebook-js-sdk-tests.ts +++ b/facebook-js-sdk/facebook-js-sdk-tests.ts @@ -14,6 +14,12 @@ FB.getLoginStatus(function(response: fb.AuthResponse) { console.log(response.authResponse.accessToken); }); +FB.getLoginStatus(function(response: fb.AuthResponse) { + console.log(response); + console.log(response.status); + console.log(response.authResponse.accessToken); +}, true); + FB.getAuthResponse(function(response: fb.AuthResponse) { console.log(response); console.log(response.status); diff --git a/facebook-js-sdk/facebook-js-sdk.d.ts b/facebook-js-sdk/facebook-js-sdk.d.ts index 5353353911..bee34f0a2c 100644 --- a/facebook-js-sdk/facebook-js-sdk.d.ts +++ b/facebook-js-sdk/facebook-js-sdk.d.ts @@ -8,10 +8,11 @@ declare var FB: fb.FacebookStatic; declare namespace facebook { interface FacebookStatic { - // api: any; - // AppEvents: any; - // Canvas: any; - // Event: any; + api: any; + AppEvents: any; + Canvas: any; + Event: any; + /** * The method FB.getAuthResponse() is a synchronous accessor for the current authResponse. * The synchronous nature of this method is what sets it apart from the other login methods. @@ -25,7 +26,7 @@ declare namespace facebook { * * @param callback function to handle the response. */ - getLoginStatus(callback: (response: AuthResponse) => void): void; + getLoginStatus(callback: (response: AuthResponse) => void, roundtrip?: boolean ): void; /** * The method FB.init() is used to initialize and setup the SDK. * @@ -49,8 +50,9 @@ declare namespace facebook { * @param callback function to handle the response */ logout(callback: (response: AuthResponse) => void): void; - // ui: any; - // XFBML: any; + + ui: any; + XFBML: any; } interface InitParams { diff --git a/fs-extra-promise/fs-extra-promise.d.ts b/fs-extra-promise/fs-extra-promise.d.ts index bdf8360b77..2243a4d1c5 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/github-electron/github-electron-main-tests.ts b/github-electron/github-electron-main-tests.ts index bebf0b99c8..966465ed3a 100644 --- a/github-electron/github-electron-main-tests.ts +++ b/github-electron/github-electron-main-tests.ts @@ -240,6 +240,63 @@ app.setUserTasks([ } ]); app.setUserTasks([]); + +app.setJumpList([ + { + type: 'custom', + name: 'Recent Projects', + items: [ + { type: 'file', path: 'C:\\Projects\\project1.proj' }, + { type: 'file', path: 'C:\\Projects\\project2.proj' } + ] + }, + { // has a name so type is assumed to be "custom" + name: 'Tools', + items: [ + { + type: 'task', + title: 'Tool A', + program: process.execPath, + args: '--run-tool-a', + iconPath: process.execPath, + iconIndex: 0, + description: 'Runs Tool A' + }, + { + type: 'task', + title: 'Tool B', + program: process.execPath, + args: '--run-tool-b', + iconPath: process.execPath, + iconIndex: 0, + description: 'Runs Tool B' + }] + }, + { + type: 'frequent' + }, + { // has no name and no type so type is assumed to be "tasks" + items: [ + { + type: 'task', + title: 'New Project', + program: process.execPath, + args: '--new-project', + description: 'Create a new project.' + }, + { + type: 'separator' + }, + { + type: 'task', + title: 'Recover Project', + program: process.execPath, + args: '--recover-project', + description: 'Recover Project' + }] + } +]); + if (app.isUnityRunning()) { } if (app.isAccessibilitySupportEnabled()) { diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 7d10fce465..64b7cf6a02 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Electron v1.3.4 +// Type definitions for Electron v1.3.6 // Project: http://electron.atom.io/ // Definitions by: jedmao , rhysd , Milan Burda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -62,7 +62,7 @@ declare namespace Electron { /** * Emitted when Electron has finished initialization. */ - on(event: 'ready', listener: Function): this; + on(event: 'ready', listener: (event: Event, launchInfo: Object) => void): this; /** * Emitted when all windows have been closed. * @@ -199,7 +199,7 @@ declare namespace Electron { * All windows will be closed immediately without asking user * and the before-quit and will-quit events will not be emitted. */ - exit(exitCode: number): void; + exit(exitCode?: number): void; /** * Relaunches the app when current instance exits. * @@ -218,6 +218,10 @@ declare namespace Electron { args?: string[], execPath?: string }): void; + /** + * @returns Whether Electron has finished initializing. + */ + isReady(): boolean; /** * On Linux, focuses on the first visible window. * On macOS, makes the application the active app. @@ -333,6 +337,19 @@ declare namespace Electron { * Note: This API is only available on Windows. */ setUserTasks(tasks: Task[]): boolean; + /** + * Note: This API is only available on Windows. + */ + getJumpListSettings(): JumpListSettings; + /** + * Sets or removes a custom Jump List for the application. + * + * If categories is null the previously set custom Jump List (if any) will be replaced + * by the standard Jump List for the app (managed by Windows). + * + * Note: This API is only available on Windows. + */ + setJumpList(categories: JumpListCategory[]): SetJumpListResult; /** * This method makes your application a Single Instance Application instead of allowing * multiple instances of your app to run, this will ensure that only a single instance @@ -560,6 +577,89 @@ declare namespace Electron { iconIndex?: number; } + /** + * ok - Nothing went wrong. + * error - One or more errors occured, enable runtime logging to figure out the likely cause. + * invalidSeparatorError - An attempt was made to add a separator to a custom category in the Jump List. + * Separators are only allowed in the standard Tasks category. + * fileTypeRegistrationError - An attempt was made to add a file link to the Jump List + * for a file type the app isn't registered to handle. + * customCategoryAccessDeniedError - Custom categories can't be added to the Jump List + * due to user privacy or group policy settings. + */ + type SetJumpListResult = 'ok' | 'error' | 'invalidSeparatorError' | 'fileTypeRegistrationError' | 'customCategoryAccessDeniedError'; + + interface JumpListSettings { + /** + * The minimum number of items that will be shown in the Jump List. + */ + minItems: number; + /** + * Items that the user has explicitly removed from custom categories in the Jump List. + */ + removedItems: JumpListItem[]; + } + + interface JumpListCategory { + /** + * tasks - Items in this category will be placed into the standard Tasks category. + * frequent - Displays a list of files frequently opened by the app, the name of the category and its items are set by Windows. + * recent - Displays a list of files recently opened by the app, the name of the category and its items are set by Windows. + * custom - Displays tasks or file links, name must be set by the app. + */ + type?: 'tasks' | 'frequent' | 'recent' | 'custom'; + /** + * Must be set if type is custom, otherwise it should be omitted. + */ + name?: string; + /** + * Array of JumpListItem objects if type is tasks or custom, otherwise it should be omitted. + */ + items?: JumpListItem[]; + } + + interface JumpListItem { + /** + * task - A task will launch an app with specific arguments. + * separator - Can be used to separate items in the standard Tasks category. + * file - A file link will open a file using the app that created the Jump List. + */ + type: 'task' | 'separator' | 'file'; + /** + * Path of the file to open, should only be set if type is file. + */ + path?: string; + /** + * Path of the program to execute, usually you should specify process.execPath which opens the current program. + * Should only be set if type is task. + */ + program?: string; + /** + * The command line arguments when program is executed. Should only be set if type is task. + */ + args?: string; + /** + * The text to be displayed for the item in the Jump List. Should only be set if type is task. + */ + title?: string; + /** + * Description of the task (displayed in a tooltip). Should only be set if type is task. + */ + description?: string; + /** + * The absolute path to an icon to be displayed in a Jump List, which can be an arbitrary + * resource file that contains an icon (e.g. .ico, .exe, .dll). + * You can usually specify process.execPath to show the program icon. + */ + iconPath?: string; + /** + * The index of the icon in the resource file. If a resource file contains multiple icons + * this value can be used to specify the zero-based index of the icon that should be displayed + * for this task. If a resource file contains only one icon, this property should be set to zero. + */ + iconIndex?: number; + } + interface LoginItemSettings { /** * True if the app is set to open at login. @@ -1271,6 +1371,12 @@ declare namespace Electron { } interface WebPreferences { + /** + * Whether to enable DevTools. + * If it is set to false, can not use BrowserWindow.webContents.openDevTools() to open DevTools. + * Default: true. + */ + devTools?: boolean; /** * Whether node integration is enabled. * Default: true. @@ -1861,7 +1967,7 @@ declare namespace Electron { interface CrashReporterStartOptions { /** - * Default: Electron + * Default: app.getName() */ productName?: string; companyName: string; @@ -3296,16 +3402,18 @@ declare namespace Electron { interface Shell { /** * Show the given file in a file manager. If possible, select the file. + * @returns Whether the item was successfully shown. */ - showItemInFolder(fullPath: string): void; + showItemInFolder(fullPath: string): boolean; /** * Open the given file in the desktop's default manner. + * @returns Whether the item was successfully shown. */ - openItem(fullPath: string): void; + openItem(fullPath: string): boolean; /** * Open the given external protocol URL in the desktop's default manner * (e.g., mailto: URLs in the default mail user agent). - * @returns true if an application was available to open the URL, false otherwise. + * @returns Whether an application was available to open the URL. */ openExternal(url: string, options?: { /** @@ -3316,7 +3424,7 @@ declare namespace Electron { }): boolean; /** * Move the given file to trash. - * @returns boolean status for the operation. + * @returns Whether the item was successfully moved to the trash. */ moveItemToTrash(fullPath: string): boolean; /** @@ -3595,7 +3703,7 @@ declare namespace Electron { interface WebContentsStatic { /** - * @returns An array of all web contents. This will contain web contents for all windows, + * @returns An array of all WebContents instances. This will contain web contents for all windows, * webviews, opened devtools, and devtools extension background pages. */ getAllWebContents(): WebContents[]; @@ -3603,6 +3711,10 @@ declare namespace Electron { * @returns The web contents that is focused in this application, otherwise returns null. */ getFocusedWebContents(): WebContents; + /** + * Find a WebContents instance according to its ID. + */ + fromId(id: number): WebContents; } /** @@ -4971,6 +5083,17 @@ declare namespace Electron { * See webContents.sendInputEvent for detailed description of event object. */ sendInputEvent(event: SendInputEvent): void + /** + * Changes the zoom factor to the specified factor. + * Zoom factor is zoom percent divided by 100, so 300% = 3.0. + */ + setZoomFactor(factor: number): void; + /** + * Changes the zoom level to the specified level. + * The original size is 0 and each increment above or below represents + * zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. + */ + setZoomLevel(level: number): void; /** * Shows pop-up dictionary that searches the selected word on the page. * Note: This API is available only on macOS. diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 0eaa0b9c3d..0aef3b74a6 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -756,7 +756,7 @@ declare namespace google.maps { zIndex?: number; } - export interface PolyMouseEvent { + export interface PolyMouseEvent extends MouseEvent { edge?: number; path?: number; vertex?: number; diff --git a/heatmap.js/heatmap.d.ts b/heatmap.js/heatmap.d.ts index 7cd14fc214..fb2b4eea3d 100644 --- a/heatmap.js/heatmap.d.ts +++ b/heatmap.js/heatmap.d.ts @@ -3,7 +3,7 @@ // Definitions by: Yang Guan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /* * Configuration object of a heatmap diff --git a/heremaps/heremaps.d.ts b/heremaps/heremaps.d.ts index fe79e55ecf..8d730f3ae5 100644 --- a/heremaps/heremaps.d.ts +++ b/heremaps/heremaps.d.ts @@ -1073,6 +1073,125 @@ declare namespace H { */ resizeToCenter(center: H.geo.IPoint, opt_out?: H.geo.Rect): H.geo.Rect; } + + /** + * A strip is a flat list of latitude, longitude, altitude tuples in a fixed order. + */ + export class Strip { + /** + * Constructor + * @param opt_latLngAlts {Array=} - An optional array of latitude, longitude and altitude triples to initialize the strip with. + * @param opt_ctx {H.geo.AltitudeContext=} - An optional altitude context for all altitudes contained in this strip. + */ + constructor(opt_latLngAlts?: Array, opt_ctx?: H.geo.AltitudeContext); + + /** + * This method pushes a lat, lng, alt to the end of this strip. + * @param lat {H.geo.Latitude} + * @param lng {H.geo.Longitude} + * @param alt {H.geo.Altitude} + */ + pushLatLngAlt(lat: H.geo.Latitude, lng: H.geo.Longitude, alt: H.geo.Altitude): void; + + /** + * This method splices the strip at the provided index, removing the specified number of items at that index and inserting the lat, lng, alt array. + * @param index {number} - The index at which to splice + * @param opt_nRemove {number=} - The number of lat, lng, alt values to remove + * @param opt_latLngAlts {Array=} - The lat, lng, alt values to add + * @returns {Array} - an array of removed elements + */ + spliceLatLngAlts(index: number, opt_nRemove?: number, opt_latLngAlts?: Array): Array; + + /** + * This method inserts one set of lat, lng, alt values into the strip at the specified index. + * @param index {number} - the index at which to add the element + * @param lat {H.geo.Latitude} - the latitude to insert + * @param lng {H.geo.Longitude} - the longitude to insert + * @param alt {H.geo.Altitude} - the altitude to insert + */ + insertLatLngAlt(index: number, lat: H.geo.Latitude, lng: H.geo.Longitude, alt: H.geo.Altitude): void; + + /** + * This method removes one set of lat, lng, alt values from the strip at the specified index. + * @param index {number} + */ + removeLatLngAlt(index: number): void; + + /** + * This method pushes the lat, lng, alt values of a H.geo.Point to the end of this strip. + * @param geoPoint {H.geo.IPoint} + */ + pushPoint(geoPoint: H.geo.IPoint): void; + + /** + * This method inserts the lat, lng, alt values of a H.geo.Point into the list at the specified index. + * @param pointIndex {number} + * @param geoPoint {H.geo.IPoint} + */ + insertPoint(pointIndex: number, geoPoint: H.geo.IPoint): void; + + /** + * This method removes one set of lat, lng, alt values from this strip at the virtual point index specified. + * @param pointIndex {number} - the virtual point index + */ + removePoint(pointIndex: number): void; + + /** + * This method extracts a H.geo.Point from this strip at the virtual point index. If the extracted point has an alt value, the strip's altitude context will be supplied to the point. + * @param pointIndex {number} - the virtual point index in the strip + * @param opt_out {H.geo.Point=} - an optional point object to store the lat, lng, alt values + * @returns {H.geo.Point} - returns either the 'opt_out' point object or a new point object. + */ + extractPoint(pointIndex: number, opt_out?: H.geo.Point): H.geo.Point; + + /** + * This method is a utility method that iterates over the lat, lng, alt array and calls the provided function for each 3 elements passing lat, lng and alt and the virtual point index as arguments. + * @param eachFn {function(H.geo.Latitude, H.geo.Longitude, H.geo.Altitude, number)} - the function to be called for each 3 elements + * @param opt_start {number=} - an optional start index to iterate from + * @param opt_end {number=} - an optional end index to iterate to + */ + eachLatLngAlt(eachFn: (lat: H.geo.Latitude, lng: H.geo.Longitude, alt: H.geo.Altitude, n: number) => void, opt_start?: number, opt_end?: number): void; + + /** + * This method returns the number of times that legs in this strip cross the date border. + * @param opt_closed {boolean=} - indicates whether the strip is closed (i.e. whether the strip's last and first coordinates form the closing leg of a polygon) + * @returns {number} - the amount of times this strip crosses the date border. + */ + getDBCs(opt_closed?: boolean): number; + + /** + * This method return the number of points stored in this strip. + * @returns {number} - the number of points in this strip + */ + getPointCount(): number; + + /** + * This method returns the internal array keeping the lat, lng, alt values. Modifying this array directly can destroy the integrity of this strip. Use it only for read access. + * @returns {Array} - returns the raw lat, lng, alt values of this strip + */ + getLatLngAltArray(): Array; + + /** + * This method returns the bounding box of this strip. + * @returns {?H.geo.Rect} - this strip's bounding rectangle + */ + getBounds(): H.geo.Rect; + + /** + * This method checks whether two longitudes form a leg which crosses the date border. + * @param lng1 {H.geo.Longitude} - the start longitude of the leg + * @param lng2 {H.geo.Longitude} - the end longitude of the leg + * @returns {boolean} - true if the leg crosses the date border, otherwise false + */ + static isDBC(lng1: H.geo.Longitude, lng2: H.geo.Longitude): boolean; + + /** + * This method initializes a new strip with an array of lat, lng values. Arrays are expected to have an even length with the format [lat, lng, lat, lng, ...]. + * @param latLngs {Array} - the array of lat, lng value. + * @returns {H.geo.Strip} - the strip containing the lat, lng values + */ + static fromLatLngArray(latLngs: Array): H.geo.Strip; + } } /***** lang *****/ @@ -1173,6 +1292,78 @@ declare namespace H { } } + /** + * A Polygon with a circular shape. + */ + export class Circle extends H.map.Polygon { + /** + * Constructor + * @param center {H.geo.IPoint} - The geographical coordinates of the circle's center + * @param radius {number} - The radius of the circle in meters + * @param opt_options {H.map.Circle.Options=} - An object that specifies circle options and their initial values (among these, precision has a significant impact on the shape of the circle - please see + */ + constructor(center: H.geo.IPoint, radius: number, opt_options?: H.map.Circle.Options); + + /** + * To set the geographical center point of this circle. If the specified center is an instance of H.geo.Point you must not modify this Point instance without calling setCenter immediately afterwards. + * @param center {H.geo.IPoint} + */ + setCenter(center: H.geo.IPoint): void; + + /** + * To get the center point of this circle You must not modify the returned Point instance without calling setCenter immediately afterwards. + * @returns {H.geo.Point} + */ + getCenter(): H.geo.Point; + + /** + * To set the length of the radius of the circle in meters. The value is clamped to the of {@code[0 ... 20015089.27787877]} (half WGS84 mean circumference) + * @param radius {number} + */ + setRadius(radius: number): void; + + /** + * To get the length of the radius of the circle in meters. + * @returns {number} + */ + getRadius(): number; + + /** + * To set the precision of this circle {@see H.map.Circle.Options#precision} + * @param precision {number} + */ + setPrecision(precision: number): void; + + /** + * To get the precision value of this circle + * @returns {number} + */ + getPrecision(): number; + } + + export module Circle { + /** + * @property style {H.map.SpatialStyle=} - the style to be used when tracing the polyline + * @property visibility {boolean=} - An optional boolean value indicating whether this map object is visible, default is true + * @property precision {number=} - The precision of a circle as a number of segments to be used when rendering the circle. The value is clamped to the range between [4 ... 360], where 60 is the default. Note that the lower the value the more angular and the less circle-like the shape appears and, conversely, the higher the value the smoother and more rounded the result. Thus, starting at the extreme low end of the possible values, 4 produces a square, 6 a hexagon, while 30 results in a circle-like shape, although it appears increasingly angular as the zoom level increases (as you zoom in), and finally 360 produces a smooth circle. + * @property zIndex {number=} - The z-index value of the circle, default is 0 + * @property min {number=} - The minimum zoom level for which the circle is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the circle is visible, default is Infinity + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData + */ + export interface Options { + style?: H.map.SpatialStyle | H.map.SpatialStyle.Options; + visibility?: boolean; + precision?: number; + zIndex?: number; + min?: number; + max?: number; + provider?: H.map.provider.Provider; + data?: any; + } + } + /** * The class represents data model of the map. It holds list of layers that are rendered by map's RenderEngine. The class listens to 'update' events from layers and dispatches them to the RenderEngine. */ @@ -1242,6 +1433,38 @@ declare namespace H { } } + /** + * This class represents a spatial shape in geographic space. It is defined by a path containing the vertices of the shape (lat, lng, alt values). + */ + export class GeoShape extends H.map.Spatial { + /** + * Constructor + * @param isClosed {boolean} - Indicates whether this geographical shape is closed (a polygon) + * @param strip {H.geo.Strip} - The strip describing the shape of the spatial object + * @param options {H.map.Spatial.Options} - The options to apply + */ + constructor(isClosed: boolean, strip: H.geo.Strip, options: H.map.Spatial.Options); + + /** + * This method returns the strip which represents the shape of the spatial object. + * @returns {H.geo.Strip} - the strip + */ + getStrip(): H.geo.Strip; + + /** + * This method sets the geo-information for the spatial object + * @param strip {?H.geo.Strip} - The strip which represents the shape of the spatial object. + * @returns {H.map.GeoShape} - the Spatial instance itself + */ + setStrip(strip: H.geo.Strip): H.map.GeoShape; + + /** + * This method returns the bounding rectangle for this object. The rectangle is the smallest rectangle which encloses all points of the spatial object. + * @returns {H.geo.Rect} + */ + getBounds(): H.geo.Rect; + } + /** * This class represents a map object which can contain other map objects. It's visibility, zIndex and object-order influences the contained map objects */ @@ -1855,6 +2078,92 @@ declare namespace H { } } + /** + * This class represents a polygon in geo-space. It is defined by a strip containing the vertices of a geo shape object (lat, lng, alt values) and a pen to use when rendering the polyline. Polygon represents a closed plane defined by the list of verticies, projected on the map display. List of vericies which define the polygon are is a list of geo coordinates encapsulated by the strip object H.geo.Strip + */ + export class Polygon extends H.map.GeoShape { + /** + * Constructor + * @param strip {H.geo.Strip} - the strip describing this polygon's vertices + * @param opt_options {H.map.Spatial.Options=} - optional initialization parameters + */ + constructor(strip: H.geo.Strip, opt_options?: H.map.Spatial.Options); + + /** + * To set the indicator whether this polygon covers the north pole. It's needed for Polygons whose strip is defined as lines arround the world on longitude axis (for example a circle whose center is one of the poles). In this case a additional information is needed to know if the southern or northern part of the world should be covered by the poygon. + * @param flag {boolean} - A value of true means it covers the north pole, false means south pole + * @returns {H.map.Polygon} - the Polygon instance itself + */ + setNorthPoleCovering(flag: boolean): H.map.Polygon; + + /** + * See H.map.Polygon#setNorthPoleCovering + * @returns {boolean} + */ + getNorthPoleCovering(): boolean; + } + + /** + * This class represents a polyline in geo-space. It is defined by a path containing the vertices of a polyline (lat, lng, alt values) and a pen to use when tracing the path on the map. + */ + export class Polyline extends H.map.GeoShape { + /** + * Constructor + * @param strip {H.geo.Strip} - the strip describing this polygon's vertices + * @param opt_options {H.map.Polyline.Options=} - optional initialization parameters + */ + constructor(strip: H.geo.Strip, opt_options?: H.map.Polyline.Options); + + /** + * This method clips this polyline against a rectangular area and returns the intersecting sub-lines. + * @param geoRect {H.geo.Rect} + * @returns {Array>} + */ + clip(geoRect: H.geo.Rect): Array>; + } + + export module Polyline { + /** + * Options which are used to initialize a polyline + * @property style {(H.map.SpatialStyle | H.map.SpatialStyle.Options)=} - the style to be used when tracing the polyline + * @property arrows {(H.map.ArrowStyle | H.map.ArrowStyle.Options)=} - The arrows style to be used when rendering the polyline. + * @property visibility {boolean=} - An optional boolean value indicating whether this map object is visible, default is true + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData + */ + export interface Options { + style?: (H.map.SpatialStyle | H.map.SpatialStyle.Options); + arrows?: (H.map.ArrowStyle | H.map.ArrowStyle.Options); + visibility?: boolean; + zIndex?: number; + min?: number; + max?: number; + provider?: H.map.provider.Provider; + data?: any; + } + } + + /** + * A Polygon with a rectangular shape. + */ + export class Rect extends H.map.Polygon { + /** + * Constructor + * @param bounds {H.geo.Rect} - The geographical bounding box for this rectangle + * @param opt_options {H.map.Spatial.Options=} + */ + constructor(bounds: H.geo.Rect, opt_options?: H.map.Spatial.Options); + + /** + * To set the bounds of this rectangle. + * @param bounds {H.geo.Rect} + */ + setBounds(bounds: H.geo.Rect): void; + } + /** * This class represents a spatial map object which provides its projected geometry. */ @@ -1985,8 +2294,8 @@ declare namespace H { miterLimit: number; lineDash: Array; lineDashOffset: number; - MAX_LINE_WIDTH: number; - DEFAULT_STYLE: H.map.SpatialStyle; + static MAX_LINE_WIDTH: number; + static DEFAULT_STYLE: H.map.SpatialStyle; } export module SpatialStyle { @@ -2018,7 +2327,7 @@ declare namespace H { lineCap?: H.map.SpatialStyle.LineCap; lineJoin?: H.map.SpatialStyle.LineJoin; miterLimit?: number; - lineDash: Array; + lineDash?: Array; lineDashOffset?: number; } } diff --git a/jest/jest.d.ts b/jest/jest.d.ts index 10949a6691..b2484dfcc5 100644 --- a/jest/jest.d.ts +++ b/jest/jest.d.ts @@ -44,6 +44,7 @@ declare namespace jest { interface Matchers { not: Matchers; toThrow(expected?: any): boolean; + toThrowError(expected?: any): boolean; toBe(expected: any): boolean; toEqual(expected: any): boolean; toBeFalsy(): boolean; diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index 6321cff0a5..f0e9fe023f 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -61,8 +61,10 @@ interface KnockoutSubscription { } interface KnockoutSubscribable extends KnockoutSubscribableFunctions { - subscribe(callback: (newValue: T) => void, target?: any, event?: string): KnockoutSubscription; + subscribe(callback: (newValue: T) => void, target: any, event: "beforeChange"): KnockoutSubscription; + subscribe(callback: (newValue: T) => void, target?: any, event?: "change"): KnockoutSubscription; subscribe(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription; + extend(requestedExtenders: { [key: string]: any; }): KnockoutSubscribable; getSubscriptionsCount(): number; } @@ -91,6 +93,11 @@ interface KnockoutObservableArrayStatic { } interface KnockoutObservableArray extends KnockoutObservable, KnockoutObservableArrayFunctions { + subscribe(callback: (newValue: KnockoutArrayChange[]) => void, target: any, event: "arrayChange"): KnockoutSubscription; + subscribe(callback: (newValue: T[]) => void, target: any, event: "beforeChange"): KnockoutSubscription; + subscribe(callback: (newValue: T[]) => void, target?: any, event?: "change"): KnockoutSubscription; + subscribe(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription; + extend(requestedExtenders: { [key: string]: any; }): KnockoutObservableArray; } @@ -325,7 +332,7 @@ interface KnockoutUtils { } interface KnockoutArrayChange { - status: string; + status: "added" | "deleted"; value: T; index: number; moved?: number; diff --git a/knockout/knockoutamd-tests.ts b/knockout/knockoutamd-tests.ts index c874c6208b..9ee6658335 100644 --- a/knockout/knockoutamd-tests.ts +++ b/knockout/knockoutamd-tests.ts @@ -1,6 +1,6 @@ /// -import ko = require("knockout"); +import ko = require("knockout"); var myArray = ko.observableArray([1, 2, 3]); diff --git a/knockout/tests/knockout-tests.ts b/knockout/tests/knockout-tests.ts index 8da6c12950..122617b180 100644 --- a/knockout/tests/knockout-tests.ts +++ b/knockout/tests/knockout-tests.ts @@ -680,3 +680,38 @@ function test_tasks() { setTimeout(callback, 0); }; } + +function observableEventsTests() { + var observable = ko.observable(1); + observable.subscribe(value => { + var num: number = value; + }); + observable.subscribe(value => { + var num: number = value; + }, null, "change"); + observable.subscribe(value => { + var num: number = value; + }, null, "beforeChange"); +} + +function observableArrayEventsTests() { + var observableArray = ko.observableArray([1, 2, 3, 4]); + observableArray.subscribe(array => { + var arr: number[] = array; + }); + observableArray.subscribe(array => { + var arr: number[] = array; + }, null, "change"); + observableArray.subscribe(array => { + var arr: number[] = array; + }, null, "beforeChange"); + var count = 0; + observableArray.subscribe(changes => { + changes.forEach(change => { + if (change.status == "added") + count++; + else if (change.status == "deleted") + count--; + }); + }, null, "arrayChange"); +} \ No newline at end of file diff --git a/leaflet-curve/leaflet-curve-tests.ts b/leaflet-curve/leaflet-curve-tests.ts index 2c5bb6b8f1..9864e71252 100644 --- a/leaflet-curve/leaflet-curve-tests.ts +++ b/leaflet-curve/leaflet-curve-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// diff --git a/leaflet-curve/leaflet-curve.d.ts b/leaflet-curve/leaflet-curve.d.ts index 32358c08ac..7bd64215b9 100644 --- a/leaflet-curve/leaflet-curve.d.ts +++ b/leaflet-curve/leaflet-curve.d.ts @@ -3,7 +3,7 @@ // Definitions by: Onikiienko // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace L { /** diff --git a/leaflet-draw/leaflet-draw-tests.ts b/leaflet-draw/leaflet-draw-tests.ts index 9a1ed09306..396f5119d3 100644 --- a/leaflet-draw/leaflet-draw-tests.ts +++ b/leaflet-draw/leaflet-draw-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// @@ -44,4 +44,4 @@ map.on('draw:created', function (e: L.DrawEvents.Created) { layer = e.layer; drawnItems.addLayer(layer); -}); \ No newline at end of file +}); diff --git a/leaflet-draw/leaflet-draw.d.ts b/leaflet-draw/leaflet-draw.d.ts index 253d6c3a11..7c80f17ef2 100644 --- a/leaflet-draw/leaflet-draw.d.ts +++ b/leaflet-draw/leaflet-draw.d.ts @@ -3,7 +3,7 @@ // Definitions by: Matt Guest // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace L { export interface MapOptions { diff --git a/leaflet-editable/leaflet-editable.d.ts b/leaflet-editable/leaflet-editable.d.ts index 0d7b2bcc0f..f559917b62 100644 --- a/leaflet-editable/leaflet-editable.d.ts +++ b/leaflet-editable/leaflet-editable.d.ts @@ -3,7 +3,7 @@ // Definitions by: Dominic Alie // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace L { /** diff --git a/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen-tests.ts b/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen-tests.ts index c6519ab371..d623120a73 100644 --- a/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen-tests.ts +++ b/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', diff --git a/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen.d.ts b/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen.d.ts index 8809472e43..3e388ff515 100644 --- a/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen.d.ts +++ b/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace L { namespace Control { diff --git a/leaflet-label/leaflet-label.d.ts b/leaflet-label/leaflet-label.d.ts index 009ded17f8..ea18df3cea 100644 --- a/leaflet-label/leaflet-label.d.ts +++ b/leaflet-label/leaflet-label.d.ts @@ -3,7 +3,7 @@ // Definitions by: Wim Looman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace L { export interface IconOptions { diff --git a/leaflet-markercluster/leaflet-markercluster.d.ts b/leaflet-markercluster/leaflet-markercluster.d.ts index 7d8757be03..b756389275 100644 --- a/leaflet-markercluster/leaflet-markercluster.d.ts +++ b/leaflet-markercluster/leaflet-markercluster.d.ts @@ -3,7 +3,7 @@ // Definitions by: Robert Imig // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace L { export interface MarkerClusterGroupOptions { @@ -51,7 +51,7 @@ declare namespace L { /* * The maximum radius that a cluster will cover from the central marker (in pixels). Default 80. - * Decreasing will make more, smaller clusters. You can also use a function that accepts + * Decreasing will make more, smaller clusters. You can also use a function that accepts * the current map zoom and returns the maximum cluster radius in pixels */ maxClusterRadius?: number | ((zoom: number) => number); @@ -134,9 +134,9 @@ declare namespace L { getAllChildMarkers(): Marker[]; /* - * Zooms to show the given marker (spiderfying if required), + * Zooms to show the given marker (spiderfying if required), * calls the callback when the marker is visible on the map. - */ + */ zoomToShowLayer(layer: any, callback: () => void): void; } } diff --git a/leaflet.awesome-markers/leaflet.awesome-markers.d.ts b/leaflet.awesome-markers/leaflet.awesome-markers.d.ts index 6fa754ad8d..4364743d48 100644 --- a/leaflet.awesome-markers/leaflet.awesome-markers.d.ts +++ b/leaflet.awesome-markers/leaflet.awesome-markers.d.ts @@ -3,7 +3,7 @@ // Definitions by: Egor Komarov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module L { module AwesomeMarkers { diff --git a/leaflet.fullscreen/leaflet.fullscreen.d.ts b/leaflet.fullscreen/leaflet.fullscreen.d.ts index b8be6604dc..f094c307dc 100644 --- a/leaflet.fullscreen/leaflet.fullscreen.d.ts +++ b/leaflet.fullscreen/leaflet.fullscreen.d.ts @@ -3,7 +3,7 @@ // Definitions by: William Comartin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace L { diff --git a/leaflet/leaflet-0.7-tests.ts b/leaflet/leaflet-0.7-tests.ts new file mode 100644 index 0000000000..1a88096002 --- /dev/null +++ b/leaflet/leaflet-0.7-tests.ts @@ -0,0 +1,427 @@ +/// + +// initialize the map on the "map" div with a given center and zoom + +var div = document.getElementById('map'); + +var map : L.Map = L.map(div, { + center: L.latLng([51.505, -0.09]), + zoom: 13, + minZoom: 3, + maxZoom: 8, + maxBounds: L.latLngBounds([L.latLng(-60, -60), L.latLng(60, 60)]), + dragging: true, + touchZoom: true, + scrollWheelZoom: true, + boxZoom: true, + tap: true, + + tapTolerance: 30, + trackResize: true, + worldCopyJump: false, + closePopupOnClick: true, + bounceAtZoomLimits: true, + + keyboard: true, + keyboardPanOffset: 80, + keyboardZoomOffset: 1, + + inertia: true, + inertiaDeceleration: 3000, + inertiaMaxSpeed: 1500, + inertiaThreshold: 32, + + zoomControl: true, + attributionControl: true, + + fadeAnimation: true, + zoomAnimation: true, + zoomAnimationThreshold: 4, + markerZoomAnimation: true + +}); + +map.dragging.enable(); +map.touchZoom.enable(); +map.scrollWheelZoom.enable(); +map.doubleClickZoom.enable(); +map.boxZoom.enable(); +map.tap.enable(); + +map.setView(new L.LatLng(42, 51)); +map.setView(L.latLng(42, 51)); + +map.setView(L.latLng(42, 51), 12); +map.setView(L.latLng(42, 51), 12, { + reset: true, + pan: { + animate: true, + duration: 0.25, + easeLinearity: 0.25, + noMoveStart: false + }, + zoom: { + animate: true + } +}); + +map.setZoom(50); +map.setZoom(50, {}); + +map.zoomIn(); +map.zoomOut(); + +map.zoomIn(2); +map.zoomOut(2); + +map.zoomIn(2, { animate: true }); +map.zoomOut(2, { animate: true }); + +map.setZoomAround(L.latLng(42, 51), 8, { animate: false }); + +map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20))); +map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20)), { + paddingTopLeft: L.point(20, 20), + paddingBottomRight: L.point(20, 20), + padding: L.point(0, 0), + maxZoom: null +}); + +map.fitWorld(); + +map.fitWorld({ + animate: false +}); + +map.panTo(L.latLng(42, 42)); +map.panTo(L.latLng(42, 42), { + animate: true +}); + +map.invalidateSize(true); +map.invalidateSize({ reset: true }); + +map.setMaxBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20))); + +map.locate(); +map.locate({ + watch: false, + setView: false, + maxZoom: 18, + timeout: 10000, + maximumAge: 0, + enableHighAccuracy: false +}); + +map.stopLocate(); + +map.remove(); + +var center : L.LatLng = map.getCenter(); +var zoom : number = map.getZoom(); +var minZoom: number = map.getMinZoom(); +var maxZoom: number = map.getMaxZoom(); +var bounds: L.LatLngBounds = map.getBounds(); +var boundsZoom: number = map.getBoundsZoom(bounds, true); +var size: L.Point = map.getSize(); +var pixelBounds: L.Bounds = map.getPixelBounds(); +var pixelOrigin: L.Point = map.getPixelOrigin(); + +var layer = L.tileLayer("http://{s}.example.net/{x}/{y}/{z}.png"); + +map.addLayer(layer); +map.addLayer(layer, false); +map.eachLayer(l => {}); + +map.removeLayer(layer); +map.hasLayer(layer); + +map.openPopup("canard", L.latLng(42, 51)); + +var popup = L.popup({ + autoPan: true +}); + +map.openPopup(popup); +map.closePopup(popup); +map.closePopup(); + +map.addControl(L.control.attribution({position: 'bottomright'})); +map.removeControl(L.control.attribution({ position: 'bottomright' })); + +L.control.layers({'Base': layer}).addTo(map); +map.on('baseLayerChange', function(e: L.LeafletLayersControlEvent) { + alert(e.name); +}); + +map.latLngToLayerPoint(map.layerPointToLatLng(L.point(0, 0))); +map.latLngToContainerPoint(map.containerPointToLatLng(L.point(0, 0))); +map.containerPointToLayerPoint(L.point(0, 0)); +map.layerPointToContainerPoint(L.point(0, 0)); + +map.project(map.unproject(L.point(10, 20))); +map.project(map.unproject(L.point(10, 20), 12), 12); + +var mouseEvent: L.LeafletMouseEvent; +map.mouseEventToContainerPoint(mouseEvent); +map.mouseEventToLayerPoint(mouseEvent); +map.mouseEventToLatLng(mouseEvent); + +map.getContainer().classList.add('roger'); +map.getPanes().mapPane.classList.add('roger'); +map.getPanes().markerPane.classList.add('roger'); +map.getPanes().objectsPane.classList.add('roger'); +map.getPanes().overlayPane.classList.add('roger'); +map.getPanes().popupPane.classList.add('roger'); +map.getPanes().shadowPane.classList.add('roger'); +map.getPanes().tilePane.classList.add('roger'); + +map.whenReady((m: L.Map) => { + m.zoomOut(); +}); + +map.on('click', () => { + map.zoomOut(); +}); + +map.off('dblclick', L.Util.falseFn); + +map.once('contextmenu', (e: L.LeafletMouseEvent) => { + map.openPopup('contextmenu', e.latlng); +}); + +var marker = L.marker(L.latLng(42, 51), { + icon: L.icon({ + iconUrl: 'roger.png', + iconRetinaUrl: 'roger-retina.png', + iconSize: L.point(40, 40), + iconAnchor: L.point(20, 0), + shadowUrl: 'roger-shadow.png', + shadowRetinaUrl: 'roger-shadow-retina.png', + shadowSize: L.point(44, 44), + shadowAnchor: L.point(22, 0), + popupAnchor: L.point(0, 0), + className: 'roger-icon' + }), + clickable: true, + draggable: false, + keyboard: true, + title: 'this is an icon', + alt: '', + zIndexOffset: 0, + opacity: 1.0, + riseOnHover: false, + riseOffset: 250 +}); + +marker.addTo(map); + +marker.on('click', (e: L.LeafletMouseEvent) => { + map.setView(e.latlng); +}); + +marker.once('mouseover', () => { + marker.openPopup(); +}) + +marker.setLatLng(marker.getLatLng()); + +marker.setIcon(L.icon({})); + +marker.setZIndexOffset(30); +marker.setOpacity(0.8); + +marker.bindPopup(popup); +marker.unbindPopup(); +marker.bindPopup('hello', { + closeOnClick: true +}); + +marker.openPopup(); +marker.closePopup(); +marker.togglePopup(); +marker.togglePopup(); +marker.setPopupContent('hello 3') +marker.getPopup().setContent('hello 2'); +marker.update(); + +marker.toGeoJSON(); + +marker.dragging.enable(); + +popup = L.popup({ + maxWidth: 300, + minWidth: 50, + maxHeight: null, + autoPan: true, + keepInView: false, + closeButton: true, + offset: L.point(0, 6), + autoPanPaddingTopLeft: null, + autoPanPaddingBottomRight: L.point(20, 20), + autoPanPadding: L.point(5, 5), + zoomAnimation: true, + closeOnClick: null, + className: 'roger' +}); + +popup.setLatLng(L.latLng(12, 54)).setContent('this is nice popup').openOn(map); + +popup.update(); + +var tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}', { + minZoom: 0, + maxZoom: 18, + maxNativeZoom: 17, + tileSize: 256, + subdomains: ['a','b','c'], + errorTileUrl: '', + attribution: '', + tms: false, + continuousWorld: false, + noWrap: false, + zoomOffset: 0, + zoomReverse: false, + opacity: 1.0, + zIndex: null, + unloadInvisibleTiles: false, + updateWhenIdle: false, + detectRetina: true, + reuseTiles: true, + bounds: null +}); + +tileLayer.on('loading', L.Util.falseFn) + .off('loading', L.Util.falseFn) + .once('tileload', L.Util.falseFn); + +tileLayer.addTo(map); + +tileLayer.bringToBack() + .bringToFront() + .setOpacity(0.7) + .setZIndex(9) + .redraw() + .setUrl('http://perdu.com') + .getContainer(); + +namespace CustomControl { + export interface Options { + title: string; + position?: string; + } +} +interface CustomControl extends L.Control { + getTitle(): string; + setTitle(title: string): CustomControl; +} +var CustomControl: { new(options: CustomControl.Options): CustomControl }; +CustomControl = L.Control.extend({ + initialize: function(options: CustomControl.Options) { + L.Control.prototype.initialize.call(this, { + position: options.position || 'bottomleft', + }); + this.title = options.title; + }, + getTitle: function() { + return this.title; + }, + setTitle: function(title: string) { + this.title = title; + }, +}); + +// Different latLng and latLngBounds expressions +var latLngLiteral = [10, 20]; +var latLngObjectLiteral = { lat: 10, lng: 10 }; +var boundsLiteral = [[10, 20], [20, 20]]; +var boundLiteralOfLatLngObjects = [latLngObjectLiteral, latLngObjectLiteral]; + +var circle: L.Circle = L.circle(latLngLiteral, 4); +circle = new L.Circle(latLngLiteral, 4); +circle.setLatLng(latLngLiteral); + +circle = L.circle(latLngObjectLiteral, 4); +circle = new L.Circle(latLngObjectLiteral, 4); +circle.setLatLng(latLngObjectLiteral); + +var circleMarker: L.CircleMarker = L.circleMarker(latLngLiteral); +circleMarker = new L.CircleMarker(latLngLiteral); +circleMarker.setLatLng(latLngLiteral); + +circleMarker = L.circleMarker(latLngObjectLiteral); +circleMarker = new L.CircleMarker(latLngObjectLiteral); +circleMarker.setLatLng(latLngObjectLiteral); + +var latLng: L.LatLng = L.latLng(latLngLiteral); +latLng = new L.LatLng(latLngLiteral); +latLng.distanceTo(latLngLiteral); +latLng.equals(latLngLiteral); + +latLng = L.latLng(latLngObjectLiteral); +latLng = new L.LatLng(latLngObjectLiteral); +latLng.distanceTo(latLngObjectLiteral); +latLng.equals(latLngObjectLiteral); + +var bounds: L.LatLngBounds = L.latLngBounds(boundsLiteral); +bounds = L.latLngBounds(boundLiteralOfLatLngObjects); +bounds = new L.LatLngBounds(boundsLiteral); +bounds = new L.LatLngBounds(boundLiteralOfLatLngObjects); +bounds = new L.LatLngBounds(latLngLiteral, latLngLiteral); + +bounds.extend(latLngLiteral); +bounds.extend(latLngObjectLiteral); +bounds.extend(boundsLiteral); +bounds.extend(boundLiteralOfLatLngObjects); + +bounds.contains(latLngLiteral); +bounds.contains(boundLiteralOfLatLngObjects); +bounds.contains(boundsLiteral); + +bounds.intersects(boundsLiteral); +bounds.intersects(boundLiteralOfLatLngObjects); + +bounds.equals(boundsLiteral); +bounds.equals(boundLiteralOfLatLngObjects); + +map.setView(latLngLiteral); +map.setView(latLngObjectLiteral); +map.setZoomAround(latLngLiteral, 15); +map.setZoomAround(latLngObjectLiteral, 15); +map.panTo(latLngLiteral); +map.panTo(latLngObjectLiteral); +map.openPopup('test', latLngLiteral); +map.openPopup('test', latLngObjectLiteral); +map.latLngToLayerPoint(latLngLiteral); +map.latLngToLayerPoint(latLngObjectLiteral); +map.latLngToContainerPoint(latLngLiteral); +map.latLngToContainerPoint(latLngObjectLiteral); +map.project(latLngLiteral); +map.project(latLngObjectLiteral); + +marker.setLatLng(latLngLiteral); +marker.setLatLng(latLngObjectLiteral); + +var polygon: L.Polygon = L.polygon(boundsLiteral); +polygon = L.polygon(boundLiteralOfLatLngObjects); +polygon = new L.Polygon(boundsLiteral); +polygon = new L.Polygon(boundLiteralOfLatLngObjects); + +var polyline: L.Polyline = L.polyline(boundsLiteral); +polyline = L.polyline(boundLiteralOfLatLngObjects); +polyline = new L.Polyline(boundsLiteral); +polyline = new L.Polyline(boundLiteralOfLatLngObjects); +polyline.setLatLngs(boundsLiteral); +polyline.setLatLngs(boundLiteralOfLatLngObjects); +polyline.addLatLng(latLngLiteral); +polyline.addLatLng(latLngObjectLiteral); + +var popup: L.Popup = L.popup(); +popup.setLatLng(latLngLiteral); +popup.setLatLng(latLngObjectLiteral); + +var zoomCtrl = L.control.zoom({ + position: "topleft", + zoomInText: '+', + zoomOutText: '-' +}); diff --git a/leaflet/leaflet-0.7.d.ts b/leaflet/leaflet-0.7.d.ts new file mode 100644 index 0000000000..0c4bca15a6 --- /dev/null +++ b/leaflet/leaflet-0.7.d.ts @@ -0,0 +1,4382 @@ +// Type definitions for Leaflet.js 0.7.x +// Project: https://github.com/Leaflet/Leaflet +// Definitions by: Vladimir Zotov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace L { + type LatLngExpression = LatLng | number[] | ({ lat: number; lng: number }) + type LatLngBoundsExpression = LatLngBounds | LatLngExpression[]; + type PositionString = 'topleft' | 'topright' | 'bottomleft' | 'bottomright'; +} + +declare namespace L { + + export interface AttributionOptions { + + /** + * The position of the control (one of the map corners). See control positions. + * Default value: 'bottomright'. + */ + position?: PositionString; + + /** + * The HTML text shown before the attributions. Pass false to disable. + * Default value: 'Powered by Leaflet'. + */ + prefix?: string; + + } +} + +declare namespace L { + + /** + * Creates a Bounds object from two coordinates (usually top-left and bottom-right + * corners). + */ + export function bounds(topLeft: Point, bottomRight: Point): Bounds; + + /** + * Creates a Bounds object defined by the points it contains. + */ + export function bounds(points: Point[]): Bounds; + + + export interface BoundsStatic { + /** + * Creates a Bounds object from two coordinates (usually top-left and bottom-right + * corners). + */ + new(topLeft: Point, bottomRight: Point): Bounds; + + /** + * Creates a Bounds object defined by the points it contains. + */ + new(points: Point[]): Bounds; + } + export var Bounds: BoundsStatic; + + export interface Bounds { + /** + * Extends the bounds to contain the given point. + */ + extend(point: Point): void; + + /** + * Returns the center point of the bounds. + */ + getCenter(): Point; + + /** + * Returns true if the rectangle contains the given one. + */ + contains(otherBounds: Bounds): boolean; + + /** + * Returns true if the rectangle contains the given point. + */ + contains(point: Point): boolean; + + /** + * Returns true if the rectangle intersects the given bounds. + */ + intersects(otherBounds: Bounds): boolean; + + /** + * Returns true if the bounds are properly initialized. + */ + isValid(): boolean; + + /** + * Returns the size of the given bounds. + */ + getSize(): Point; + + /** + * The top left corner of the rectangle. + */ + min: Point; + + /** + * The bottom right corner of the rectangle. + */ + max: Point; + } +} + +declare namespace L { + + namespace Browser { + + /** + * true for all Internet Explorer versions. + */ + export var ie: boolean; + + /** + * true for Internet Explorer 6. + */ + export var ie6: boolean; + + /** + * true for Internet Explorer 6. + */ + export var ie7: boolean; + + /** + * true for webkit-based browsers like Chrome and Safari (including mobile + * versions). + */ + export var webkit: boolean; + + /** + * true for webkit-based browsers that support CSS 3D transformations. + */ + export var webkit3d: boolean; + + /** + * true for Android mobile browser. + */ + export var android: boolean; + + /** + * true for old Android stock browsers (2 and 3). + */ + export var android23: boolean; + + /** + * true for modern mobile browsers (including iOS Safari and different Android + * browsers). + */ + export var mobile: boolean; + + /** + * true for mobile webkit-based browsers. + */ + export var mobileWebkit: boolean; + + /** + * true for mobile Opera. + */ + export var mobileOpera: boolean; + + /** + * true for all browsers on touch devices. + */ + export var touch: boolean; + + /** + * true for browsers with Microsoft touch model (e.g. IE10). + */ + export var msTouch: boolean; + + /** + * true for devices with Retina screens. + */ + export var retina: boolean; + + } +} + + +declare namespace L { + + /** + * Instantiates a circle object given a geographical point, a radius in meters + * and optionally an options object. + */ + function circle(latlng: LatLngExpression, radius: number, options?: PathOptions): Circle; + + export interface CircleStatic extends ClassStatic { + /** + * Instantiates a circle object given a geographical point, a radius in meters + * and optionally an options object. + */ + new(latlng: LatLngExpression, radius: number, options?: PathOptions): Circle; + } + export var Circle: CircleStatic; + + export interface Circle extends Path { + /** + * Returns the current geographical position of the circle. + */ + getLatLng(): LatLng; + + /** + * Returns the current radius of a circle. Units are in meters. + */ + getRadius(): number; + + /** + * Sets the position of a circle to a new location. + */ + setLatLng(latlng: LatLngExpression): Circle; + + /** + * Sets the radius of a circle. Units are in meters. + */ + setRadius(radius: number): Circle; + + /** + * Returns a GeoJSON representation of the circle (GeoJSON Point Feature). + */ + toGeoJSON(): GeoJSON.Feature; + + } +} + +declare namespace L { + + /** + * Instantiates a circle marker given a geographical point and optionally + * an options object. The default radius is 10 and can be altered by passing a + * "radius" member in the path options object. + */ + function circleMarker(latlng: LatLngExpression, options?: PathOptions): CircleMarker; + + + export interface CircleMarkerStatic extends ClassStatic { + /** + * Instantiates a circle marker given a geographical point and optionally + * an options object. The default radius is 10 and can be altered by passing a + * "radius" member in the path options object. + */ + new(latlng: LatLngExpression, options?: PathOptions): CircleMarker; + } + export var CircleMarker: CircleMarkerStatic; + + export interface CircleMarker extends Circle { + /** + * Sets the position of a circle marker to a new location. + */ + setLatLng(latlng: LatLngExpression): CircleMarker; + + /** + * Sets the radius of a circle marker. Units are in pixels. + */ + setRadius(radius: number): CircleMarker; + } +} + +declare namespace L { + export interface ClassExtendOptions { + /** + * Your class's constructor function, meaning that it gets called when you do 'new MyClass(...)'. + */ + initialize?: Function; + + /** + * options is a special property that unlike other objects that you pass + * to extend will be merged with the parent one instead of overriding it + * completely, which makes managing configuration of objects and default + * values convenient. + */ + options?: any; + + /** + * includes is a special class property that merges all specified objects + * into the class (such objects are called mixins). A good example of this + * is L.Mixin.Events that event-related methods like on, off and fire + * to the class. + */ + includes?: any; + + /** + * statics is just a convenience property that injects specified object + * properties as the static properties of the class, useful for defining + * constants. + */ + static?: any; + + [prop: string]: any; + } + + export interface ClassStatic { + /** + * You use L.Class.extend to define new classes, but you can use the + * same method on any class to inherit from it. + */ + extend(options: ClassExtendOptions): any; + extend(options: ClassExtendOptions): { new(options?: Options): NewClass }; + + /** + * You can also use the following shortcut when you just need to make + * one additional method call. + */ + addInitHook(methodName: string, ...args: any[]): void; + } + + + /** + * L.Class powers the OOP facilities of Leaflet and is used to create + * almost all of the Leaflet classes documented. + */ + namespace Class { + /** + * You use L.Class.extend to define new classes, but you can use the + * same method on any class to inherit from it. + */ + function extend(options: ClassExtendOptions): any; + } + +} + +declare namespace L { + export interface ControlStatic extends ClassStatic { + /** + * Creates a control with the given options. + */ + new(options?: ControlOptions): Control; + + Zoom: Control.ZoomStatic; + Attribution: Control.AttributionStatic; + Layers: Control.LayersStatic; + Scale: Control.ScaleStatic; + } + export var Control: ControlStatic; + + export interface Control extends IControl { + /** + * Sets the position of the control. See control positions. + */ + setPosition(position: PositionString): Control; + + /** + * Returns the current position of the control. + */ + getPosition(): PositionString; + + /** + * Adds the control to the map. + */ + addTo(map: Map): Control; + + /** + * Removes the control from the map. + */ + removeFrom(map: Map): Control; + + /** + * Returns the HTML container of the control. + */ + getContainer(): HTMLElement; + + // IControl members + + /** + * Should contain code that creates all the neccessary DOM elements for the + * control, adds listeners on relevant map events, and returns the element + * containing the control. Called on map.addControl(control) or control.addTo(map). + */ + onAdd(map: Map): HTMLElement; + + /** + * Optional, should contain all clean up code (e.g. removes control's event + * listeners). Called on map.removeControl(control) or control.removeFrom(map). + * The control's DOM container is removed automatically. + */ + onRemove(map: Map): void; + } + + namespace Control { + export interface ZoomStatic extends ClassStatic { + /** + * Creates a zoom control. + */ + new (options?: ZoomOptions): Zoom; + } + + export interface Zoom extends L.Control { + } + + export interface ZoomOptions { + /** + * The position of the control (one of the map corners). + * Can be 'topleft', 'topright', 'bottomleft', or 'bottomright'. + * + * Default value: 'topright'. + */ + position?: PositionString; + + /** + * The text set on the zoom in button. + * + * Default value: '+' + */ + zoomInText?: string; + + /** + * The text set on the zoom out button. + * + * Default value: '-' + */ + zoomOutText?: string; + + /** + * The title set on the zoom in button. + * + * Default value: 'Zoom in' + */ + zoomInTitle?: string; + + /** + * The title set on the zoom out button. + * + * Default value: 'Zoom out' + */ + zoomOutTitle?: string; + } + + export interface AttributionStatic extends ClassStatic { + /** + * Creates an attribution control. + */ + new(options?: AttributionOptions): Attribution; + } + + export interface Attribution extends L.Control { + /** + * Sets the text before the attributions. + */ + setPrefix(prefix: string): Attribution; + + /** + * Adds an attribution text (e.g. 'Vector data © CloudMade'). + */ + addAttribution(text: string): Attribution; + + /** + * Removes an attribution text. + */ + removeAttribution(text: string): Attribution; + + } + + export interface LayersStatic extends ClassStatic { + /** + * Creates an attribution control with the given layers. Base layers will be + * switched with radio buttons, while overlays will be switched with checkboxes. + */ + new(baseLayers?: any, overlays?: any, options?: LayersOptions): Layers; + } + + export interface Layers extends L.Control, IEventPowered { + /** + * Adds a base layer (radio button entry) with the given name to the control. + */ + addBaseLayer(layer: ILayer, name: string): Layers; + + /** + * Adds an overlay (checkbox entry) with the given name to the control. + */ + addOverlay(layer: ILayer, name: string): Layers; + + /** + * Remove the given layer from the control. + */ + removeLayer(layer: ILayer): Layers; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Layers; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Layers; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Layers; + fire(type: string, data?: any): Layers; + addEventListener(eventMap: any, context?: any): Layers; + removeEventListener(eventMap?: any, context?: any): Layers; + clearAllEventListeners(): Layers; + on(eventMap: any, context?: any): Layers; + off(eventMap?: any, context?: any): Layers; + } + + export interface ScaleStatic extends ClassStatic { + /** + * Creates an scale control with the given options. + */ + new(options?: ScaleOptions): Scale; + } + + export interface Scale extends L.Control { + } + } + + export interface control { + /** + * Creates a control with the given options. + */ + (options?: ControlOptions): Control; + } + + export namespace control { + + /** + * Creates a zoom control. + */ + export function zoom(options?: Control.ZoomOptions): L.Control.Zoom; + + /** + * Creates an attribution control. + */ + export function attribution(options?: AttributionOptions): L.Control.Attribution; + + /** + * Creates an attribution control with the given layers. Base layers will be + * switched with radio buttons, while overlays will be switched with checkboxes. + */ + export function layers(baseLayers?: any, overlays?: any, options?: LayersOptions): L.Control.Layers; + + /** + * Creates an scale control with the given options. + */ + export function scale(options?: ScaleOptions): L.Control.Scale; + } +} + +declare namespace L { + + export interface ControlOptions { + + /** + * The initial position of the control (one of the map corners). See control + * positions. + * Default value: 'topright'. + */ + position?: PositionString; + + } +} + +declare namespace L { + + namespace CRS { + + /** + * The most common CRS for online maps, used by almost all free and commercial + * tile providers. Uses Spherical Mercator projection. Set in by default in + * Map's crs option. + */ + export var EPSG3857: ICRS; + + /** + * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection. + */ + export var EPSG4326: ICRS; + + /** + * Rarely used by some commercial tile providers. Uses Elliptical Mercator + * projection. + */ + export var EPSG3395: ICRS; + + /** + * A simple CRS that maps longitude and latitude into x and y directly. May be + * used for maps of flat surfaces (e.g. game maps). Note that the y axis should + * still be inverted (going from bottom to top). + */ + export var Simple: ICRS; + + } +} + +declare namespace L { + + /** + * Creates a div icon instance with the given options. + */ + function divIcon(options: DivIconOptions): DivIcon; + + export interface DivIconStatic extends ClassStatic { + /** + * Creates a div icon instance with the given options. + */ + new(options: DivIconOptions): DivIcon; + } + export var DivIcon: DivIconStatic; + + export interface DivIcon extends Icon { + } +} + +declare namespace L { + + export interface DivIconOptions { + + /** + * Size of the icon in pixels. Can be also set through CSS. + */ + iconSize?: Point|[number, number]; + + /** + * The coordinates of the "tip" of the icon (relative to its top left corner). + * The icon will be aligned so that this point is at the marker's geographical + * location. Centered by default if size is specified, also can be set in CSS + * with negative margins. + */ + iconAnchor?: Point|[number, number]; + + /** + * A custom class name to assign to the icon. + * + * Default value: 'leaflet-div-icon'. + */ + className?: string; + + /** + * A custom HTML code to put inside the div element. + * + * Default value: ''. + */ + html?: string; + + /** + * The coordinates of the point from which popups will "open", relative to the + * icon anchor. + */ + popupAnchor?: Point|[number, number]; + + } +} + +declare namespace L { + + export interface DomEvent { + + /** + * Adds a listener fn to the element's DOM event of the specified type. this keyword + * inside the listener will point to context, or to the element if not specified. + */ + addListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + on(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + + /** + * Removes an event listener from the element. + */ + removeListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + off(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + + /** + * Stop the given event from propagation to parent elements. Used inside the + * listener functions: + * L.DomEvent.addListener(div, 'click', function + * (e) { + * L.DomEvent.stopPropagation(e); + * }); + */ + stopPropagation(e: Event): DomEvent; + + /** + * Prevents the default action of the event from happening (such as following + * a link in the href of the a element, or doing a POST request with page reload + * when form is submitted). Use it inside listener functions. + */ + preventDefault(e: Event): DomEvent; + + /** + * Does stopPropagation and preventDefault at the same time. + */ + stop(e: Event): DomEvent; + + /** + * Adds stopPropagation to the element's 'click', 'doubleclick', 'mousedown' + * and 'touchstart' events. + */ + disableClickPropagation(el: HTMLElement): DomEvent; + + /** + * Gets normalized mouse position from a DOM event relative to the container + * or to the whole page if not specified. + */ + getMousePosition(e: Event, container?: HTMLElement): Point; + + /** + * Gets normalized wheel delta from a mousewheel DOM event. + */ + getWheelDelta(e: Event): number; + + } + + export var DomEvent: DomEvent; +} + +declare namespace L { + + namespace DomUtil { + + /** + * Returns an element with the given id if a string was passed, or just returns + * the element if it was passed directly. + */ + export function get(id: string): HTMLElement; + + /** + * Returns the value for a certain style attribute on an element, including + * computed values or values set through CSS. + */ + export function getStyle(el: HTMLElement, style: string): string; + + /** + * Returns the offset to the viewport for the requested element. + */ + export function getViewportOffset(el: HTMLElement): Point; + + /** + * Creates an element with tagName, sets the className, and optionally appends + * it to container element. + */ + export function create(tagName: string, className: string, container?: HTMLElement): HTMLElement; + + /** + * Makes sure text cannot be selected, for example during dragging. + */ + export function disableTextSelection(): void; + + /** + * Makes text selection possible again. + */ + export function enableTextSelection(): void; + + /** + * Returns true if the element class attribute contains name. + */ + export function hasClass(el: HTMLElement, name: string): boolean; + + /** + * Adds name to the element's class attribute. + */ + export function addClass(el: HTMLElement, name: string): void; + + /** + * Removes name from the element's class attribute. + */ + export function removeClass(el: HTMLElement, name: string): void; + + /** + * Set the opacity of an element (including old IE support). Value must be from + * 0 to 1. + */ + export function setOpacity(el: HTMLElement, value: number): void; + + /** + * Goes through the array of style names and returns the first name that is a valid + * style name for an element. If no such name is found, it returns false. Useful + * for vendor-prefixed styles like transform. + */ + export function testProp(props: string[]): any; + + /** + * Returns a CSS transform string to move an element by the offset provided in + * the given point. Uses 3D translate on WebKit for hardware-accelerated transforms + * and 2D on other browsers. + */ + export function getTranslateString(point: Point): string; + + /** + * Returns a CSS transform string to scale an element (with the given scale origin). + */ + export function getScaleString(scale: number, origin: Point): string; + + /** + * Sets the position of an element to coordinates specified by point, using + * CSS translate or top/left positioning depending on the browser (used by + * Leaflet internally to position its layers). Forces top/left positioning + * if disable3D is true. + */ + export function setPosition(el: HTMLElement, point: Point, disable3D?: boolean): void; + + /** + * Returns the coordinates of an element previously positioned with setPosition. + */ + export function getPosition(el: HTMLElement): Point; + + /** + * Vendor-prefixed transition style name (e.g. 'webkitTransition' for WebKit). + */ + export var TRANSITION: string; + + /** + * Vendor-prefixed transform style name. + */ + export var TRANSFORM: string; + + } +} + +declare namespace L { + export interface DraggableStatic extends ClassStatic { + /** + * Creates a Draggable object for moving the given element when you start dragging + * the dragHandle element (equals the element itself by default). + */ + new(element: HTMLElement, dragHandle?: HTMLElement): Draggable; + } + export var Draggable: DraggableStatic; + + + export interface Draggable extends IEventPowered { + /** + * Enables the dragging ability. + */ + enable(): void; + + /** + * Disables the dragging ability. + */ + disable(): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Draggable; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Draggable; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Draggable; + fire(type: string, data?: any): Draggable; + addEventListener(eventMap: any, context?: any): Draggable; + removeEventListener(eventMap?: any, context?: any): Draggable; + clearAllEventListeners(): Draggable; + on(eventMap: any, context?: any): Draggable; + off(eventMap?: any, context?: any): Draggable; + } +} + + + +declare namespace L { + + /** + * Create a layer group, optionally given an initial set of layers. + */ + function featureGroup(layers?: T[]): FeatureGroup; + + + export interface FeatureGroupStatic extends ClassStatic { + /** + * Create a layer group, optionally given an initial set of layers. + */ + new(layers?: T[]): FeatureGroup; + } + export var FeatureGroup: FeatureGroupStatic; + + export interface FeatureGroup extends LayerGroup, ILayer, IEventPowered> { + /** + * Binds a popup with a particular HTML content to a click on any layer from the + * group that has a bindPopup method. + */ + bindPopup(htmlContent: string, options?: PopupOptions): FeatureGroup; + + /** + * Returns the LatLngBounds of the Feature Group (created from bounds and coordinates + * of its children). + */ + getBounds(): LatLngBounds; + + /** + * Sets the given path options to each layer of the group that has a setStyle method. + */ + setStyle(style: PathOptions): FeatureGroup; + + /** + * Brings the layer group to the top of all other layers. + */ + bringToFront(): FeatureGroup; + + /** + * Brings the layer group to the bottom of all other layers. + */ + bringToBack(): FeatureGroup; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): FeatureGroup; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; + fire(type: string, data?: any): FeatureGroup; + addEventListener(eventMap: any, context?: any): FeatureGroup; + removeEventListener(eventMap?: any, context?: any): FeatureGroup; + clearAllEventListeners(): FeatureGroup; + on(eventMap: any, context?: any): FeatureGroup; + off(eventMap?: any, context?: any): FeatureGroup; + } +} + +declare namespace L { + + /** + * Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format + * to display on the map (you can alternatively add it later with addData method) + * and an options object. + */ + function geoJson(geojson?: any, options?: GeoJSONOptions): GeoJSON; + + export interface GeoJSONStatic extends ClassStatic { + /** + * Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format + * to display on the map (you can alternatively add it later with addData method) + * and an options object. + */ + new(geojson?: any, options?: GeoJSONOptions): GeoJSON; + + /** + * Creates a layer from a given GeoJSON feature. + */ + geometryToLayer(featureData: GeoJSON, pointToLayer?: (featureData: any, latlng: LatLng) => ILayer): ILayer; + + /** + * Creates a LatLng object from an array of 2 numbers (latitude, longitude) + * used in GeoJSON for points. If reverse is set to true, the numbers will be interpreted + * as (longitude, latitude). + */ + coordsToLatLng(coords: number[], reverse?: boolean): LatLng; + + /** + * Creates a multidimensional array of LatLng objects from a GeoJSON coordinates + * array. levelsDeep specifies the nesting level (0 is for an array of points, + * 1 for an array of arrays of points, etc., 0 by default). If reverse is set to + * true, the numbers will be interpreted as (longitude, latitude). + */ + coordsToLatLngs(coords: any[], levelsDeep?: number, reverse?: boolean): any[]; + } + export var GeoJSON: GeoJSONStatic; + + export interface GeoJSON extends FeatureGroup { + /** + * Adds a GeoJSON object to the layer. + */ + addData(data: any): boolean; + + /** + * Changes styles of GeoJSON vector layers with the given style function. + */ + setStyle(style: (featureData: any) => any): GeoJSON; + + /** + * Changes styles of GeoJSON vector layers with the given style options. + */ + setStyle(style: PathOptions): GeoJSON; + + /** + * Resets the the given vector layer's style to the original GeoJSON style, + * useful for resetting style after hover events. + */ + resetStyle(layer: Path): GeoJSON; + } +} + +declare namespace L { + export interface GeoJSONOptions { + /** + * Function that will be used for creating layers for GeoJSON points (if not + * specified, simple markers will be created). + */ + pointToLayer?: (featureData: any, latlng: LatLng) => ILayer; + + /** + * Function that will be used to get style options for vector layers created + * for GeoJSON features. + */ + style?: (featureData: any) => any; + + /** + * Function that will be called on each created feature layer. Useful for attaching + * events and popups to features. + */ + onEachFeature?: (featureData: any, layer: ILayer) => void; + + /** + * Function that will be used to decide whether to show a feature or not. + */ + filter?: (featureData: any, layer: ILayer) => boolean; + + /** + * Function that will be used for converting GeoJSON coordinates to LatLng points + * (if not specified, coords will be assumed to be WGS84 � standard[longitude, latitude] + * values in degrees). + */ + coordsToLatLng?: (coords: any[]) => LatLng[]; + } +} + + + + +declare namespace L { + + /** + * Creates an icon instance with the given options. + */ + function icon(options: IconOptions): Icon; + + export interface IconStatic extends ClassStatic { + /** + * Creates an icon instance with the given options. + */ + new(options: IconOptions): Icon; + + Default: { + /** + * Creates a default icon instance with the given options. + */ + new(options?: IconOptions): Icon.Default; + + imagePath: string; + }; + } + export var Icon: IconStatic; + + export interface Icon { + } + + namespace Icon { + /** + * L.Icon.Default extends L.Icon and is the blue icon Leaflet uses + * for markers by default. + */ + export interface Default extends Icon { + } + } +} + +declare namespace L { + + export interface IconOptions { + + /** + * (required) The URL to the icon image (absolute or relative to your script + * path). + */ + iconUrl?: string; + + /** + * The URL to a retina sized version of the icon image (absolute or relative to + * your script path). Used for Retina screen devices. + */ + iconRetinaUrl?: string; + + /** + * Size of the icon image in pixels. + */ + iconSize?: Point|[number, number]; + + /** + * The coordinates of the "tip" of the icon (relative to its top left corner). + * The icon will be aligned so that this point is at the marker's geographical + * location. Centered by default if size is specified, also can be set in CSS + * with negative margins. + */ + iconAnchor?: Point|[number, number]; + + /** + * The URL to the icon shadow image. If not specified, no shadow image will be + * created. + */ + shadowUrl?: string; + + /** + * The URL to the retina sized version of the icon shadow image. If not specified, + * no shadow image will be created. Used for Retina screen devices. + */ + shadowRetinaUrl?: string; + + /** + * Size of the shadow image in pixels. + */ + shadowSize?: Point|[number, number]; + + /** + * The coordinates of the "tip" of the shadow (relative to its top left corner) + * (the same as iconAnchor if not specified). + */ + shadowAnchor?: Point|[number, number]; + + /** + * The coordinates of the point from which popups will "open", relative to the + * icon anchor. + */ + popupAnchor?: Point|[number, number]; + + /** + * A custom class name to assign to both icon and shadow images. Empty by default. + */ + className?: string; + } +} + +declare namespace L { + + export interface IControl { + + /** + * Should contain code that creates all the neccessary DOM elements for the + * control, adds listeners on relevant map events, and returns the element + * containing the control. Called on map.addControl(control) or control.addTo(map). + */ + onAdd(map: Map): HTMLElement; + + /** + * Optional, should contain all clean up code (e.g. removes control's event + * listeners). Called on map.removeControl(control) or control.removeFrom(map). + * The control's DOM container is removed automatically. + */ + onRemove(map: Map): void; + } +} + +declare namespace L { + + export interface ICRS { + + /** + * Projection that this CRS uses. + */ + projection: IProjection; + + /** + * Transformation that this CRS uses to turn projected coordinates into screen + * coordinates for a particular tile service. + */ + transformation: Transformation; + + /** + * Standard code name of the CRS passed into WMS services (e.g. 'EPSG:3857'). + */ + code: string; + + /** + * Projects geographical coordinates on a given zoom into pixel coordinates. + */ + latLngToPoint(latlng: LatLng, zoom: number): Point; + + /** + * The inverse of latLngToPoint. Projects pixel coordinates on a given zoom + * into geographical coordinates. + */ + pointToLatLng(point: Point, zoom: number): LatLng; + + /** + * Projects geographical coordinates into coordinates in units accepted + * for this CRS (e.g. meters for EPSG:3857, for passing it to WMS services). + */ + project(latlng: LatLng): Point; + + /** + * Returns the scale used when transforming projected coordinates into pixel + * coordinates for a particular zoom. For example, it returns 256 * 2^zoom for + * Mercator-based CRS. + */ + scale(zoom: number): number; + + /** + * Returns the size of the world in pixels for a particular zoom. + */ + getSize(zoom: number): Point; + + } +} + +declare namespace L { + + export interface IEventPowered { + + /** + * Adds a listener function (fn) to a particular event type of the object. You + * can optionally specify the context of the listener (object the this keyword + * will point to). You can also pass several space-separated types (e.g. 'click + * dblclick'). + */ + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): T; + + /** + * The same as above except the listener will only get fired once and then removed. + */ + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): T; + /** + * Adds a set of type/listener pairs, e.g. {click: onClick, mousemove: onMouseMove} + */ + addEventListener(eventMap: any, context?: any): T; + + /** + * Removes a previously added listener function. If no function is specified, + * it will remove all the listeners of that particular event from the object. + */ + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): T; + + /** + * Removes a set of type/listener pairs. + */ + removeEventListener(eventMap?: any, context?: any): T; + + /** + * Returns true if a particular event type has some listeners attached to it. + */ + hasEventListeners(type: string): boolean; + + /** + * Fires an event of the specified type. You can optionally provide an data object + * — the first argument of the listener function will contain its properties. + */ + fireEvent(type: string, data?: any): T; + + /** + * Removes all listeners to all events on the object. + */ + clearAllEventListeners(): T; + + /** + * Alias to addEventListener. + */ + on(type: string, fn: (e: LeafletEvent) => void, context?: any): T; + + /** + * Alias to addEventListener. + */ + on(eventMap: any, context?: any): T; + + /** + * Alias to addOneTimeEventListener. + */ + once(type: string, fn: (e: LeafletEvent) => void, context?: any): T; + + /** + * Alias to removeEventListener. + */ + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): T; + + /** + * Alias to removeEventListener. + */ + off(eventMap?: any, context?: any): T; + + /** + * Alias to fireEvent. + */ + fire(type: string, data?: any): T; + } +} + +declare namespace L { + + export interface IHandler { + + /** + * Enables the handler. + */ + enable(): void; + + /** + * Disables the handler. + */ + disable(): void; + + /** + * Returns true if the handler is enabled. + */ + enabled(): boolean; + } + + export interface Handler { + initialize(map: Map): void; + } +} + +declare namespace L { + + export interface ILayer { + + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + } +} + +declare namespace L { + namespace Mixin { + export interface LeafletMixinEvents extends IEventPowered { + } + + export var Events: LeafletMixinEvents; + } +} + +declare namespace L { + + /** + * Instantiates an image overlay object given the URL of the image and the geographical + * bounds it is tied to. + */ + function imageOverlay(imageUrl: string, bounds: LatLngBounds, options?: ImageOverlayOptions): ImageOverlay; + + export interface ImageOverlayStatic extends ClassStatic { + /** + * Instantiates an image overlay object given the URL of the image and the geographical + * bounds it is tied to. + */ + new(imageUrl: string, bounds: LatLngBounds, options?: ImageOverlayOptions): ImageOverlay; + } + export var ImageOverlay: ImageOverlayStatic; + + export interface ImageOverlay extends ILayer { + /** + * Adds the overlay to the map. + */ + addTo(map: Map): ImageOverlay; + + /** + * Sets the opacity of the overlay. + */ + setOpacity(opacity: number): ImageOverlay; + + /** + * Changes the URL of the image. + */ + setUrl(imageUrl: string): ImageOverlay; + + /** + * Brings the layer to the top of all overlays. + */ + bringToFront(): ImageOverlay; + + /** + * Brings the layer to the bottom of all overlays. + */ + bringToBack(): ImageOverlay; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + } +} + +declare namespace L { + + export interface ImageOverlayOptions { + + /** + * The opacity of the image overlay. + */ + opacity?: number; + } +} + +declare namespace L { + + export interface IProjection { + + /** + * Projects geographical coordinates into a 2D point. + */ + project(latlng: LatLng): Point; + + /** + * The inverse of project. Projects a 2D point into geographical location. + */ + unproject(point: Point): LatLng; + } +} + +declare namespace L { + + /** + * A constant that represents the Leaflet version in use. + */ + export var version: string; + + /** + * This method restores the L global variale to the original value it had + * before Leaflet inclusion, and returns the real Leaflet namespace. + */ + export function noConflict(): typeof L; +} + +declare namespace L { + /** + * Creates an object representing a geographical point with the given latitude + * and longitude. + */ + function latLng(latitude: number, longitude: number): LatLng; + + /** + * Creates an object representing a geographical point with the given latitude + * and longitude. + */ + function latLng(coords: LatLngExpression): LatLng; + + export interface LatLngStatic { + /** + * Creates an object representing a geographical point with the given latitude + * and longitude. + */ + new(latitude: number, longitude: number): LatLng; + + /** + * Creates an object representing a geographical point with the given latitude + * and longitude. + */ + new(coords: LatLngExpression): LatLng; + + /** + * A multiplier for converting degrees into radians. + * + * Value: Math.PI / 180. + */ + DEG_TO_RAD: number; + + /** + * A multiplier for converting radians into degrees. + * + * Value: 180 / Math.PI. + */ + RAD_TO_DEG: number; + + /** + * Max margin of error for the equality check. + * + * Value: 1.0E-9. + */ + MAX_MARGIN: number; + } + export var LatLng: LatLngStatic; + + export interface LatLng { + /** + * Returns the distance (in meters) to the given LatLng calculated using the + * Haversine formula. See description on wikipedia + */ + distanceTo(otherLatlng: LatLngExpression): number; + + /** + * Returns true if the given LatLng point is at the same position (within a small + * margin of error). + */ + equals(otherLatlng: LatLngExpression): boolean; + + /** + * Returns a string representation of the point (for debugging purposes). + */ + toString(): string; + + /** + * Returns a new LatLng object with the longitude wrapped around left and right + * boundaries (-180 to 180 by default). + */ + wrap(left?: number, right?: number): LatLng; + + /** + * Latitude in degrees. + */ + lat: number; + + /** + * Longitude in degrees. + */ + lng: number; + } +} + +declare namespace L { + + /** + * Creates a LatLngBounds object by defining south-west and north-east corners + * of the rectangle. + */ + function latLngBounds(southWest: LatLngExpression, northEast: LatLngExpression): LatLngBounds; + + /** + * Creates a LatLngBounds object defined by the geographical points it contains. + * Very useful for zooming the map to fit a particular set of locations with fitBounds. + */ + function latLngBounds(latlngs: LatLngBoundsExpression): LatLngBounds; + + export interface LatLngBoundsStatic { + /** + * Creates a LatLngBounds object by defining south-west and north-east corners + * of the rectangle. + */ + new(southWest: LatLngExpression, northEast: LatLngExpression): LatLngBounds; + + /** + * Creates a LatLngBounds object defined by the geographical points it contains. + * Very useful for zooming the map to fit a particular set of locations with fitBounds. + */ + new(latlngs: LatLngBoundsExpression): LatLngBounds; + } + export var LatLngBounds: LatLngBoundsStatic; + + export interface LatLngBounds { + /** + * Extends the bounds to contain the given point. + */ + extend(latlng: LatLngExpression): LatLngBounds; + + /** + * Extends the bounds to contain the given bounds. + */ + extend(latlng: LatLngBoundsExpression): LatLngBounds; + + /** + * Returns the south-west point of the bounds. + */ + getSouthWest(): LatLng; + + /** + * Returns the north-east point of the bounds. + */ + getNorthEast(): LatLng; + + /** + * Returns the north-west point of the bounds. + */ + getNorthWest(): LatLng; + + /** + * Returns the south-east point of the bounds. + */ + getSouthEast(): LatLng; + + /** + * Returns the west longitude in degrees of the bounds. + */ + getWest(): number; + + /** + * Returns the east longitude in degrees of the bounds. + */ + getEast(): number; + + /** + * Returns the north latitude in degrees of the bounds. + */ + getNorth(): number; + + /** + * Returns the south latitude in degrees of the bounds. + */ + getSouth(): number; + + /** + * Returns the center point of the bounds. + */ + getCenter(): LatLng; + + /** + * Returns true if the rectangle contains the given one. + */ + contains(otherBounds: LatLngBoundsExpression): boolean; + + /** + * Returns true if the rectangle contains the given point. + */ + contains(latlng: LatLngExpression): boolean; + + /** + * Returns true if the rectangle intersects the given bounds. + */ + intersects(otherBounds: LatLngBoundsExpression): boolean; + + /** + * Returns true if the rectangle is equivalent (within a small margin of error) + * to the given bounds. + */ + equals(otherBounds: LatLngBoundsExpression): boolean; + + /** + * Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' + * format. Useful for sending requests to web services that return geo data. + */ + toBBoxString(): string; + + /** + * Returns bigger bounds created by extending the current bounds by a given + * percentage in each direction. + */ + pad(bufferRatio: number): LatLngBounds; + + /** + * Returns true if the bounds are properly initialized. + */ + isValid(): boolean; + + } +} + +declare namespace L { + + /** + * Create a layer group, optionally given an initial set of layers. + */ + function layerGroup(layers?: T[]): LayerGroup; + + + export interface LayerGroupStatic extends ClassStatic { + /** + * Create a layer group, optionally given an initial set of layers. + */ + new(layers?: T[]): LayerGroup; + } + export var LayerGroup: LayerGroupStatic; + + export interface LayerGroup extends ILayer { + /** + * Adds the group of layers to the map. + */ + addTo(map: Map): LayerGroup; + + /** + * Adds a given layer to the group. + */ + addLayer(layer: T): LayerGroup; + + /** + * Removes a given layer from the group. + */ + removeLayer(layer: T): LayerGroup; + + /** + * Removes a given layer of the given id from the group. + */ + removeLayer(id: string): LayerGroup; + + /** + * Returns true if the given layer is currently added to the group. + */ + hasLayer(layer: T): boolean; + + /** + * Returns the layer with the given id. + */ + getLayer(id: string): T; + + /** + * Returns an array of all the layers added to the group. + */ + getLayers(): T[]; + + /** + * Removes all the layers from the group. + */ + clearLayers(): LayerGroup; + + /** + * Iterates over the layers of the group, optionally specifying context of + * the iterator function. + */ + eachLayer(fn: (layer: T) => void, context?: any): LayerGroup; + + /** + * Returns a GeoJSON representation of the layer group (GeoJSON FeatureCollection). + * Note: Descendent classes MultiPolygon & MultiPolyLine return `Feature`s, not `FeatureCollection`s + */ + toGeoJSON(): GeoJSON.FeatureCollection|GeoJSON.Feature; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + } +} + + +declare namespace L { + + export interface LayersOptions { + + /** + * The position of the control (one of the map corners). See control positions. + * + * Default value: 'topright'. + */ + position?: PositionString; + + /** + * If true, the control will be collapsed into an icon and expanded on mouse hover + * or touch. + * + * Default value: true. + */ + collapsed?: boolean; + + /** + * If true, the control will assign zIndexes in increasing order to all of its + * layers so that the order is preserved when switching them on/off. + * + * Default value: true. + */ + autoZIndex?: boolean; + + } +} + +declare namespace L { + + export interface LeafletErrorEvent extends LeafletEvent { + + /** + * Error message. + */ + message: string; + + /** + * Error code (if applicable). + */ + code: number; + } +} + +declare namespace L { + + export interface LeafletEvent { + + /** + * The event type (e.g. 'click'). + */ + type: string; + + /** + * The object that fired the event. + */ + target: any; + } +} + +declare namespace L { + + export interface LeafletGeoJSONEvent extends LeafletEvent { + + /** + * The layer for the GeoJSON feature that is being added to the map. + */ + layer: ILayer; + + /** + * GeoJSON properties of the feature. + */ + properties: any; + + /** + * GeoJSON geometry type of the feature. + */ + geometryType: string; + + /** + * GeoJSON ID of the feature (if present). + */ + id: string; + } +} + +declare namespace L { + + export interface LeafletLayerEvent extends LeafletEvent { + + /** + * The layer that was added or removed. + */ + layer: ILayer; + } +} + +declare namespace L { + + export interface LeafletLayersControlEvent extends LeafletEvent { + + /** + * The layer that was added or removed. + */ + layer: ILayer; + + /** + * The name of the layer that was added or removed. + */ + name: string; + } +} + +declare namespace L { + + export interface LeafletLocationEvent extends LeafletEvent { + + /** + * Detected geographical location of the user. + */ + latlng: LatLng; + + /** + * Geographical bounds of the area user is located in (with respect to the accuracy + * of location). + */ + bounds: LatLngBounds; + + /** + * Accuracy of location in meters. + */ + accuracy: number; + + /** + * Height of the position above the WGS84 ellipsoid in meters. + */ + altitude: number; + + /** + * Accuracy of altitude in meters. + */ + altitudeAccuracy: number; + + /** + * The direction of travel in degrees counting clockwise from true North. + */ + heading: number; + + /** + * Current velocity in meters per second. + */ + speed: number; + + /** + * The time when the position was acquired. + */ + timestamp: number; + + } +} + +declare namespace L { + + export interface LeafletMouseEvent extends LeafletEvent { + + /** + * The geographical point where the mouse event occured. + */ + latlng: LatLng; + + /** + * Pixel coordinates of the point where the mouse event occured relative to + * the map layer. + */ + layerPoint: Point; + + /** + * Pixel coordinates of the point where the mouse event occured relative to + * the map сontainer. + */ + containerPoint: Point; + + /** + * The original DOM mouse event fired by the browser. + */ + originalEvent: MouseEvent; + } +} + +declare namespace L { + + export interface LeafletPopupEvent extends LeafletEvent { + + /** + * The popup that was opened or closed. + */ + popup: Popup; + } +} + +declare namespace L { + + export interface LeafletDragEndEvent extends LeafletEvent { + + /** + * The distance in pixels the draggable element was moved by. + */ + distance: number; + } +} + +declare namespace L { + + export interface LeafletResizeEvent extends LeafletEvent { + + /** + * The old size before resize event. + */ + oldSize: Point; + + /** + * The new size after the resize event. + */ + newSize: Point; + } +} + +declare namespace L { + + export interface LeafletTileEvent extends LeafletEvent { + + /** + * The tile element (image). + */ + tile: HTMLElement; + + /** + * The source URL of the tile. + */ + url: string; + } +} + +declare namespace L { + + namespace LineUtil { + + /** + * Dramatically reduces the number of points in a polyline while retaining + * its shape and returns a new array of simplified points. Used for a huge performance + * boost when processing/displaying Leaflet polylines for each zoom level + * and also reducing visual noise. tolerance affects the amount of simplification + * (lesser value means higher quality but slower and with more points). Also + * released as a separated micro-library Simplify.js. + */ + export function simplify(points: Point[], tolerance: number): Point[]; + + /** + * Returns the distance between point p and segment p1 to p2. + */ + export function pointToSegmentDistance(p: Point, p1: Point, p2: Point): number; + + /** + * Returns the closest point from a point p on a segment p1 to p2. + */ + export function closestPointOnSegment(p: Point, p1: Point, p2: Point): Point; + + /** + * Clips the segment a to b by rectangular bounds. Used by Leaflet to only show + * polyline points that are on the screen or near, increasing performance. Returns + * either false or a length-2 array of clipped points. + */ + export function clipSegment(a: Point, b: Point, bounds: Bounds): Point[] | boolean; + + } +} + +declare namespace L { + + export interface LocateOptions { + + /** + * If true, starts continous watching of location changes (instead of detecting + * it once) using W3C watchPosition method. You can later stop watching using + * map.stopLocate() method. + * + * Default value: false. + */ + watch?: boolean; + + /** + * If true, automatically sets the map view to the user location with respect + * to detection accuracy, or to world view if geolocation failed. + * + * Default value: false. + */ + setView?: boolean; + + /** + * The maximum zoom for automatic view setting when using `setView` option. + * + * Default value: Infinity. + */ + maxZoom?: number; + + /** + * Number of millisecond to wait for a response from geolocation before firing + * a locationerror event. + * + * Default value: 10000. + */ + timeout?: number; + + /** + * Maximum age of detected location. If less than this amount of milliseconds + * passed since last geolocation response, locate will return a cached location. + * + * Default value: 0. + */ + maximumAge?: number; + + /** + * Enables high accuracy, see description in the W3C spec. + * + * Default value: false. + */ + enableHighAccuracy?: boolean; + } +} + +declare namespace L { + + /** + * Instantiates a map object given a div element and optionally an + * object literal with map options described below. + */ + function map(id: HTMLElement, options?: Map.MapOptions): Map; + + /** + * Instantiates a map object given a div element id and optionally an + * object literal with map options described below. + */ + function map(id: string, options?: Map.MapOptions): Map; + + + export interface MapStatic extends ClassStatic { + /** + * Instantiates a map object given a div element and optionally an + * object literal with map options described below. + * + * @constructor + */ + new(id: HTMLElement, options?: Map.MapOptions): Map; + + /** + * Instantiates a map object given a div element id and optionally an + * object literal with map options described below. + * + * @constructor + */ + new(id: string, options?: Map.MapOptions): Map; + } + export var Map: MapStatic; + + export interface Map extends IEventPowered { + // Methods for Modifying Map State + + /** + * Sets the view of the map (geographical center and zoom) with the given + * animation options. + */ + setView(center: LatLngExpression, zoom?: number, options?: Map.ZoomPanOptions): Map; + + /** + * Sets the zoom of the map. + */ + setZoom(zoom: number, options?: Map.ZoomPanOptions): Map; + + /** + * Increases the zoom of the map by delta (1 by default). + */ + zoomIn(delta?: number, options?: Map.ZoomPanOptions): Map; + + /** + * Decreases the zoom of the map by delta (1 by default). + */ + zoomOut(delta?: number, options?: Map.ZoomPanOptions): Map; + + /** + * Zooms the map while keeping a specified point on the map stationary + * (e.g. used internally for scroll zoom and double-click zoom). + */ + setZoomAround(latlng: LatLngExpression, zoom: number, options?: Map.ZoomPanOptions): Map; + + /** + * Sets a map view that contains the given geographical bounds with the maximum + * zoom level possible. + */ + fitBounds(bounds: LatLngBounds, options?: Map.FitBoundsOptions): Map; + + /** + * Sets a map view that mostly contains the whole world with the maximum zoom + * level possible. + */ + fitWorld(options?: Map.FitBoundsOptions): Map; + + /** + * Pans the map to a given center. Makes an animated pan if new center is not more + * than one screen away from the current one. + */ + panTo(latlng: LatLngExpression, options?: PanOptions): Map; + + /** + * Pans the map to the closest view that would lie inside the given bounds (if + * it's not already). + */ + panInsideBounds(bounds: LatLngBounds): Map; + + /** + * Pans the map by a given number of pixels (animated). + */ + panBy(point: Point, options?: PanOptions): Map; + + /** + * Checks if the map container size changed and updates the map if so — call it + * after you've changed the map size dynamically, also animating pan by default. + * If options.pan is false, panning will not occur. + */ + invalidateSize(options: Map.ZoomPanOptions): Map; + + /** + * Checks if the map container size changed and updates the map if so — call it + * after you've changed the map size dynamically, also animating pan by default. + */ + invalidateSize(animate: boolean): Map; + + /** + * Restricts the map view to the given bounds (see map maxBounds option), + * passing the given animation options through to `setView`, if required. + */ + setMaxBounds(bounds: LatLngBounds, options?: Map.ZoomPanOptions): Map; + + /** + * Tries to locate the user using Geolocation API, firing locationfound event + * with location data on success or locationerror event on failure, and optionally + * sets the map view to the user location with respect to detection accuracy + * (or to the world view if geolocation failed). See Locate options for more + * details. + */ + locate(options?: LocateOptions): Map; + + /** + * Stops watching location previously initiated by map.locate({watch: true}) + * and aborts resetting the map view if map.locate was called with {setView: true}. + */ + stopLocate(): Map; + + /** + * Destroys the map and clears all related event listeners. + */ + remove(): Map; + + // Methods for Getting Map State + + /** + * Returns the geographical center of the map view. + */ + getCenter(): LatLng; + + /** + * Returns the current zoom of the map view. + */ + getZoom(): number; + + /** + * Returns the minimum zoom level of the map. + */ + getMinZoom(): number; + + /** + * Returns the maximum zoom level of the map. + */ + getMaxZoom(): number; + + /** + * Returns the LatLngBounds of the current map view. + */ + getBounds(): LatLngBounds; + + /** + * Returns the maximum zoom level on which the given bounds fit to the map view + * in its entirety. If inside (optional) is set to true, the method instead returns + * the minimum zoom level on which the map view fits into the given bounds in its + * entirety. + */ + getBoundsZoom(bounds: LatLngBounds, inside?: boolean): number; + + /** + * Returns the current size of the map container. + */ + getSize(): Point; + + /** + * Returns the bounds of the current map view in projected pixel coordinates + * (sometimes useful in layer and overlay implementations). + */ + getPixelBounds(): Bounds; + + /** + * Returns the projected pixel coordinates of the top left point of the map layer + * (useful in custom layer and overlay implementations). + */ + getPixelOrigin(): Point; + + // Methods for Layers and Controls + + /** + * Adds the given layer to the map. If optional insertAtTheBottom is set to true, + * the layer is inserted under all others (useful when switching base tile layers). + */ + addLayer(layer: ILayer, insertAtTheBottom?: boolean): Map; + + /** + * Removes the given layer from the map. + */ + removeLayer(layer: ILayer): Map; + + /** + * Returns true if the given layer is currently added to the map. + */ + hasLayer(layer: ILayer): boolean; + + /** + * Opens the specified popup while closing the previously opened (to make sure + * only one is opened at one time for usability). + */ + openPopup(popup: Popup): Map; + + /** + * Creates a popup with the specified options and opens it in the given point + * on a map. + */ + openPopup(html: string, latlng: LatLngExpression, options?: PopupOptions): Map; + + /** + * Creates a popup with the specified options and opens it in the given point + * on a map. + */ + openPopup(el: HTMLElement, latlng: LatLngExpression, options?: PopupOptions): Map; + + /** + * Closes the popup previously opened with openPopup (or the given one). + */ + closePopup(popup?: Popup): Map; + + /** + * Adds the given control to the map. + */ + addControl(control: IControl): Map; + + /** + * Removes the given control from the map. + */ + removeControl(control: IControl): Map; + + // Conversion Methods + + /** + * Returns the map layer point that corresponds to the given geographical coordinates + * (useful for placing overlays on the map). + */ + latLngToLayerPoint(latlng: LatLngExpression): Point; + + /** + * Returns the geographical coordinates of a given map layer point. + */ + layerPointToLatLng(point: Point): LatLng; + + /** + * Converts the point relative to the map container to a point relative to the + * map layer. + */ + containerPointToLayerPoint(point: Point): Point; + + /** + * Converts the point relative to the map layer to a point relative to the map + * container. + */ + layerPointToContainerPoint(point: Point): Point; + + /** + * Returns the map container point that corresponds to the given geographical + * coordinates. + */ + latLngToContainerPoint(latlng: LatLngExpression): Point; + + /** + * Returns the geographical coordinates of a given map container point. + */ + containerPointToLatLng(point: Point): LatLng; + + /** + * Projects the given geographical coordinates to absolute pixel coordinates + * for the given zoom level (current zoom level by default). + */ + project(latlng: LatLngExpression, zoom?: number): Point; + + /** + * Projects the given absolute pixel coordinates to geographical coordinates + * for the given zoom level (current zoom level by default). + */ + unproject(point: Point, zoom?: number): LatLng; + + /** + * Returns the pixel coordinates of a mouse click (relative to the top left corner + * of the map) given its event object. + */ + mouseEventToContainerPoint(event: LeafletMouseEvent): Point; + + /** + * Returns the pixel coordinates of a mouse click relative to the map layer given + * its event object. + */ + mouseEventToLayerPoint(event: LeafletMouseEvent): Point; + + /** + * Returns the geographical coordinates of the point the mouse clicked on given + * the click's event object. + */ + mouseEventToLatLng(event: LeafletMouseEvent): LatLng; + + // Other Methods + + /** + * Returns the container element of the map. + */ + getContainer(): HTMLElement; + + /** + * Returns an object with different map panes (to render overlays in). + */ + getPanes(): MapPanes; + + // REVIEW: Should we make it more flexible declaring parameter 'fn' as Function? + /** + * Runs the given callback when the map gets initialized with a place and zoom, + * or immediately if it happened already, optionally passing a function context. + */ + whenReady(fn: (map: Map) => void, context?: any): Map; + + // Properties + + /** + * Map dragging handler (by both mouse and touch). + */ + dragging: IHandler; + + /** + * Touch zoom handler. + */ + touchZoom: IHandler; + + /** + * Double click zoom handler. + */ + doubleClickZoom: IHandler; + + /** + * Scroll wheel zoom handler. + */ + scrollWheelZoom: IHandler; + + /** + * Box (shift-drag with mouse) zoom handler. + */ + boxZoom: IHandler; + + /** + * Keyboard navigation handler. + */ + keyboard: IHandler; + + /** + * Mobile touch hacks (quick tap and touch hold) handler. + */ + tap: IHandler; + + /** + * Zoom control. + */ + zoomControl: Control.Zoom; + + /** + * Attribution control. + */ + attributionControl: Control.Attribution; + + /** + * Map state options + */ + options: Map.MapOptions; + + /** + * Iterates over the layers of the map, optionally specifying context + * of the iterator function. + */ + eachLayer(fn: (layer: ILayer) => void, context?: any): Map; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Map; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Map; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Map; + fire(type: string, data?: any): Map;addEventListener(eventMap: any, context?: any): Map; + removeEventListener(eventMap?: any, context?: any): Map; + clearAllEventListeners(): Map; + on(eventMap: any, context?: any): Map; + off(eventMap?: any, context?: any): Map; + } +} + +declare namespace L.Map { + + export interface MapOptions { + + // Map State Options + + /** + * Initial geographical center of the map. + */ + center?: LatLng; + + /** + * Initial map zoom. + */ + zoom?: number; + + /** + * Layers that will be added to the map initially. + */ + layers?: ILayer[]; + + /** + * Minimum zoom level of the map. Overrides any minZoom set on map layers. + */ + minZoom?: number; + + /** + * Maximum zoom level of the map. This overrides any maxZoom set on map layers. + */ + maxZoom?: number; + + /** + * When this option is set, the map restricts the view to the given geographical + * bounds, bouncing the user back when he tries to pan outside the view, and also + * not allowing to zoom out to a view that's larger than the given bounds (depending + * on the map size). To set the restriction dynamically, use setMaxBounds method + */ + maxBounds?: LatLngBounds; + + /** + * Coordinate Reference System to use. Don't change this if you're not sure + * what it means. + * + * Default value: L.CRS.EPSG3857. + */ + crs?: ICRS; + + // Interaction Options + + /** + * Whether the map be draggable with mouse/touch or not. + * + * Default value: true. + */ + dragging?: boolean; + + /** + * Whether the map can be zoomed by touch-dragging with two fingers. + * + * Default value: true. + */ + touchZoom?: boolean; + + /** + * Whether the map can be zoomed by using the mouse wheel. + * If passed 'center', it will zoom to the center of the view regardless of + * where the mouse was. + * + * Default value: true. + */ + scrollWheelZoom?: boolean; + + /** + * Whether the map can be zoomed in by double clicking on it and zoomed out + * by double clicking while holding shift. + * If passed 'center', double-click zoom will zoom to the center of the view + * regardless of where the mouse was. + * + * Default value: true. + */ + doubleClickZoom?: boolean; + + /** + * Whether the map can be zoomed to a rectangular area specified by dragging + * the mouse while pressing shift. + * + * Default value: true. + */ + boxZoom?: boolean; + + /** + * Enables mobile hacks for supporting instant taps (fixing 200ms click delay + * on iOS/Android) and touch holds (fired as contextmenu events). + * + * Default value: true. + */ + tap?: boolean; + + /** + * The max number of pixels a user can shift his finger during touch for it + * to be considered a valid tap. + * + * Default value: 15. + */ + tapTolerance?: number; + + /** + * Whether the map automatically handles browser window resize to update itself. + * + * Default value: true. + */ + trackResize?: boolean; + + /** + * With this option enabled, the map tracks when you pan to another "copy" of + * the world and seamlessly jumps to the original one so that all overlays like + * markers and vector layers are still visible. + * + * Default value: false. + */ + worldCopyJump?: boolean; + + /** + * Set it to false if you don't want popups to close when user clicks the map. + * + * Default value: true. + */ + closePopupOnClick?: boolean; + + // Keyboard Navigation Options + + /** + * Makes the map focusable and allows users to navigate the map with keyboard + * arrows and +/- keys. + * + * Default value: true. + */ + keyboard?: boolean; + + /** + * Amount of pixels to pan when pressing an arrow key. + * + * Default value: 80. + */ + keyboardPanOffset?: number; + + /** + * Number of zoom levels to change when pressing + or - key. + * + * Default value: 1. + */ + keyboardZoomOffset?: number; + + // Panning Inertia Options + + /** + * If enabled, panning of the map will have an inertia effect where the map builds + * momentum while dragging and continues moving in the same direction for some + * time. Feels especially nice on touch devices. + * + * Default value: true. + */ + inertia?: boolean; + + /** + * The rate with which the inertial movement slows down, in pixels/second2. + * + * Default value: 3000. + */ + inertiaDeceleration?: number; + + /** + * Max speed of the inertial movement, in pixels/second. + * + * Default value: 1500. + */ + inertiaMaxSpeed?: number; + + /** + * Amount of milliseconds that should pass between stopping the movement and + * releasing the mouse or touch to prevent inertial movement. + * + * Default value: 32 for touch devices and 14 for the rest. + */ + inertiaThreshold?: number; + + // Control options + + /** + * Whether the zoom control is added to the map by default. + * + * Default value: true. + */ + zoomControl?: boolean; + + /** + * Whether the attribution control is added to the map by default. + * + * Default value: true. + */ + attributionControl?: boolean; + + // Animation options + + /** + * Whether the tile fade animation is enabled. By default it's enabled in all + * browsers that support CSS3 Transitions except Android. + */ + fadeAnimation?: boolean; + + /** + * Whether the tile zoom animation is enabled. By default it's enabled in all + * browsers that support CSS3 Transitions except Android. + */ + zoomAnimation?: boolean; + + /** + * Won't animate zoom if the zoom difference exceeds this value. + * + * Default value: 4. + */ + zoomAnimationThreshold?: number; + + /** + * Whether markers animate their zoom with the zoom animation, if disabled + * they will disappear for the length of the animation. By default it's enabled + * in all browsers that support CSS3 Transitions except Android. + */ + markerZoomAnimation?: boolean; + + /** + * Set it to false if you don't want the map to zoom beyond min/max zoom + * and then bounce back when pinch-zooming. + * + * Default value: true. + */ + bounceAtZoomLimits?: boolean; + } + + export interface ZoomOptions { + /** + * If not specified, zoom animation will happen if the zoom origin is inside the current view. + * If true, the map will attempt animating zoom disregarding where zoom origin is. + * Setting false will make it always reset the view completely without animation. + */ + animate?: boolean; + } + + export interface ZoomPanOptions { + + /** + * If true, the map view will be completely reset (without any animations). + * + * Default value: false. + */ + reset?: boolean; + + /** + * Sets the options for the panning (without the zoom change) if it occurs. + */ + pan?: PanOptions; + + /** + * Sets the options for the zoom change if it occurs. + */ + zoom?: ZoomOptions; + + /** + * An equivalent of passing animate to both zoom and pan options (see below). + */ + animate?: boolean; + + /** + * If true, it will delay moveend event so that it doesn't happen many times in a row. + */ + debounceMoveend?: boolean; + + /** + * Duration of animated panning, in seconds. + */ + duration?: number; + + /** + * The curvature factor of panning animation easing (third parameter of the Cubic Bezier curve). + * 1.0 means linear animation, the less the more bowed the curve. + */ + easeLinearity?: number; + + /** + * If true, panning won't fire movestart event on start (used internally for panning inertia). + */ + noMoveStart?: boolean; + } + + export interface FitBoundsOptions extends ZoomPanOptions { + + /** + * Sets the amount of padding in the top left corner of a map container that + * shouldn't be accounted for when setting the view to fit bounds. Useful if + * you have some control overlays on the map like a sidebar and you don't + * want them to obscure objects you're zooming to. + * + * Default value: [0, 0]. + */ + paddingTopLeft?: Point; + + /** + * The same for bottom right corner of the map. + * + * Default value: [0, 0]. + */ + paddingBottomRight?: Point; + + /** + * Equivalent of setting both top left and bottom right padding to the same value. + * + * Default value: [0, 0]. + */ + padding?: Point; + + /** + * The maximum possible zoom to use. + * + * Default value: null + */ + maxZoom?: number; + } +} + +declare namespace L { + + export interface MapPanes { + + /** + * Pane that contains all other map panes. + */ + mapPane: HTMLElement; + + /** + * Pane for tile layers. + */ + tilePane: HTMLElement; + + /** + * Pane that contains all the panes except tile pane. + */ + objectsPane: HTMLElement; + + /** + * Pane for overlay shadows (e.g. marker shadows). + */ + shadowPane: HTMLElement; + + /** + * Pane for overlays like polylines and polygons. + */ + overlayPane: HTMLElement; + + /** + * Pane for marker icons. + */ + markerPane: HTMLElement; + + /** + * Pane for popups. + */ + popupPane: HTMLElement; + } +} + +declare namespace L { + + /** + * Instantiates a Marker object given a geographical point and optionally + * an options object. + */ + function marker(latlng: LatLngExpression, options?: MarkerOptions): Marker; + + var Marker: { + /** + * Instantiates a Marker object given a geographical point and optionally + * an options object. + */ + new(latlng: LatLngExpression, options?: MarkerOptions): Marker; + }; + + export interface Marker extends ILayer, IEventPowered { + /** + * Adds the marker to the map. + */ + addTo(map: Map): Marker; + + /** + * Returns the current geographical position of the marker. + */ + getLatLng(): LatLng; + + /** + * Changes the marker position to the given point. + */ + setLatLng(latlng: LatLngExpression): Marker; + + /** + * Changes the marker icon. + */ + setIcon(icon: Icon): Marker; + + /** + * Changes the zIndex offset of the marker. + */ + setZIndexOffset(offset: number): Marker; + + /** + * Changes the opacity of the marker. + */ + setOpacity(opacity: number): Marker; + + /** + * Updates the marker position, useful if coordinates of its latLng object + * were changed directly. + */ + update(): Marker; + + /** + * Binds a popup with a particular HTML content to a click on this marker. You + * can also open the bound popup with the Marker openPopup method. + */ + bindPopup(html: string, options?: PopupOptions): Marker; + + /** + * Binds a popup with a particular HTML content to a click on this marker. You + * can also open the bound popup with the Marker openPopup method. + */ + bindPopup(el: HTMLElement, options?: PopupOptions): Marker; + + /** + * Binds a popup with a particular HTML content to a click on this marker. You + * can also open the bound popup with the Marker openPopup method. + */ + bindPopup(popup: Popup, options?: PopupOptions): Marker; + + /** + * Unbinds the popup previously bound to the marker with bindPopup. + */ + unbindPopup(): Marker; + + /** + * Opens the popup previously bound by the bindPopup method. + */ + openPopup(): Marker; + + /** + * Returns the popup previously bound by the bindPopup method. + */ + getPopup(): Popup; + + /** + * Closes the bound popup of the marker if it's opened. + */ + closePopup(): Marker; + + /** + * Toggles the popup previously bound by the bindPopup method. + */ + togglePopup(): Marker; + + /** + * Sets an HTML content of the popup of this marker. + */ + setPopupContent(html: string, options?: PopupOptions): Marker; + + /** + * Sets an HTML content of the popup of this marker. + */ + setPopupContent(el: HTMLElement, options?: PopupOptions): Marker; + + /** + * Returns a GeoJSON representation of the marker (GeoJSON Point Feature). + */ + toGeoJSON(): GeoJSON.Feature; + + /** + * Marker dragging handler (by both mouse and touch). + */ + dragging: IHandler; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Marker; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Marker; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Marker; + fire(type: string, data?: any): Marker; + addEventListener(eventMap: any, context?: any): Marker; + removeEventListener(eventMap?: any, context?: any): Marker; + clearAllEventListeners(): Marker; + on(eventMap: any, context?: any): Marker; + off(eventMap?: any, context?: any): Marker; + } +} + +declare namespace L { + + export interface MarkerOptions { + + /** + * Icon class to use for rendering the marker. See Icon documentation for details + * on how to customize the marker icon. + * + * Default value: new L.Icon.Default(). + */ + icon?: Icon; + + /** + * If false, the marker will not emit mouse events and will act as a part of the + * underlying map. + * + * Default value: true. + */ + clickable?: boolean; + + /** + * Whether the marker is draggable with mouse/touch or not. + * + * Default value: false. + */ + draggable?: boolean; + + /** + * Whether the marker can be tabbed to with a keyboard and clicked by pressing enter. + * + * Default value: true. + */ + keyboard?: boolean; + + /** + * Text for the browser tooltip that appear on marker hover (no tooltip by default). + * + * Default value: ''. + */ + title?: string; + + /** + * Text for the alt attribute of the icon image (useful for accessibility). + * + * Default value: ''. + */ + alt?: string; + + /** + * By default, marker images zIndex is set automatically based on its latitude. + * You this option if you want to put the marker on top of all others (or below), + * specifying a high value like 1000 (or high negative value, respectively). + * + * Default value: 0. + */ + zIndexOffset?: number; + + /** + * The opacity of the marker. + * + * Default value: 1.0. + */ + opacity?: number; + + /** + * If true, the marker will get on top of others when you hover the mouse over it. + * + * Default value: false. + */ + riseOnHover?: boolean; + + /** + * The z-index offset used for the riseOnHover feature. + * + * Default value: 250. + */ + riseOffset?: number; + } +} + +declare namespace L { + + /** + * Instantiates a multi-polyline object given an array of latlngs arrays (one + * for each individual polygon) and optionally an options object (the same + * as for MultiPolyline). + */ + function multiPolygon(latlngs: LatLng[][], options?: PolylineOptions): MultiPolygon; + + export interface MultiPolygonStatic extends ClassStatic { + /** + * Instantiates a multi-polyline object given an array of latlngs arrays (one + * for each individual polygon) and optionally an options object (the same + * as for MultiPolyline). + */ + new(latlngs: LatLng[][], options?: PolylineOptions): MultiPolygon; + } + export var MultiPolygon: MultiPolygonStatic; + + export interface MultiPolygon extends FeatureGroup { + /** + * Replace all polygons and their paths with the given array of arrays + * of geographical points. + */ + setLatLngs(latlngs: LatLng[][]): MultiPolygon; + + /** + * Returns an array of arrays of geographical points in each polygon. + */ + getLatLngs(): LatLng[][]; + + /** + * Opens the popup previously bound by bindPopup. + */ + openPopup(): MultiPolygon; + + /** + * Returns a GeoJSON representation of the multipolygon (GeoJSON MultiPolygon Feature). + */ + toGeoJSON(): GeoJSON.Feature; + } +} + +declare namespace L { + + /** + * Instantiates a multi-polyline object given an array of arrays of geographical + * points (one for each individual polyline) and optionally an options object. + */ + function multiPolyline(latlngs: LatLng[][], options?: PolylineOptions): MultiPolyline; + + export interface MultiPolylineStatic extends ClassStatic { + /** + * Instantiates a multi-polyline object given an array of arrays of geographical + * points (one for each individual polyline) and optionally an options object. + */ + new(latlngs: LatLng[][], options?: PolylineOptions): MultiPolyline; + } + export var MultiPolyline: MultiPolylineStatic; + + export interface MultiPolyline extends FeatureGroup { + /** + * Replace all polygons and their paths with the given array of arrays + * of geographical points. + */ + setLatLngs(latlngs: LatLng[][]): MultiPolyline; + + /** + * Returns an array of arrays of geographical points in each polygon. + */ + getLatLngs(): LatLng[][]; + + /** + * Opens the popup previously bound by bindPopup. + */ + openPopup(): MultiPolyline; + + /** + * Returns a GeoJSON representation of the multipolyline (GeoJSON MultiLineString Feature). + */ + toGeoJSON(): GeoJSON.Feature; + } +} + +declare namespace L { + + export interface PanOptions { + + /** + * If true, panning will always be animated if possible. If false, it will not + * animate panning, either resetting the map view if panning more than a screen + * away, or just setting a new offset for the map pane (except for `panBy` + * which always does the latter). + */ + animate?: boolean; + + /** + * Duration of animated panning. + * + * Default value: 0.25. + */ + duration?: number; + + /** + * The curvature factor of panning animation easing (third parameter of the Cubic + * Bezier curve). 1.0 means linear animation, the less the more bowed the curve. + * + * Default value: 0.25. + */ + easeLinearity?: number; + + /** + * If true, panning won't fire movestart event on start (used internally for panning inertia). + * + * Default value: false. + */ + noMoveStart?: boolean; + } +} + +declare namespace L { + + export interface Path extends ILayer, IEventPowered { + + /** + * Adds the layer to the map. + */ + addTo(map: Map): Path; + + /** + * Binds a popup with a particular HTML content to a click on this path. + */ + bindPopup(html: string, options?: PopupOptions): Path; + + /** + * Binds a popup with a particular HTML content to a click on this path. + */ + bindPopup(el: HTMLElement, options?: PopupOptions): Path; + + /** + * Binds a popup with a particular HTML content to a click on this path. + */ + bindPopup(popup: Popup, options?: PopupOptions): Path; + + /** + * Unbinds the popup previously bound to the path with bindPopup. + */ + unbindPopup(): Path; + + /** + * Opens the popup previously bound by the bindPopup method in the given point, + * or in one of the path's points if not specified. + */ + openPopup(latlng?: LatLngExpression): Path; + + /** + * Closes the path's bound popup if it is opened. + */ + closePopup(): Path; + + /** + * Changes the appearance of a Path based on the options in the Path options object. + */ + setStyle(object: PathOptions): Path; + + /** + * Returns the LatLngBounds of the path. + */ + getBounds(): LatLngBounds; + + /** + * Brings the layer to the top of all path layers. + */ + bringToFront(): Path; + + /** + * Brings the layer to the bottom of all path layers. + */ + bringToBack(): Path; + + /** + * Redraws the layer. Sometimes useful after you changed the coordinates that + * the path uses. + */ + redraw(): Path; + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Path; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Path; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Path; + fire(type: string, data?: any): Path; + addEventListener(eventMap: any, context?: any): Path; + removeEventListener(eventMap?: any, context?: any): Path; + clearAllEventListeners(): Path; + on(eventMap: any, context?: any): Path; + off(eventMap?: any, context?: any): Path; + } + + export namespace Path { + /** + * True if SVG is used for vector rendering (true for most modern browsers). + */ + export var SVG: boolean; + + /** + * True if VML is used for vector rendering (IE 6-8). + */ + export var VML: boolean; + + /** + * True if Canvas is used for vector rendering (Android 2). You can also force + * this by setting global variable L_PREFER_CANVAS to true before the Leaflet + * include on your page — sometimes it can increase performance dramatically + * when rendering thousands of circle markers, but currently suffers from + * a bug that causes removing such layers to be extremely slow. + */ + export var CANVAS: boolean; + + /** + * How much to extend the clip area around the map view (relative to its size, + * e.g. 0.5 is half the screen in each direction). Smaller values mean that you + * will see clipped ends of paths while you're dragging the map, and bigger values + * decrease drawing performance. + */ + export var CLIP_PADDING: number; + } +} + +declare namespace L { + + export interface PathOptions { + + /** + * Whether to draw stroke along the path. Set it to false to disable borders on + * polygons or circles. + * + * Default value: true. + */ + stroke?: boolean; + + /** + * Stroke color. + * + * Default value: '#03f'. + */ + color?: string; + + /** + * Stroke width in pixels. + * + * Default value: 5. + */ + weight?: number; + + /** + * Stroke opacity. + * + * Default value: 0.5. + */ + opacity?: number; + + /** + * Whether to fill the path with color. Set it to false to disable filling on polygons + * or circles. + */ + fill?: boolean; + + /** + * Fill color. + * + * Default value: same as color. + */ + fillColor?: string; + + /** + * Fill opacity. + * + * Default value: 0.2. + */ + fillOpacity?: number; + + /** + * A string that defines the stroke dash pattern. Doesn't work on canvas-powered + * layers (e.g. Android 2). + */ + dashArray?: string; + + /** + * A string that defines shape to be used at the end of the stroke. + * + * Default: null. + */ + lineCap?: string; + + /** + * A string that defines shape to be used at the corners of the stroke. + * + * Default: null. + */ + lineJoin?: string; + + /** + * If false, the vector will not emit mouse events and will act as a part of the + * underlying map. + * + * Default value: true. + */ + clickable?: boolean; + + /** + * Sets the pointer-events attribute on the path if SVG backend is used. + */ + pointerEvents?: string; + + /** + * Custom class name set on an element. + * + * Default value: ''. + */ + className?: string; + + /** + * Sets the radius of a circle marker. + */ + radius?: number; + + } +} + +declare namespace L { + + /** + * Creates a Point object with the given x and y coordinates. If optional round + * is set to true, rounds the x and y values. + */ + function point(x: number, y: number, round?: boolean): Point; + + export interface PointStatic { + /** + * Creates a Point object with the given x and y coordinates. If optional round + * is set to true, rounds the x and y values. + */ + new(x: number, y: number, round?: boolean): Point; + } + export var Point: PointStatic; + + export interface Point { + /** + * Returns the result of addition of the current and the given points. + */ + add(otherPoint: Point): Point; + + /** + * Returns the result of subtraction of the given point from the current. + */ + subtract(otherPoint: Point): Point; + + /** + * Returns the result of multiplication of the current point by the given number. + */ + multiplyBy(number: number): Point; + + /** + * Returns the result of division of the current point by the given number. If + * optional round is set to true, returns a rounded result. + */ + divideBy(number: number, round?: boolean): Point; + + /** + * Returns the distance between the current and the given points. + */ + distanceTo(otherPoint: Point): number; + + /** + * Returns a copy of the current point. + */ + clone(): Point; + + /** + * Returns a copy of the current point with rounded coordinates. + */ + round(): Point; + + /** + * Returns true if the given point has the same coordinates. + */ + equals(otherPoint: Point): boolean; + + /** + * Returns a string representation of the point for debugging purposes. + */ + toString(): string; + + /** + * The x coordinate. + */ + x: number; + + /** + * The y coordinate. + */ + y: number; + } +} + +declare namespace L { + + /** + * Instantiates a polygon object given an array of geographical points and + * optionally an options object (the same as for Polyline). You can also create + * a polygon with holes by passing an array of arrays of latlngs, with the first + * latlngs array representing the exterior ring while the remaining represent + * the holes inside. + */ + function polygon(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polygon; + + + export interface PolygonStatic extends ClassStatic { + /** + * Instantiates a polygon object given an array of geographical points and + * optionally an options object (the same as for Polyline). You can also create + * a polygon with holes by passing an array of arrays of latlngs, with the first + * latlngs array representing the exterior ring while the remaining represent + * the holes inside. + */ + new(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polygon; + } + export var Polygon: PolygonStatic; + + export interface Polygon extends Polyline { + } +} + +declare namespace L { + + /** + * Instantiates a polyline object given an array of geographical points and + * optionally an options object. + */ + function polyline(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polyline; + + export interface PolylineStatic extends ClassStatic { + /** + * Instantiates a polyline object given an array of geographical points and + * optionally an options object. + */ + new(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polyline; + } + export var Polyline: PolylineStatic; + + export interface Polyline extends Path { + /** + * Adds a given point to the polyline. + */ + addLatLng(latlng: LatLngExpression): Polyline; + + /** + * Replaces all the points in the polyline with the given array of geographical + * points. + */ + setLatLngs(latlngs: LatLngBoundsExpression): Polyline; + + /** + * Returns an array of the points in the path. + */ + getLatLngs(): LatLng[]; + + /** + * Allows adding, removing or replacing points in the polyline. Syntax is the + * same as in Array#splice. Returns the array of removed points (if any). + */ + spliceLatLngs(index: number, pointsToRemove: number, ...latlngs: LatLng[]): LatLng[]; + + /** + * Returns the LatLngBounds of the polyline. + */ + getBounds(): LatLngBounds; + + /** + * Returns a GeoJSON representation of the polyline (GeoJSON LineString Feature). + */ + toGeoJSON(): GeoJSON.Feature; + } +} + +declare namespace L { + + export interface PolylineOptions extends PathOptions { + + /** + * How much to simplify the polyline on each zoom level. More means better performance + * and smoother look, and less means more accurate representation. + * + * Default value: 1.0. + */ + smoothFactor?: number; + + /** + * Disabled polyline clipping. + * + * Default value: false. + */ + noClip?: boolean; + } +} + +declare namespace L { + + namespace PolyUtil { + + /** + * Clips the polygon geometry defined by the given points by rectangular bounds. + * Used by Leaflet to only show polygon points that are on the screen or near, + * increasing performance. Note that polygon points needs different algorithm + * for clipping than polyline, so there's a seperate method for it. + */ + export function clipPolygon(points: Point[], bounds: Bounds): Point[]; + } +} + +declare namespace L { + + /** + * Instantiates a Popup object given an optional options object that describes + * its appearance and location and an optional object that is used to tag the + * popup with a reference to the source object to which it refers. + */ + function popup(options?: PopupOptions, source?: any): Popup; + + export interface PopupStatic extends ClassStatic { + /** + * Instantiates a Popup object given an optional options object that describes + * its appearance and location and an optional object that is used to tag the + * popup with a reference to the source object to which it refers. + */ + new(options?: PopupOptions, source?: any): Popup; + } + export var Popup: PopupStatic; + + export interface Popup extends ILayer { + /** + * Adds the popup to the map. + */ + addTo(map: Map): Popup; + + /** + * Adds the popup to the map and closes the previous one. The same as map.openPopup(popup). + */ + openOn(map: Map): Popup; + + /** + * Sets the geographical point where the popup will open. + */ + setLatLng(latlng: LatLngExpression): Popup; + + /** + * Returns the geographical point of popup. + */ + getLatLng(): LatLng; + + /** + * Sets the HTML content of the popup. + */ + setContent(html: string): Popup; + + /** + * Sets the HTML content of the popup. + */ + setContent(el: HTMLElement): Popup; + + /** + * Returns the content of the popup. + */ + getContent(): HTMLElement; + //getContent(): string; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + /** + * Updates the popup content, layout and position. Useful for updating the popup after + * something inside changed, e.g. image loaded. + */ + update(): Popup; + } +} + +declare namespace L { + + export interface PopupOptions { + + /** + * Max width of the popup. + * + * Default value: 300. + */ + maxWidth?: number; + + /** + * Min width of the popup. + * + * Default value: 50. + */ + minWidth?: number; + + /** + * If set, creates a scrollable container of the given height inside a popup + * if its content exceeds it. + */ + maxHeight?: number; + + /** + * Set it to false if you don't want the map to do panning animation to fit the opened + * popup. + * + * Default value: true. + */ + autoPan?: boolean; + + /** + * Set it to true if you want to prevent users from panning the popup off of the screen while it is open. + */ + keepInView?: boolean; + + /** + * Controls the presense of a close button in the popup. + * + * Default value: true. + */ + closeButton?: boolean; + + /** + * The offset of the popup position. Useful to control the anchor of the popup + * when opening it on some overlays. + * + * Default value: new Point(0, 6). + */ + offset?: Point; + + /** + * The margin between the popup and the top left corner of the map view after + * autopanning was performed. + * + * Default value: null. + */ + autoPanPaddingTopLeft?: Point; + + /** + * The margin between the popup and the bottom right corner of the map view after + * autopanning was performed. + * + * Default value: null. + */ + autoPanPaddingBottomRight?: Point; + + /** + * The margin between the popup and the edges of the map view after autopanning + * was performed. + * + * Default value: new Point(5, 5). + */ + autoPanPadding?: Point; + + /** + * Whether to animate the popup on zoom. Disable it if you have problems with + * Flash content inside popups. + * + * Default value: true. + */ + zoomAnimation?: boolean; + + /** + * Set it to false if you want to override the default behavior of the popup + * closing when user clicks the map (set globally by the Map closePopupOnClick + * option). + */ + closeOnClick?: boolean; + + /** + * A custom class name to assign to the popup. + */ + className?: string; + } +} + +declare namespace L { + + export interface PosAnimationStatic extends ClassStatic { + /** + * Creates a PosAnimation object. + */ + new(): PosAnimation; + } + export var PosAnimation: PosAnimationStatic; + + export interface PosAnimation extends IEventPowered { + /** + * Run an animation of a given element to a new position, optionally setting + * duration in seconds (0.25 by default) and easing linearity factor (3rd argument + * of the cubic bezier curve, 0.5 by default) + */ + run(element: HTMLElement, newPos: Point, duration?: number, easeLinearity?: number): PosAnimation; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): PosAnimation; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): PosAnimation; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): PosAnimation; + fire(type: string, data?: any): PosAnimation; + addEventListener(eventMap: any, context?: any): PosAnimation; + removeEventListener(eventMap?: any, context?: any): PosAnimation; + clearAllEventListeners(): PosAnimation; + on(eventMap: any, context?: any): PosAnimation; + off(eventMap?: any, context?: any): PosAnimation; + } +} + +declare namespace L { + + namespace Projection { + + /** + * Spherical Mercator projection — the most common projection for online maps, + * used by almost all free and commercial tile providers. Assumes that Earth + * is a sphere. Used by the EPSG:3857 CRS. + */ + export var SphericalMercator: IProjection; + + /** + * Elliptical Mercator projection — more complex than Spherical Mercator. + * Takes into account that Earth is a geoid, not a perfect sphere. Used by the + * EPSG:3395 CRS. + */ + export var Mercator: IProjection; + + /** + * Equirectangular, or Plate Carree projection — the most simple projection, + * mostly used by GIS enthusiasts. Directly maps x as longitude, and y as latitude. + * Also suitable for flat worlds, e.g. game maps. Used by the EPSG:3395 and Simple + * CRS. + */ + export var LonLat: IProjection; + } +} + +declare namespace L { + + /** + * Instantiates a rectangle object with the given geographical bounds and + * optionally an options object. + */ + function rectangle(bounds: LatLngBounds, options?: PathOptions): Rectangle; + + export interface RectangleStatic extends ClassStatic { + /** + * Instantiates a rectangle object with the given geographical bounds and + * optionally an options object. + */ + new(bounds: LatLngBounds, options?: PathOptions): Rectangle; + } + export var Rectangle: RectangleStatic; + + export interface Rectangle extends Polygon { + /** + * Redraws the rectangle with the passed bounds. + */ + setBounds(bounds: LatLngBounds): Rectangle; + } +} + + +declare namespace L { + + export interface ScaleOptions { + + /** + * The position of the control (one of the map corners). See control positions. + * Default value: 'bottomleft'. + */ + position?: PositionString; + + /** + * Maximum width of the control in pixels. The width is set dynamically to show + * round values (e.g. 100, 200, 500). + * Default value: 100. + */ + maxWidth?: number; + + /** + * Whether to show the metric scale line (m/km). + * Default value: true. + */ + metric?: boolean; + + /** + * Whether to show the imperial scale line (mi/ft). + * Default value: true. + */ + imperial?: boolean; + + /** + * If true, the control is updated on moveend, otherwise it's always up-to-date + * (updated on move). + * Default value: false. + */ + updateWhenIdle?: boolean; + } +} + +declare namespace L { + + export interface TileLayerStatic extends ClassStatic { + /** + * Instantiates a tile layer object given a URL template and optionally an options + * object. + */ + new(urlTemplate: string, options?: TileLayerOptions): TileLayer; + + WMS: { + /** + * Instantiates a WMS tile layer object given a base URL of the WMS service and + * a WMS parameters/options object. + */ + new(baseUrl: string, options: WMSOptions): TileLayer.WMS; + }; + + Canvas: { + /** + * Instantiates a Canvas tile layer object given an options object (optionally). + */ + new(options?: TileLayerOptions): TileLayer.Canvas; + }; + } + export var TileLayer: TileLayerStatic; + + export interface TileLayer extends ILayer, IEventPowered { + /** + * Adds the layer to the map. + */ + addTo(map: Map): TileLayer; + + /** + * Brings the tile layer to the top of all tile layers. + */ + bringToFront(): TileLayer; + + /** + * Brings the tile layer to the bottom of all tile layers. + */ + bringToBack(): TileLayer; + + /** + * Changes the opacity of the tile layer. + */ + setOpacity(opacity: number): TileLayer; + + /** + * Sets the zIndex of the tile layer. + */ + setZIndex(zIndex: number): TileLayer; + + /** + * Causes the layer to clear all the tiles and request them again. + */ + redraw(): TileLayer; + + /** + * Updates the layer's URL template and redraws it. + */ + setUrl(urlTemplate: string): TileLayer; + + /** + * Returns the HTML element that contains the tiles for this layer. + */ + getContainer(): HTMLElement; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): TileLayer; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): TileLayer; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): TileLayer; + fire(type: string, data?: any): TileLayer; + addEventListener(eventMap: any, context?: any): TileLayer; + removeEventListener(eventMap?: any, context?: any): TileLayer; + clearAllEventListeners(): TileLayer; + on(eventMap: any, context?: any): TileLayer; + off(eventMap?: any, context?: any): TileLayer; + } + + namespace TileLayer { + export interface WMS extends TileLayer { + /** + * Merges an object with the new parameters and re-requests tiles on the current + * screen (unless noRedraw was set to true). + */ + setParams(params: WMS, noRedraw?: boolean): WMS; + } + + export interface Canvas extends TileLayer { + /** + * You need to define this method after creating the instance to draw tiles; + * canvas is the actual canvas tile on which you can draw, tilePoint represents + * the tile numbers, and zoom is the current zoom. + */ + drawTile(canvas: HTMLCanvasElement, tilePoint: Point, zoom: number): Canvas; + + /** + * Calling redraw will cause the drawTile method to be called for all tiles. + * May be used for updating dynamic content drawn on the Canvas + */ + redraw(): Canvas; + } + } + + export interface TileLayerFactory { + + /** + * Instantiates a tile layer object given a URL template and optionally an options + * object. + */ + (urlTemplate: string, options?: TileLayerOptions): TileLayer; + + /** + * Instantiates a WMS tile layer object given a base URL of the WMS service and + * a WMS parameters/options object. + */ + wms(baseUrl: string, options: WMSOptions): L.TileLayer.WMS; + + /** + * Instantiates a Canvas tile layer object given an options object (optionally). + */ + canvas(options?: TileLayerOptions): L.TileLayer.Canvas; + } + + export var tileLayer: TileLayerFactory; +} + +declare namespace L { + + export interface TileLayerOptions { + + /** + * Minimum zoom number. + * + * Default value: 0. + */ + minZoom?: number; + + /** + * Maximum zoom number. + * + * Default value: 18. + */ + maxZoom?: number; + + /** + * Maximum zoom number the tiles source has available. If it is specified, + * the tiles on all zoom levels higher than maxNativeZoom will be loaded from + * maxZoom level and auto-scaled. + * + * Default value: null. + */ + maxNativeZoom?: number; + + /** + * Tile size (width and height in pixels, assuming tiles are square). + * + * Default value: 256. + */ + tileSize?: number; + + /** + * Subdomains of the tile service. Can be passed in the form of one string (where + * each letter is a subdomain name) or an array of strings. + * + * Default value: 'abc'. + */ + subdomains?: string|string[]; + + /** + * URL to the tile image to show in place of the tile that failed to load. + * + * Default value: ''. + */ + errorTileUrl?: string; + + /** + * e.g. "© CloudMade" — the string used by the attribution control, describes + * the layer data. + * + * Default value: ''. + */ + attribution?: string; + + /** + * If true, inverses Y axis numbering for tiles (turn this on for TMS services). + * + * Default value: false. + */ + tms?: boolean; + + /** + * If set to true, the tile coordinates won't be wrapped by world width (-180 + * to 180 longitude) or clamped to lie within world height (-90 to 90). Use this + * if you use Leaflet for maps that don't reflect the real world (e.g. game, indoor + * or photo maps). + * + * Default value: false. + */ + continuousWorld?: boolean; + + /** + * If set to true, the tiles just won't load outside the world width (-180 to 180 + * longitude) instead of repeating. + * + * Default value: false. + */ + noWrap?: boolean; + + /** + * The zoom number used in tile URLs will be offset with this value. + * + * Default value: 0. + */ + zoomOffset?: number; + + /** + * If set to true, the zoom number used in tile URLs will be reversed (maxZoom + * - zoom instead of zoom) + * + * Default value: false. + */ + zoomReverse?: boolean; + + /** + * The opacity of the tile layer. + * + * Default value: 1.0. + */ + opacity?: number; + + /** + * The explicit zIndex of the tile layer. Not set by default. + */ + zIndex?: number; + + /** + * If true, all the tiles that are not visible after panning are removed (for + * better performance). true by default on mobile WebKit, otherwise false. + */ + unloadInvisibleTiles?: boolean; + + /** + * If false, new tiles are loaded during panning, otherwise only after it (for + * better performance). true by default on mobile WebKit, otherwise false. + */ + updateWhenIdle?: boolean; + + /** + * If true and user is on a retina display, it will request four tiles of half the + * specified size and a bigger zoom level in place of one to utilize the high resolution. + * + * Default value: false. + */ + detectRetina?: boolean; + + /** + * If true, all the tiles that are not visible after panning are placed in a reuse + * queue from which they will be fetched when new tiles become visible (as opposed + * to dynamically creating new ones). This will in theory keep memory usage + * low and eliminate the need for reserving new memory whenever a new tile is + * needed. + * + * Default value: false. + */ + reuseTiles?: boolean; + + /** + * When this option is set, the TileLayer only loads tiles that are in the given geographical bounds. + */ + bounds?: LatLngBounds; + + /** + * Custom keys may be specified in TileLayerOptions so they can be used in a provided URL template. + */ + [additionalKeys: string]: any; + } +} + +declare namespace L { + export interface TransformationStatic { + /** + * Creates a transformation object with the given coefficients. + */ + new(a: number, b: number, c: number, d: number): Transformation; + } + export var Transformation: TransformationStatic; + + export interface Transformation { + /** + * Returns a transformed point, optionally multiplied by the given scale. + * Only accepts real L.Point instances, not arrays. + */ + transform(point: Point, scale?: number): Point; + + /** + * Returns the reverse transformation of the given point, optionally divided + * by the given scale. Only accepts real L.Point instances, not arrays. + */ + untransform(point: Point, scale?: number): Point; + } +} + +declare namespace L { + + namespace Util { + + /** + * Merges the properties of the src object (or multiple objects) into dest object + * and returns the latter. Has an L.extend shortcut. + */ + export function extend(dest: any, ...sources: any[]): any; + + /** + * Returns a function which executes function fn with the given scope obj (so + * that this keyword refers to obj inside the function code). Has an L.bind shortcut. + */ + export function bind(fn: T, obj: any): T; + + /** + * Applies a unique key to the object and returns that key. Has an L.stamp shortcut. + */ + export function stamp(obj: any): string; + + /** + * Returns a wrapper around the function fn that makes sure it's called not more + * often than a certain time interval time, but as fast as possible otherwise + * (for example, it is used for checking and requesting new tiles while dragging + * the map), optionally passing the scope (context) in which the function will + * be called. + */ + export function limitExecByInterval(fn: T, time: number, context?: any): T; + + /** + * Returns a function which always returns false. + */ + export function falseFn(): () => boolean; + + /** + * Returns the number num rounded to digits decimals. + */ + export function formatNum(num: number, digits: number): number; + + /** + * Trims and splits the string on whitespace and returns the array of parts. + */ + export function splitWords(str: string): string[]; + + /** + * Merges the given properties to the options of the obj object, returning the + * resulting options. See Class options. Has an L.setOptions shortcut. + */ + export function setOptions(obj: any, options: any): any; + + /** + * Converts an object into a parameter URL string, e.g. {a: "foo", b: "bar"} + * translates to '?a=foo&b=bar'. + */ + export function getParamString(obj: any): string; + + /** + * Simple templating facility, creates a string by applying the values of the + * data object of a form {a: 'foo', b: 'bar', …} to a template string of the form + * 'Hello {a}, {b}' — in this example you will get 'Hello foo, bar'. + */ + export function template(str: string, data: any): string; + + /** + * Returns true if the given object is an array. + */ + export function isArray(obj: any): boolean; + + /** + * Trims the whitespace from both ends of the string and returns the result. + */ + export function trim(str: string): string; + + /** + * Data URI string containing a base64-encoded empty GIF image. Used as a hack + * to free memory from unused images on WebKit-powered mobile devices (by setting + * image src to this string). + */ + export var emptyImageUrl: string; + } +} + + +declare namespace L { + + export interface WMSOptions { + + /** + * (required) Comma-separated list of WMS layers to show. + * + * Default value: ''. + */ + layers?: string; + + /** + * Comma-separated list of WMS styles. + * + * Default value: 'image/jpeg'. + */ + styles?: string; + + /** + * WMS image format (use 'image/png' for layers with transparency). + * + * Default value: false. + */ + format?: string; + + /** + * If true, the WMS service will return images with transparency. + * + * Default value: '1.1.1'. + */ + transparent?: boolean; + + /** + * Version of the WMS service to use. + */ + version?: string; + + } +} + +/** + * Forces Leaflet to use the Canvas back-end (if available) for vector layers + * instead of SVG. This can increase performance considerably in some cases + * (e.g. many thousands of circle markers on the map). + */ +declare var L_PREFER_CANVAS: boolean; + +/** + * Forces Leaflet to not use touch events even if it detects them. + */ +declare var L_NO_TOUCH: boolean; + +/** + * Forces Leaflet to not use hardware-accelerated CSS 3D transforms for positioning + * (which may cause glitches in some rare environments) even if they're supported. + */ +declare var L_DISABLE_3D: boolean; + +declare module "leaflet" { + export = L; +} + +// vim: et ts=4 sw=4 diff --git a/leaflet/leaflet-tests.ts b/leaflet/leaflet-tests.ts index b0568b216a..9b07b8fd03 100644 --- a/leaflet/leaflet-tests.ts +++ b/leaflet/leaflet-tests.ts @@ -1,427 +1,267 @@ /// -// initialize the map on the "map" div with a given center and zoom - -var div = document.getElementById('map'); - -var map : L.Map = L.map(div, { - center: L.latLng([51.505, -0.09]), - zoom: 13, - minZoom: 3, - maxZoom: 8, - maxBounds: L.latLngBounds([L.latLng(-60, -60), L.latLng(60, 60)]), - dragging: true, - touchZoom: true, - scrollWheelZoom: true, - boxZoom: true, - tap: true, - - tapTolerance: 30, - trackResize: true, - worldCopyJump: false, - closePopupOnClick: true, - bounceAtZoomLimits: true, - - keyboard: true, - keyboardPanOffset: 80, - keyboardZoomOffset: 1, - - inertia: true, - inertiaDeceleration: 3000, - inertiaMaxSpeed: 1500, - inertiaThreshold: 32, - - zoomControl: true, - attributionControl: true, - - fadeAnimation: true, - zoomAnimation: true, - zoomAnimationThreshold: 4, - markerZoomAnimation: true - -}); - -map.dragging.enable(); -map.touchZoom.enable(); -map.scrollWheelZoom.enable(); -map.doubleClickZoom.enable(); -map.boxZoom.enable(); -map.tap.enable(); - -map.setView(new L.LatLng(42, 51)); -map.setView(L.latLng(42, 51)); - -map.setView(L.latLng(42, 51), 12); -map.setView(L.latLng(42, 51), 12, { - reset: true, - pan: { - animate: true, - duration: 0.25, - easeLinearity: 0.25, - noMoveStart: false - }, - zoom: { - animate: true - } -}); - -map.setZoom(50); -map.setZoom(50, {}); - -map.zoomIn(); -map.zoomOut(); - -map.zoomIn(2); -map.zoomOut(2); - -map.zoomIn(2, { animate: true }); -map.zoomOut(2, { animate: true }); - -map.setZoomAround(L.latLng(42, 51), 8, { animate: false }); - -map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20))); -map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20)), { - paddingTopLeft: L.point(20, 20), - paddingBottomRight: L.point(20, 20), - padding: L.point(0, 0), - maxZoom: null -}); - -map.fitWorld(); - -map.fitWorld({ - animate: false -}); - -map.panTo(L.latLng(42, 42)); -map.panTo(L.latLng(42, 42), { - animate: true -}); - -map.invalidateSize(true); -map.invalidateSize({ reset: true }); - -map.setMaxBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20))); - -map.locate(); -map.locate({ - watch: false, - setView: false, - maxZoom: 18, - timeout: 10000, - maximumAge: 0, - enableHighAccuracy: false -}); - -map.stopLocate(); - -map.remove(); - -var center : L.LatLng = map.getCenter(); -var zoom : number = map.getZoom(); -var minZoom: number = map.getMinZoom(); -var maxZoom: number = map.getMaxZoom(); -var bounds: L.LatLngBounds = map.getBounds(); -var boundsZoom: number = map.getBoundsZoom(bounds, true); -var size: L.Point = map.getSize(); -var pixelBounds: L.Bounds = map.getPixelBounds(); -var pixelOrigin: L.Point = map.getPixelOrigin(); - -var layer = L.tileLayer("http://{s}.example.net/{x}/{y}/{z}.png"); - -map.addLayer(layer); -map.addLayer(layer, false); -map.eachLayer(l => {}); - -map.removeLayer(layer); -map.hasLayer(layer); - -map.openPopup("canard", L.latLng(42, 51)); - -var popup = L.popup({ - autoPan: true -}); - -map.openPopup(popup); -map.closePopup(popup); -map.closePopup(); - -map.addControl(L.control.attribution({position: 'bottomright'})); -map.removeControl(L.control.attribution({ position: 'bottomright' })); - -L.control.layers({'Base': layer}).addTo(map); -map.on('baseLayerChange', function(e: L.LeafletLayersControlEvent) { - alert(e.name); -}); - -map.latLngToLayerPoint(map.layerPointToLatLng(L.point(0, 0))); -map.latLngToContainerPoint(map.containerPointToLatLng(L.point(0, 0))); -map.containerPointToLayerPoint(L.point(0, 0)); -map.layerPointToContainerPoint(L.point(0, 0)); - -map.project(map.unproject(L.point(10, 20))); -map.project(map.unproject(L.point(10, 20), 12), 12); - -var mouseEvent: L.LeafletMouseEvent; -map.mouseEventToContainerPoint(mouseEvent); -map.mouseEventToLayerPoint(mouseEvent); -map.mouseEventToLatLng(mouseEvent); - -map.getContainer().classList.add('roger'); -map.getPanes().mapPane.classList.add('roger'); -map.getPanes().markerPane.classList.add('roger'); -map.getPanes().objectsPane.classList.add('roger'); -map.getPanes().overlayPane.classList.add('roger'); -map.getPanes().popupPane.classList.add('roger'); -map.getPanes().shadowPane.classList.add('roger'); -map.getPanes().tilePane.classList.add('roger'); - -map.whenReady((m: L.Map) => { - m.zoomOut(); -}); - -map.on('click', () => { - map.zoomOut(); -}); - -map.off('dblclick', L.Util.falseFn); - -map.once('contextmenu', (e: L.LeafletMouseEvent) => { - map.openPopup('contextmenu', e.latlng); -}); - -var marker = L.marker(L.latLng(42, 51), { - icon: L.icon({ - iconUrl: 'roger.png', - iconRetinaUrl: 'roger-retina.png', - iconSize: L.point(40, 40), - iconAnchor: L.point(20, 0), - shadowUrl: 'roger-shadow.png', - shadowRetinaUrl: 'roger-shadow-retina.png', - shadowSize: L.point(44, 44), - shadowAnchor: L.point(22, 0), - popupAnchor: L.point(0, 0), - className: 'roger-icon' - }), - clickable: true, - draggable: false, - keyboard: true, - title: 'this is an icon', - alt: '', - zIndexOffset: 0, - opacity: 1.0, - riseOnHover: false, - riseOffset: 250 -}); - -marker.addTo(map); - -marker.on('click', (e: L.LeafletMouseEvent) => { - map.setView(e.latlng); -}); - -marker.once('mouseover', () => { - marker.openPopup(); -}) - -marker.setLatLng(marker.getLatLng()); - -marker.setIcon(L.icon({})); - -marker.setZIndexOffset(30); -marker.setOpacity(0.8); - -marker.bindPopup(popup); -marker.unbindPopup(); -marker.bindPopup('hello', { - closeOnClick: true -}); - -marker.openPopup(); -marker.closePopup(); -marker.togglePopup(); -marker.togglePopup(); -marker.setPopupContent('hello 3') -marker.getPopup().setContent('hello 2'); -marker.update(); - -marker.toGeoJSON(); - -marker.dragging.enable(); - -popup = L.popup({ - maxWidth: 300, - minWidth: 50, - maxHeight: null, - autoPan: true, - keepInView: false, - closeButton: true, - offset: L.point(0, 6), - autoPanPaddingTopLeft: null, - autoPanPaddingBottomRight: L.point(20, 20), - autoPanPadding: L.point(5, 5), - zoomAnimation: true, - closeOnClick: null, - className: 'roger' -}); - -popup.setLatLng(L.latLng(12, 54)).setContent('this is nice popup').openOn(map); - -popup.update(); - -var tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}', { - minZoom: 0, - maxZoom: 18, - maxNativeZoom: 17, - tileSize: 256, - subdomains: ['a','b','c'], - errorTileUrl: '', - attribution: '', - tms: false, - continuousWorld: false, - noWrap: false, - zoomOffset: 0, - zoomReverse: false, - opacity: 1.0, - zIndex: null, - unloadInvisibleTiles: false, - updateWhenIdle: false, - detectRetina: true, - reuseTiles: true, - bounds: null -}); - -tileLayer.on('loading', L.Util.falseFn) - .off('loading', L.Util.falseFn) - .once('tileload', L.Util.falseFn); - -tileLayer.addTo(map); - -tileLayer.bringToBack() - .bringToFront() - .setOpacity(0.7) - .setZIndex(9) - .redraw() - .setUrl('http://perdu.com') - .getContainer(); - -namespace CustomControl { - export interface Options { - title: string; - position?: string; - } -} -interface CustomControl extends L.Control { - getTitle(): string; - setTitle(title: string): CustomControl; -} -var CustomControl: { new(options: CustomControl.Options): CustomControl }; -CustomControl = L.Control.extend({ - initialize: function(options: CustomControl.Options) { - L.Control.prototype.initialize.call(this, { - position: options.position || 'bottomleft', - }); - this.title = options.title; - }, - getTitle: function() { - return this.title; - }, - setTitle: function(title: string) { - this.title = title; - }, -}); - -// Different latLng and latLngBounds expressions -var latLngLiteral = [10, 20]; -var latLngObjectLiteral = { lat: 10, lng: 10 }; -var boundsLiteral = [[10, 20], [20, 20]]; -var boundLiteralOfLatLngObjects = [latLngObjectLiteral, latLngObjectLiteral]; - -var circle: L.Circle = L.circle(latLngLiteral, 4); -circle = new L.Circle(latLngLiteral, 4); -circle.setLatLng(latLngLiteral); - -circle = L.circle(latLngObjectLiteral, 4); -circle = new L.Circle(latLngObjectLiteral, 4); -circle.setLatLng(latLngObjectLiteral); - -var circleMarker: L.CircleMarker = L.circleMarker(latLngLiteral); -circleMarker = new L.CircleMarker(latLngLiteral); -circleMarker.setLatLng(latLngLiteral); - -circleMarker = L.circleMarker(latLngObjectLiteral); -circleMarker = new L.CircleMarker(latLngObjectLiteral); -circleMarker.setLatLng(latLngObjectLiteral); - -var latLng: L.LatLng = L.latLng(latLngLiteral); -latLng = new L.LatLng(latLngLiteral); -latLng.distanceTo(latLngLiteral); -latLng.equals(latLngLiteral); - -latLng = L.latLng(latLngObjectLiteral); -latLng = new L.LatLng(latLngObjectLiteral); -latLng.distanceTo(latLngObjectLiteral); -latLng.equals(latLngObjectLiteral); - -var bounds: L.LatLngBounds = L.latLngBounds(boundsLiteral); -bounds = L.latLngBounds(boundLiteralOfLatLngObjects); -bounds = new L.LatLngBounds(boundsLiteral); -bounds = new L.LatLngBounds(boundLiteralOfLatLngObjects); -bounds = new L.LatLngBounds(latLngLiteral, latLngLiteral); - -bounds.extend(latLngLiteral); -bounds.extend(latLngObjectLiteral); -bounds.extend(boundsLiteral); -bounds.extend(boundLiteralOfLatLngObjects); - -bounds.contains(latLngLiteral); -bounds.contains(boundLiteralOfLatLngObjects); -bounds.contains(boundsLiteral); - -bounds.intersects(boundsLiteral); -bounds.intersects(boundLiteralOfLatLngObjects); - -bounds.equals(boundsLiteral); -bounds.equals(boundLiteralOfLatLngObjects); - -map.setView(latLngLiteral); -map.setView(latLngObjectLiteral); -map.setZoomAround(latLngLiteral, 15); -map.setZoomAround(latLngObjectLiteral, 15); -map.panTo(latLngLiteral); -map.panTo(latLngObjectLiteral); -map.openPopup('test', latLngLiteral); -map.openPopup('test', latLngObjectLiteral); -map.latLngToLayerPoint(latLngLiteral); -map.latLngToLayerPoint(latLngObjectLiteral); -map.latLngToContainerPoint(latLngLiteral); -map.latLngToContainerPoint(latLngObjectLiteral); -map.project(latLngLiteral); -map.project(latLngObjectLiteral); - -marker.setLatLng(latLngLiteral); -marker.setLatLng(latLngObjectLiteral); - -var polygon: L.Polygon = L.polygon(boundsLiteral); -polygon = L.polygon(boundLiteralOfLatLngObjects); -polygon = new L.Polygon(boundsLiteral); -polygon = new L.Polygon(boundLiteralOfLatLngObjects); - -var polyline: L.Polyline = L.polyline(boundsLiteral); -polyline = L.polyline(boundLiteralOfLatLngObjects); -polyline = new L.Polyline(boundsLiteral); -polyline = new L.Polyline(boundLiteralOfLatLngObjects); -polyline.setLatLngs(boundsLiteral); -polyline.setLatLngs(boundLiteralOfLatLngObjects); -polyline.addLatLng(latLngLiteral); -polyline.addLatLng(latLngObjectLiteral); - -var popup: L.Popup = L.popup(); -popup.setLatLng(latLngLiteral); -popup.setLatLng(latLngObjectLiteral); - -var zoomCtrl = L.control.zoom({ - position: "topleft", - zoomInText: '+', - zoomOutText: '-' -}); +import L = require('leaflet'); + +const latLngLiteral: L.LatLngLiteral = {lat: 12, lng: 13}; +const latLngTuple: L.LatLngTuple = [12, 13]; + +let latLng: L.LatLng; +latLng = L.latLng(12, 13); +latLng = L.latLng(12, 13, 0); +latLng = L.latLng(latLngLiteral); +latLng = L.latLng({lat: 12, lng: 13, alt: 0}); +latLng = L.latLng(latLngTuple); +latLng = L.latLng([12, 13, 0]); + +const latLngBoundsLiteral: L.LatLngBoundsLiteral = [[12, 13], latLngTuple]; + +let latLngBounds: L.LatLngBounds; +latLngBounds = L.latLngBounds(latLng, latLng); +latLngBounds = L.latLngBounds(latLngLiteral, latLngLiteral); +latLngBounds = L.latLngBounds(latLngTuple, latLngTuple); + +const pointTuple: L.PointTuple = [0, 0]; + +let point: L.Point; +point = L.point(12, 13); +point = L.point(12, 13, true); +point = L.point(pointTuple); +point = L.point({x: 12, y: 13}); + +const boundsLiteral: L.BoundsLiteral = [[1, 1], pointTuple]; + +let bounds: L.Bounds; +bounds = L.bounds(point, point); +bounds = L.bounds(pointTuple, pointTuple); +bounds = L.bounds([point, point]); +bounds = L.bounds(boundsLiteral); + +let mapOptions: L.MapOptions = {}; +mapOptions = { + preferCanvas: true, + attributionControl: false, + zoomControl: true, + closePopupOnClick: false, + zoomSnap: 1, + zoomDelta: 1, + trackResize: false, + boxZoom: true, + dragging: true, + // CRS + zoom: 12, + minZoom: 10, + maxZoom: 14, + fadeAnimation: true, + markerZoomAnimation: false, + transform3DLimit: 123, + zoomAnimation: false, + zoomAnimationThreshold: 4, + inertia: false, + inertiaDeceleration: 2000, + inertiaMaxSpeed: 1000, + easeLinearity: 0.5, + worldCopyJump: true, + maxBoundsViscosity: 1.0, + keyboard: false, + keyboardPanDelta: 100, + wheelDebounceTime: 30, + wheelPxPerZoomLevel: 25, + tap: false, + tapTolerance: 10, + bounceAtZoomLimits: false +}; + +mapOptions.doubleClickZoom = true; +mapOptions.doubleClickZoom = 'center'; + +mapOptions.center = latLng; +mapOptions.center = latLngLiteral; +mapOptions.center = latLngTuple; + +mapOptions.layers = []; +mapOptions.layers = [L.tileLayer('')]; // add layers of other types + +mapOptions.maxBounds = latLngBounds; +mapOptions.maxBounds = []; +mapOptions.maxBounds = latLngBoundsLiteral; + +// mapOptions.renderer = ? + +mapOptions.scrollWheelZoom = true; +mapOptions.scrollWheelZoom = 'center'; + +mapOptions.touchZoom = false; +mapOptions.touchZoom = 'center'; + +let layer: L.Layer; + +const htmlElement = document.getElementById('foo'); + +let popupOptions: L.PopupOptions = {}; + +let tooltipOptions: L.TooltipOptions = {}; + +let zoomPanOptions: L.ZoomPanOptions = {}; +zoomPanOptions = { + animate: false, + duration: 0.5, + easeLinearity: 0.6, + noMoveStart: true +}; + +let zoomOptions: L.ZoomOptions = {}; + +let panOptions: L.PanOptions = {}; + +let fitBoundsOptions: L.FitBoundsOptions = {}; + +let map = L.map('foo'); +map = L.map('foo', mapOptions); +map = L.map(htmlElement); +map = L.map(htmlElement, mapOptions); + +let doesItHaveLayer: boolean; +doesItHaveLayer = map.hasLayer(L.tileLayer('')); + +// map.getRenderer + +let html: HTMLElement; +html = map.createPane('foo'); +html = map.createPane('foo', htmlElement) +html = map.getPane('foo'); +html = map.getPane(htmlElement); +html = map.getContainer(); + +const panes = map.getPanes(); +html = panes.mapPane; +html = panes.tilePane; +html = panes.overlayPane; +html = panes.shadowPane; +html = panes.markerPane; +html = panes.tooltipPane; +html = panes.popupPane; +html = panes['foo']; + +let coordinates: L.LatLng; +coordinates = map.getCenter(); + +let zoom: number; +zoom = map.getZoom(); +zoom = map.getMinZoom(); +zoom = map.getMaxZoom(); +zoom = map.getBoundsZoom(latLngBounds); +zoom = map.getBoundsZoom(latLngBounds, true); +zoom = map.getBoundsZoom(latLngBoundsLiteral); +zoom = map.getBoundsZoom(latLngBoundsLiteral, true); + +let mapLatLngBounds: L.LatLngBounds; +mapLatLngBounds = map.getBounds(); + +let mapPoint: L.Point; +mapPoint = map.getSize(); +mapPoint = map.getPixelOrigin(); + +let mapPixelBounds: L.Bounds; +mapPixelBounds = map.getPixelBounds(); +mapPixelBounds = map.getPixelWorldBounds(); +mapPixelBounds = map.getPixelWorldBounds(12); + +map = map + // addControl + // removeControl + .addLayer(L.tileLayer('')) + .removeLayer(L.tileLayer('')) // use a different type of layer + .eachLayer((currentLayer) => { + layer = currentLayer; + }) + .eachLayer((currentLayer) => { + layer = currentLayer; + }, {}) + .openPopup(L.popup()) + .openPopup('Hello World', latLng) + .openPopup('Hello World', latLng, popupOptions) + .openPopup('Hello World', latLngLiteral) + .openPopup('Hello World', latLngLiteral, popupOptions) + .openPopup('Hello World', latLngTuple) + .openPopup('Hello World', latLngTuple, popupOptions) + .openPopup(htmlElement, latLng) + .openPopup(htmlElement, latLng, popupOptions) + .openPopup(htmlElement, latLngLiteral) + .openPopup(htmlElement, latLngLiteral, popupOptions) + .openPopup(htmlElement, latLngTuple) + .openPopup(htmlElement, latLngTuple, popupOptions) + .closePopup() + .closePopup(L.popup()) + .openTooltip(L.tooltip()) + .openTooltip('Hello Word', latLng) + .openTooltip('Hello World', latLng, tooltipOptions) + .openTooltip('Hello World', latLngLiteral) + .openTooltip('Hello World', latLngLiteral, tooltipOptions) + .openTooltip('Hello World', latLngTuple) + .openTooltip('Hello World', latLngTuple, tooltipOptions) + .openTooltip(htmlElement, latLng) + .openTooltip(htmlElement, latLng, tooltipOptions) + .openTooltip(htmlElement, latLngLiteral) + .openTooltip(htmlElement, latLngLiteral, tooltipOptions) + .openTooltip(htmlElement, latLngTuple) + .openTooltip(htmlElement, latLngTuple, tooltipOptions) + .closeTooltip() + .closeTooltip(L.tooltip()) + .setView(latLng, 12) + .setView(latLng, 12, zoomPanOptions) + .setView(latLngLiteral, 12) + .setView(latLngLiteral, 12, zoomPanOptions) + .setView(latLngTuple, 12) + .setView(latLngTuple, 12, zoomPanOptions) + .setZoom(12, zoomPanOptions) // investigate if zoomPanOptions are really required + .zoomIn() + .zoomIn(1) + .zoomIn(1, zoomOptions) + .zoomOut() + .zoomOut(1) + .zoomOut(1, zoomOptions) + .setZoomAround(latLng, 12, zoomOptions) // investigate if zoom options are really required + .setZoomAround(latLngLiteral, 12, zoomOptions) + .setZoomAround(latLngTuple, 12, zoomOptions) + .setZoomAround(point, 12, zoomOptions) + .setZoomAround(pointTuple, 11, zoomOptions) + .fitBounds(latLngBounds, fitBoundsOptions) // investigate if fit bounds options are really required + .fitBounds(latLngBoundsLiteral, fitBoundsOptions) + .fitWorld() + .fitWorld(fitBoundsOptions) + .panTo(latLng) + .panTo(latLng, panOptions) + .panTo(latLngLiteral) + .panTo(latLngLiteral, panOptions) + .panTo(latLngTuple) + .panTo(latLngTuple, panOptions) + .panBy(point) + .panBy(pointTuple) + .setMaxBounds(bounds) // investigate if this really receives Bounds instead of LatLngBounds + .setMaxBounds(boundsLiteral) + .setMinZoom(5) + .setMaxZoom(10) + .panInsideBounds(latLngBounds) + .panInsideBounds(latLngBounds, panOptions) + .panInsideBounds(latLngBoundsLiteral) + .panInsideBounds(latLngBoundsLiteral, panOptions) + .invalidateSize(zoomPanOptions) + .invalidateSize(false) + .stop() + .flyTo(latLng) + .flyTo(latLng, 12) + .flyTo(latLng, 12, zoomOptions) + .flyTo(latLngLiteral) + .flyTo(latLngLiteral, 12) + .flyTo(latLngLiteral, 12, zoomPanOptions) + .flyTo(latLngTuple) + .flyTo(latLngTuple, 12) + .flyTo(latLngTuple, 12, zoomPanOptions) + .flyToBounds(latLngBounds) + .flyToBounds(latLngBounds, fitBoundsOptions) + .flyToBounds(latLngBoundsLiteral) + .flyToBounds(latLngBoundsLiteral, fitBoundsOptions) + // addHandler + .remove() + .whenReady(() => {}) + .whenReady(() => {}, {}); diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 3bf19a1771..87f33576e6 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -1,4382 +1,927 @@ -// Type definitions for Leaflet.js 1.0.0 +// Type definitions for Leaflet.js 1.0.0-rc3 // Project: https://github.com/Leaflet/Leaflet -// Definitions by: Vladimir Zotov +// Definitions by: Alejandro Sánchez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - declare namespace L { - type LatLngExpression = LatLng | number[] | ({ lat: number; lng: number }) - type LatLngBoundsExpression = LatLngBounds | LatLngExpression[]; - type PositionString = 'topleft' | 'topright' | 'bottomleft' | 'bottomright'; -} - -declare namespace L { - - export interface AttributionOptions { - - /** - * The position of the control (one of the map corners). See control positions. - * Default value: 'bottomright'. - */ - position?: PositionString; - - /** - * The HTML text shown before the attributions. Pass false to disable. - * Default value: 'Powered by Leaflet'. - */ - prefix?: string; - - } -} - -declare namespace L { - - /** - * Creates a Bounds object from two coordinates (usually top-left and bottom-right - * corners). - */ - export function bounds(topLeft: Point, bottomRight: Point): Bounds; - - /** - * Creates a Bounds object defined by the points it contains. - */ - export function bounds(points: Point[]): Bounds; - - - export interface BoundsStatic { - /** - * Creates a Bounds object from two coordinates (usually top-left and bottom-right - * corners). - */ - new(topLeft: Point, bottomRight: Point): Bounds; - - /** - * Creates a Bounds object defined by the points it contains. - */ - new(points: Point[]): Bounds; - } - export var Bounds: BoundsStatic; - - export interface Bounds { - /** - * Extends the bounds to contain the given point. - */ - extend(point: Point): void; - - /** - * Returns the center point of the bounds. - */ - getCenter(): Point; - - /** - * Returns true if the rectangle contains the given one. - */ - contains(otherBounds: Bounds): boolean; - - /** - * Returns true if the rectangle contains the given point. - */ - contains(point: Point): boolean; - - /** - * Returns true if the rectangle intersects the given bounds. - */ - intersects(otherBounds: Bounds): boolean; - - /** - * Returns true if the bounds are properly initialized. - */ - isValid(): boolean; - - /** - * Returns the size of the given bounds. - */ - getSize(): Point; - - /** - * The top left corner of the rectangle. - */ - min: Point; - - /** - * The bottom right corner of the rectangle. - */ - max: Point; - } -} - -declare namespace L { - - namespace Browser { - - /** - * true for all Internet Explorer versions. - */ - export var ie: boolean; - - /** - * true for Internet Explorer 6. - */ - export var ie6: boolean; - - /** - * true for Internet Explorer 6. - */ - export var ie7: boolean; - - /** - * true for webkit-based browsers like Chrome and Safari (including mobile - * versions). - */ - export var webkit: boolean; - - /** - * true for webkit-based browsers that support CSS 3D transformations. - */ - export var webkit3d: boolean; - - /** - * true for Android mobile browser. - */ - export var android: boolean; - - /** - * true for old Android stock browsers (2 and 3). - */ - export var android23: boolean; - - /** - * true for modern mobile browsers (including iOS Safari and different Android - * browsers). - */ - export var mobile: boolean; - - /** - * true for mobile webkit-based browsers. - */ - export var mobileWebkit: boolean; - - /** - * true for mobile Opera. - */ - export var mobileOpera: boolean; - - /** - * true for all browsers on touch devices. - */ - export var touch: boolean; - - /** - * true for browsers with Microsoft touch model (e.g. IE10). - */ - export var msTouch: boolean; - - /** - * true for devices with Retina screens. - */ - export var retina: boolean; - - } -} - - -declare namespace L { - - /** - * Instantiates a circle object given a geographical point, a radius in meters - * and optionally an options object. - */ - function circle(latlng: LatLngExpression, radius: number, options?: PathOptions): Circle; - - export interface CircleStatic extends ClassStatic { - /** - * Instantiates a circle object given a geographical point, a radius in meters - * and optionally an options object. - */ - new(latlng: LatLngExpression, radius: number, options?: PathOptions): Circle; - } - export var Circle: CircleStatic; - - export interface Circle extends Path { - /** - * Returns the current geographical position of the circle. - */ - getLatLng(): LatLng; - - /** - * Returns the current radius of a circle. Units are in meters. - */ - getRadius(): number; - - /** - * Sets the position of a circle to a new location. - */ - setLatLng(latlng: LatLngExpression): Circle; - - /** - * Sets the radius of a circle. Units are in meters. - */ - setRadius(radius: number): Circle; - - /** - * Returns a GeoJSON representation of the circle (GeoJSON Point Feature). - */ - toGeoJSON(): GeoJSON.Feature; - - } -} - -declare namespace L { - - /** - * Instantiates a circle marker given a geographical point and optionally - * an options object. The default radius is 10 and can be altered by passing a - * "radius" member in the path options object. - */ - function circleMarker(latlng: LatLngExpression, options?: PathOptions): CircleMarker; - - - export interface CircleMarkerStatic extends ClassStatic { - /** - * Instantiates a circle marker given a geographical point and optionally - * an options object. The default radius is 10 and can be altered by passing a - * "radius" member in the path options object. - */ - new(latlng: LatLngExpression, options?: PathOptions): CircleMarker; - } - export var CircleMarker: CircleMarkerStatic; - - export interface CircleMarker extends Circle { - /** - * Sets the position of a circle marker to a new location. - */ - setLatLng(latlng: LatLngExpression): CircleMarker; - - /** - * Sets the radius of a circle marker. Units are in pixels. - */ - setRadius(radius: number): CircleMarker; - } -} - -declare namespace L { - export interface ClassExtendOptions { - /** - * Your class's constructor function, meaning that it gets called when you do 'new MyClass(...)'. - */ - initialize?: Function; - - /** - * options is a special property that unlike other objects that you pass - * to extend will be merged with the parent one instead of overriding it - * completely, which makes managing configuration of objects and default - * values convenient. - */ - options?: any; - - /** - * includes is a special class property that merges all specified objects - * into the class (such objects are called mixins). A good example of this - * is L.Mixin.Events that event-related methods like on, off and fire - * to the class. - */ - includes?: any; - - /** - * statics is just a convenience property that injects specified object - * properties as the static properties of the class, useful for defining - * constants. - */ - static?: any; - - [prop: string]: any; - } - - export interface ClassStatic { - /** - * You use L.Class.extend to define new classes, but you can use the - * same method on any class to inherit from it. - */ - extend(options: ClassExtendOptions): any; - extend(options: ClassExtendOptions): { new(options?: Options): NewClass }; - - /** - * You can also use the following shortcut when you just need to make - * one additional method call. - */ - addInitHook(methodName: string, ...args: any[]): void; - } - - - /** - * L.Class powers the OOP facilities of Leaflet and is used to create - * almost all of the Leaflet classes documented. - */ - namespace Class { - /** - * You use L.Class.extend to define new classes, but you can use the - * same method on any class to inherit from it. - */ - function extend(options: ClassExtendOptions): any; - } - -} - -declare namespace L { - export interface ControlStatic extends ClassStatic { - /** - * Creates a control with the given options. - */ - new(options?: ControlOptions): Control; - - Zoom: Control.ZoomStatic; - Attribution: Control.AttributionStatic; - Layers: Control.LayersStatic; - Scale: Control.ScaleStatic; - } - export var Control: ControlStatic; - - export interface Control extends IControl { - /** - * Sets the position of the control. See control positions. - */ - setPosition(position: PositionString): Control; - - /** - * Returns the current position of the control. - */ - getPosition(): PositionString; - - /** - * Adds the control to the map. - */ - addTo(map: Map): Control; - - /** - * Removes the control from the map. - */ - removeFrom(map: Map): Control; - - /** - * Returns the HTML container of the control. - */ - getContainer(): HTMLElement; - - // IControl members - - /** - * Should contain code that creates all the neccessary DOM elements for the - * control, adds listeners on relevant map events, and returns the element - * containing the control. Called on map.addControl(control) or control.addTo(map). - */ - onAdd(map: Map): HTMLElement; - - /** - * Optional, should contain all clean up code (e.g. removes control's event - * listeners). Called on map.removeControl(control) or control.removeFrom(map). - * The control's DOM container is removed automatically. - */ - onRemove(map: Map): void; - } - - namespace Control { - export interface ZoomStatic extends ClassStatic { - /** - * Creates a zoom control. - */ - new (options?: ZoomOptions): Zoom; - } - - export interface Zoom extends L.Control { - } - - export interface ZoomOptions { - /** - * The position of the control (one of the map corners). - * Can be 'topleft', 'topright', 'bottomleft', or 'bottomright'. - * - * Default value: 'topright'. - */ - position?: PositionString; - - /** - * The text set on the zoom in button. - * - * Default value: '+' - */ - zoomInText?: string; - - /** - * The text set on the zoom out button. - * - * Default value: '-' - */ - zoomOutText?: string; - - /** - * The title set on the zoom in button. - * - * Default value: 'Zoom in' - */ - zoomInTitle?: string; - - /** - * The title set on the zoom out button. - * - * Default value: 'Zoom out' - */ - zoomOutTitle?: string; - } - - export interface AttributionStatic extends ClassStatic { - /** - * Creates an attribution control. - */ - new(options?: AttributionOptions): Attribution; - } - - export interface Attribution extends L.Control { - /** - * Sets the text before the attributions. - */ - setPrefix(prefix: string): Attribution; - - /** - * Adds an attribution text (e.g. 'Vector data © CloudMade'). - */ - addAttribution(text: string): Attribution; - - /** - * Removes an attribution text. - */ - removeAttribution(text: string): Attribution; - - } - - export interface LayersStatic extends ClassStatic { - /** - * Creates an attribution control with the given layers. Base layers will be - * switched with radio buttons, while overlays will be switched with checkboxes. - */ - new(baseLayers?: any, overlays?: any, options?: LayersOptions): Layers; - } - - export interface Layers extends L.Control, IEventPowered { - /** - * Adds a base layer (radio button entry) with the given name to the control. - */ - addBaseLayer(layer: ILayer, name: string): Layers; - - /** - * Adds an overlay (checkbox entry) with the given name to the control. - */ - addOverlay(layer: ILayer, name: string): Layers; - - /** - * Remove the given layer from the control. - */ - removeLayer(layer: ILayer): Layers; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Layers; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): Layers; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Layers; - fire(type: string, data?: any): Layers; - addEventListener(eventMap: any, context?: any): Layers; - removeEventListener(eventMap?: any, context?: any): Layers; - clearAllEventListeners(): Layers; - on(eventMap: any, context?: any): Layers; - off(eventMap?: any, context?: any): Layers; - } - - export interface ScaleStatic extends ClassStatic { - /** - * Creates an scale control with the given options. - */ - new(options?: ScaleOptions): Scale; - } - - export interface Scale extends L.Control { - } - } - - export interface control { - /** - * Creates a control with the given options. - */ - (options?: ControlOptions): Control; - } - - export namespace control { - - /** - * Creates a zoom control. - */ - export function zoom(options?: Control.ZoomOptions): L.Control.Zoom; - - /** - * Creates an attribution control. - */ - export function attribution(options?: AttributionOptions): L.Control.Attribution; - - /** - * Creates an attribution control with the given layers. Base layers will be - * switched with radio buttons, while overlays will be switched with checkboxes. - */ - export function layers(baseLayers?: any, overlays?: any, options?: LayersOptions): L.Control.Layers; - - /** - * Creates an scale control with the given options. - */ - export function scale(options?: ScaleOptions): L.Control.Scale; - } -} - -declare namespace L { - - export interface ControlOptions { - - /** - * The initial position of the control (one of the map corners). See control - * positions. - * Default value: 'topright'. - */ - position?: PositionString; - - } -} - -declare namespace L { - - namespace CRS { - - /** - * The most common CRS for online maps, used by almost all free and commercial - * tile providers. Uses Spherical Mercator projection. Set in by default in - * Map's crs option. - */ - export var EPSG3857: ICRS; - - /** - * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection. - */ - export var EPSG4326: ICRS; - - /** - * Rarely used by some commercial tile providers. Uses Elliptical Mercator - * projection. - */ - export var EPSG3395: ICRS; - - /** - * A simple CRS that maps longitude and latitude into x and y directly. May be - * used for maps of flat surfaces (e.g. game maps). Note that the y axis should - * still be inverted (going from bottom to top). - */ - export var Simple: ICRS; - - } -} - -declare namespace L { - - /** - * Creates a div icon instance with the given options. - */ - function divIcon(options: DivIconOptions): DivIcon; - - export interface DivIconStatic extends ClassStatic { - /** - * Creates a div icon instance with the given options. - */ - new(options: DivIconOptions): DivIcon; - } - export var DivIcon: DivIconStatic; - - export interface DivIcon extends Icon { - } -} - -declare namespace L { - - export interface DivIconOptions { - - /** - * Size of the icon in pixels. Can be also set through CSS. - */ - iconSize?: Point|[number, number]; - - /** - * The coordinates of the "tip" of the icon (relative to its top left corner). - * The icon will be aligned so that this point is at the marker's geographical - * location. Centered by default if size is specified, also can be set in CSS - * with negative margins. - */ - iconAnchor?: Point|[number, number]; - - /** - * A custom class name to assign to the icon. - * - * Default value: 'leaflet-div-icon'. - */ - className?: string; - - /** - * A custom HTML code to put inside the div element. - * - * Default value: ''. - */ - html?: string; - - /** - * The coordinates of the point from which popups will "open", relative to the - * icon anchor. - */ - popupAnchor?: Point|[number, number]; - - } -} - -declare namespace L { - - export interface DomEvent { - - /** - * Adds a listener fn to the element's DOM event of the specified type. this keyword - * inside the listener will point to context, or to the element if not specified. - */ - addListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; - on(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; - - /** - * Removes an event listener from the element. - */ - removeListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; - off(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; - - /** - * Stop the given event from propagation to parent elements. Used inside the - * listener functions: - * L.DomEvent.addListener(div, 'click', function - * (e) { - * L.DomEvent.stopPropagation(e); - * }); - */ - stopPropagation(e: Event): DomEvent; - - /** - * Prevents the default action of the event from happening (such as following - * a link in the href of the a element, or doing a POST request with page reload - * when form is submitted). Use it inside listener functions. - */ - preventDefault(e: Event): DomEvent; - - /** - * Does stopPropagation and preventDefault at the same time. - */ - stop(e: Event): DomEvent; - - /** - * Adds stopPropagation to the element's 'click', 'doubleclick', 'mousedown' - * and 'touchstart' events. - */ - disableClickPropagation(el: HTMLElement): DomEvent; - - /** - * Gets normalized mouse position from a DOM event relative to the container - * or to the whole page if not specified. - */ - getMousePosition(e: Event, container?: HTMLElement): Point; - - /** - * Gets normalized wheel delta from a mousewheel DOM event. - */ - getWheelDelta(e: Event): number; - - } - - export var DomEvent: DomEvent; -} - -declare namespace L { - - namespace DomUtil { - - /** - * Returns an element with the given id if a string was passed, or just returns - * the element if it was passed directly. - */ - export function get(id: string): HTMLElement; - - /** - * Returns the value for a certain style attribute on an element, including - * computed values or values set through CSS. - */ - export function getStyle(el: HTMLElement, style: string): string; - - /** - * Returns the offset to the viewport for the requested element. - */ - export function getViewportOffset(el: HTMLElement): Point; - - /** - * Creates an element with tagName, sets the className, and optionally appends - * it to container element. - */ - export function create(tagName: string, className: string, container?: HTMLElement): HTMLElement; - - /** - * Makes sure text cannot be selected, for example during dragging. - */ - export function disableTextSelection(): void; - - /** - * Makes text selection possible again. - */ - export function enableTextSelection(): void; - - /** - * Returns true if the element class attribute contains name. - */ - export function hasClass(el: HTMLElement, name: string): boolean; - - /** - * Adds name to the element's class attribute. - */ - export function addClass(el: HTMLElement, name: string): void; - - /** - * Removes name from the element's class attribute. - */ - export function removeClass(el: HTMLElement, name: string): void; - - /** - * Set the opacity of an element (including old IE support). Value must be from - * 0 to 1. - */ - export function setOpacity(el: HTMLElement, value: number): void; - - /** - * Goes through the array of style names and returns the first name that is a valid - * style name for an element. If no such name is found, it returns false. Useful - * for vendor-prefixed styles like transform. - */ - export function testProp(props: string[]): any; - - /** - * Returns a CSS transform string to move an element by the offset provided in - * the given point. Uses 3D translate on WebKit for hardware-accelerated transforms - * and 2D on other browsers. - */ - export function getTranslateString(point: Point): string; - - /** - * Returns a CSS transform string to scale an element (with the given scale origin). - */ - export function getScaleString(scale: number, origin: Point): string; - - /** - * Sets the position of an element to coordinates specified by point, using - * CSS translate or top/left positioning depending on the browser (used by - * Leaflet internally to position its layers). Forces top/left positioning - * if disable3D is true. - */ - export function setPosition(el: HTMLElement, point: Point, disable3D?: boolean): void; - - /** - * Returns the coordinates of an element previously positioned with setPosition. - */ - export function getPosition(el: HTMLElement): Point; - - /** - * Vendor-prefixed transition style name (e.g. 'webkitTransition' for WebKit). - */ - export var TRANSITION: string; - - /** - * Vendor-prefixed transform style name. - */ - export var TRANSFORM: string; - - } -} - -declare namespace L { - export interface DraggableStatic extends ClassStatic { - /** - * Creates a Draggable object for moving the given element when you start dragging - * the dragHandle element (equals the element itself by default). - */ - new(element: HTMLElement, dragHandle?: HTMLElement): Draggable; - } - export var Draggable: DraggableStatic; - - - export interface Draggable extends IEventPowered { - /** - * Enables the dragging ability. - */ - enable(): void; - - /** - * Disables the dragging ability. - */ - disable(): void; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Draggable; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): Draggable; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Draggable; - fire(type: string, data?: any): Draggable; - addEventListener(eventMap: any, context?: any): Draggable; - removeEventListener(eventMap?: any, context?: any): Draggable; - clearAllEventListeners(): Draggable; - on(eventMap: any, context?: any): Draggable; - off(eventMap?: any, context?: any): Draggable; - } -} - - - -declare namespace L { - - /** - * Create a layer group, optionally given an initial set of layers. - */ - function featureGroup(layers?: T[]): FeatureGroup; - - - export interface FeatureGroupStatic extends ClassStatic { - /** - * Create a layer group, optionally given an initial set of layers. - */ - new(layers?: T[]): FeatureGroup; - } - export var FeatureGroup: FeatureGroupStatic; - - export interface FeatureGroup extends LayerGroup, ILayer, IEventPowered> { - /** - * Binds a popup with a particular HTML content to a click on any layer from the - * group that has a bindPopup method. - */ - bindPopup(htmlContent: string, options?: PopupOptions): FeatureGroup; - - /** - * Returns the LatLngBounds of the Feature Group (created from bounds and coordinates - * of its children). - */ - getBounds(): LatLngBounds; - - /** - * Sets the given path options to each layer of the group that has a setStyle method. - */ - setStyle(style: PathOptions): FeatureGroup; - - /** - * Brings the layer group to the top of all other layers. - */ - bringToFront(): FeatureGroup; - - /** - * Brings the layer group to the bottom of all other layers. - */ - bringToBack(): FeatureGroup; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): FeatureGroup; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; - fire(type: string, data?: any): FeatureGroup; - addEventListener(eventMap: any, context?: any): FeatureGroup; - removeEventListener(eventMap?: any, context?: any): FeatureGroup; - clearAllEventListeners(): FeatureGroup; - on(eventMap: any, context?: any): FeatureGroup; - off(eventMap?: any, context?: any): FeatureGroup; - } -} - -declare namespace L { - - /** - * Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format - * to display on the map (you can alternatively add it later with addData method) - * and an options object. - */ - function geoJson(geojson?: any, options?: GeoJSONOptions): GeoJSON; - - export interface GeoJSONStatic extends ClassStatic { - /** - * Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format - * to display on the map (you can alternatively add it later with addData method) - * and an options object. - */ - new(geojson?: any, options?: GeoJSONOptions): GeoJSON; - - /** - * Creates a layer from a given GeoJSON feature. - */ - geometryToLayer(featureData: GeoJSON, pointToLayer?: (featureData: any, latlng: LatLng) => ILayer): ILayer; - - /** - * Creates a LatLng object from an array of 2 numbers (latitude, longitude) - * used in GeoJSON for points. If reverse is set to true, the numbers will be interpreted - * as (longitude, latitude). - */ - coordsToLatLng(coords: number[], reverse?: boolean): LatLng; - - /** - * Creates a multidimensional array of LatLng objects from a GeoJSON coordinates - * array. levelsDeep specifies the nesting level (0 is for an array of points, - * 1 for an array of arrays of points, etc., 0 by default). If reverse is set to - * true, the numbers will be interpreted as (longitude, latitude). - */ - coordsToLatLngs(coords: any[], levelsDeep?: number, reverse?: boolean): any[]; - } - export var GeoJSON: GeoJSONStatic; - - export interface GeoJSON extends FeatureGroup { - /** - * Adds a GeoJSON object to the layer. - */ - addData(data: any): boolean; - - /** - * Changes styles of GeoJSON vector layers with the given style function. - */ - setStyle(style: (featureData: any) => any): GeoJSON; - - /** - * Changes styles of GeoJSON vector layers with the given style options. - */ - setStyle(style: PathOptions): GeoJSON; - - /** - * Resets the the given vector layer's style to the original GeoJSON style, - * useful for resetting style after hover events. - */ - resetStyle(layer: Path): GeoJSON; - } -} - -declare namespace L { - export interface GeoJSONOptions { - /** - * Function that will be used for creating layers for GeoJSON points (if not - * specified, simple markers will be created). - */ - pointToLayer?: (featureData: any, latlng: LatLng) => ILayer; - - /** - * Function that will be used to get style options for vector layers created - * for GeoJSON features. - */ - style?: (featureData: any) => any; - - /** - * Function that will be called on each created feature layer. Useful for attaching - * events and popups to features. - */ - onEachFeature?: (featureData: any, layer: ILayer) => void; - - /** - * Function that will be used to decide whether to show a feature or not. - */ - filter?: (featureData: any, layer: ILayer) => boolean; - - /** - * Function that will be used for converting GeoJSON coordinates to LatLng points - * (if not specified, coords will be assumed to be WGS84 � standard[longitude, latitude] - * values in degrees). - */ - coordsToLatLng?: (coords: any[]) => LatLng[]; - } -} - - - - -declare namespace L { - - /** - * Creates an icon instance with the given options. - */ - function icon(options: IconOptions): Icon; - - export interface IconStatic extends ClassStatic { - /** - * Creates an icon instance with the given options. - */ - new(options: IconOptions): Icon; - - Default: { - /** - * Creates a default icon instance with the given options. - */ - new(options?: IconOptions): Icon.Default; - - imagePath: string; - }; - } - export var Icon: IconStatic; - - export interface Icon { - } - - namespace Icon { - /** - * L.Icon.Default extends L.Icon and is the blue icon Leaflet uses - * for markers by default. - */ - export interface Default extends Icon { - } - } -} - -declare namespace L { - - export interface IconOptions { - - /** - * (required) The URL to the icon image (absolute or relative to your script - * path). - */ - iconUrl?: string; - - /** - * The URL to a retina sized version of the icon image (absolute or relative to - * your script path). Used for Retina screen devices. - */ - iconRetinaUrl?: string; - - /** - * Size of the icon image in pixels. - */ - iconSize?: Point|[number, number]; - - /** - * The coordinates of the "tip" of the icon (relative to its top left corner). - * The icon will be aligned so that this point is at the marker's geographical - * location. Centered by default if size is specified, also can be set in CSS - * with negative margins. - */ - iconAnchor?: Point|[number, number]; - - /** - * The URL to the icon shadow image. If not specified, no shadow image will be - * created. - */ - shadowUrl?: string; - - /** - * The URL to the retina sized version of the icon shadow image. If not specified, - * no shadow image will be created. Used for Retina screen devices. - */ - shadowRetinaUrl?: string; - - /** - * Size of the shadow image in pixels. - */ - shadowSize?: Point|[number, number]; - - /** - * The coordinates of the "tip" of the shadow (relative to its top left corner) - * (the same as iconAnchor if not specified). - */ - shadowAnchor?: Point|[number, number]; - - /** - * The coordinates of the point from which popups will "open", relative to the - * icon anchor. - */ - popupAnchor?: Point|[number, number]; - - /** - * A custom class name to assign to both icon and shadow images. Empty by default. - */ - className?: string; - } -} - -declare namespace L { - - export interface IControl { - - /** - * Should contain code that creates all the neccessary DOM elements for the - * control, adds listeners on relevant map events, and returns the element - * containing the control. Called on map.addControl(control) or control.addTo(map). - */ - onAdd(map: Map): HTMLElement; - - /** - * Optional, should contain all clean up code (e.g. removes control's event - * listeners). Called on map.removeControl(control) or control.removeFrom(map). - * The control's DOM container is removed automatically. - */ - onRemove(map: Map): void; - } -} - -declare namespace L { - - export interface ICRS { - - /** - * Projection that this CRS uses. - */ - projection: IProjection; - - /** - * Transformation that this CRS uses to turn projected coordinates into screen - * coordinates for a particular tile service. - */ - transformation: Transformation; - - /** - * Standard code name of the CRS passed into WMS services (e.g. 'EPSG:3857'). - */ - code: string; - - /** - * Projects geographical coordinates on a given zoom into pixel coordinates. - */ + export interface CRS { latLngToPoint(latlng: LatLng, zoom: number): Point; - - /** - * The inverse of latLngToPoint. Projects pixel coordinates on a given zoom - * into geographical coordinates. - */ - pointToLatLng(point: Point, zoom: number): LatLng; - - /** - * Projects geographical coordinates into coordinates in units accepted - * for this CRS (e.g. meters for EPSG:3857, for passing it to WMS services). - */ + latLngToPoint(latlng: LatLngLiteral, zoom: number): Point; + latLngToPoint(latlng: LatLngTuple, zoom: number): Point; + pointToLatLng(point: Point): LatLng; + pointToLatLng(point: PointTuple): LatLng; project(latlng: LatLng): Point; - - /** - * Returns the scale used when transforming projected coordinates into pixel - * coordinates for a particular zoom. For example, it returns 256 * 2^zoom for - * Mercator-based CRS. - */ - scale(zoom: number): number; - - /** - * Returns the size of the world in pixels for a particular zoom. - */ - getSize(zoom: number): Point; - - } -} - -declare namespace L { - - export interface IEventPowered { - - /** - * Adds a listener function (fn) to a particular event type of the object. You - * can optionally specify the context of the listener (object the this keyword - * will point to). You can also pass several space-separated types (e.g. 'click - * dblclick'). - */ - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): T; - - /** - * The same as above except the listener will only get fired once and then removed. - */ - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): T; - /** - * Adds a set of type/listener pairs, e.g. {click: onClick, mousemove: onMouseMove} - */ - addEventListener(eventMap: any, context?: any): T; - - /** - * Removes a previously added listener function. If no function is specified, - * it will remove all the listeners of that particular event from the object. - */ - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): T; - - /** - * Removes a set of type/listener pairs. - */ - removeEventListener(eventMap?: any, context?: any): T; - - /** - * Returns true if a particular event type has some listeners attached to it. - */ - hasEventListeners(type: string): boolean; - - /** - * Fires an event of the specified type. You can optionally provide an data object - * — the first argument of the listener function will contain its properties. - */ - fireEvent(type: string, data?: any): T; - - /** - * Removes all listeners to all events on the object. - */ - clearAllEventListeners(): T; - - /** - * Alias to addEventListener. - */ - on(type: string, fn: (e: LeafletEvent) => void, context?: any): T; - - /** - * Alias to addEventListener. - */ - on(eventMap: any, context?: any): T; - - /** - * Alias to addOneTimeEventListener. - */ - once(type: string, fn: (e: LeafletEvent) => void, context?: any): T; - - /** - * Alias to removeEventListener. - */ - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): T; - - /** - * Alias to removeEventListener. - */ - off(eventMap?: any, context?: any): T; - - /** - * Alias to fireEvent. - */ - fire(type: string, data?: any): T; - } -} - -declare namespace L { - - export interface IHandler { - - /** - * Enables the handler. - */ - enable(): void; - - /** - * Disables the handler. - */ - disable(): void; - - /** - * Returns true if the handler is enabled. - */ - enabled(): boolean; - } - - export interface Handler { - initialize(map: Map): void; - } -} - -declare namespace L { - - export interface ILayer { - - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - } -} - -declare namespace L { - namespace Mixin { - export interface LeafletMixinEvents extends IEventPowered { - } - - export var Events: LeafletMixinEvents; - } -} - -declare namespace L { - - /** - * Instantiates an image overlay object given the URL of the image and the geographical - * bounds it is tied to. - */ - function imageOverlay(imageUrl: string, bounds: LatLngBounds, options?: ImageOverlayOptions): ImageOverlay; - - export interface ImageOverlayStatic extends ClassStatic { - /** - * Instantiates an image overlay object given the URL of the image and the geographical - * bounds it is tied to. - */ - new(imageUrl: string, bounds: LatLngBounds, options?: ImageOverlayOptions): ImageOverlay; - } - export var ImageOverlay: ImageOverlayStatic; - - export interface ImageOverlay extends ILayer { - /** - * Adds the overlay to the map. - */ - addTo(map: Map): ImageOverlay; - - /** - * Sets the opacity of the overlay. - */ - setOpacity(opacity: number): ImageOverlay; - - /** - * Changes the URL of the image. - */ - setUrl(imageUrl: string): ImageOverlay; - - /** - * Brings the layer to the top of all overlays. - */ - bringToFront(): ImageOverlay; - - /** - * Brings the layer to the bottom of all overlays. - */ - bringToBack(): ImageOverlay; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - } -} - -declare namespace L { - - export interface ImageOverlayOptions { - - /** - * The opacity of the image overlay. - */ - opacity?: number; - } -} - -declare namespace L { - - export interface IProjection { - - /** - * Projects geographical coordinates into a 2D point. - */ - project(latlng: LatLng): Point; - - /** - * The inverse of project. Projects a 2D point into geographical location. - */ + project(latlng: LatLngLiteral): Point; + project(latlng: LatLngTuple): Point; unproject(point: Point): LatLng; + unproject(point: PointTuple): LatLng; + scale(zoom: number): number; + zoom(scale: number): number; + getProjectedBounds(zoom: number): Bounds; + distance(latlng1: LatLng, latlng2: LatLng): number; + distance(latlng1: LatLngLiteral, latlng2: LatLngLiteral): number; + distance(latlng1: LatLngTuple, latlng2: LatLngTuple): number; + wrapLatLng(latlng: LatLng): LatLng; + wrapLatLng(latlng: LatLngLiteral): LatLng; + wrapLatLng(latlng: LatLngTuple): LatLng; + + code: string; + wrapLng: [number, number]; + wrapLat: [number, number]; + infinite: boolean; } -} -declare namespace L { - - /** - * A constant that represents the Leaflet version in use. - */ - export var version: string; - - /** - * This method restores the L global variale to the original value it had - * before Leaflet inclusion, and returns the real Leaflet namespace. - */ - export function noConflict(): typeof L; -} - -declare namespace L { - /** - * Creates an object representing a geographical point with the given latitude - * and longitude. - */ - function latLng(latitude: number, longitude: number): LatLng; - - /** - * Creates an object representing a geographical point with the given latitude - * and longitude. - */ - function latLng(coords: LatLngExpression): LatLng; - - export interface LatLngStatic { - /** - * Creates an object representing a geographical point with the given latitude - * and longitude. - */ - new(latitude: number, longitude: number): LatLng; - - /** - * Creates an object representing a geographical point with the given latitude - * and longitude. - */ - new(coords: LatLngExpression): LatLng; - - /** - * A multiplier for converting degrees into radians. - * - * Value: Math.PI / 180. - */ - DEG_TO_RAD: number; - - /** - * A multiplier for converting radians into degrees. - * - * Value: 180 / Math.PI. - */ - RAD_TO_DEG: number; - - /** - * Max margin of error for the equality check. - * - * Value: 1.0E-9. - */ - MAX_MARGIN: number; + export namespace CRS { + export const EPSG3395: CRS; + export const EPSG3857: CRS; + export const EPSG4326: CRS; + export const Earth: CRS; + export const Simple: CRS; + } + + export interface Projection { + project(latlng: LatLng): Point; + project(latlng: LatLngLiteral): Point; + project(latlng: LatLngTuple): Point; + unproject(point: Point): LatLng; + unproject(point: PointTuple): LatLng; + + bounds: LatLngBounds; + } + + export namespace Projection { + export const LonLat: Projection; + export const Mercator: Projection; + export const SphericalMercator: Projection; } - export var LatLng: LatLngStatic; export interface LatLng { - /** - * Returns the distance (in meters) to the given LatLng calculated using the - * Haversine formula. See description on wikipedia - */ - distanceTo(otherLatlng: LatLngExpression): number; - - /** - * Returns true if the given LatLng point is at the same position (within a small - * margin of error). - */ - equals(otherLatlng: LatLngExpression): boolean; - - /** - * Returns a string representation of the point (for debugging purposes). - */ + equals(otherLatLng: LatLng, maxMargin?: number): boolean; + equals(otherLatLng: LatLngLiteral, maxMargin?: number): boolean; + equals(otherLatLng: LatLngTuple, maxMargin?: number): boolean; toString(): string; + distanceTo(otherLatLng: LatLng): number; + distanceTo(otherLatLng: LatLngLiteral): number; + distanceTo(otherLatLng: LatLngTuple): number; + wrap(): LatLng; + toBounds(sizeInMeters: number): LatLngBounds; - /** - * Returns a new LatLng object with the longitude wrapped around left and right - * boundaries (-180 to 180 by default). - */ - wrap(left?: number, right?: number): LatLng; - - /** - * Latitude in degrees. - */ lat: number; + lng: number; + alt: number; + } - /** - * Longitude in degrees. - */ + export interface LatLngLiteral { + lat: number; lng: number; } -} -declare namespace L { + export type LatLngTuple = [number, number]; - /** - * Creates a LatLngBounds object by defining south-west and north-east corners - * of the rectangle. - */ - function latLngBounds(southWest: LatLngExpression, northEast: LatLngExpression): LatLngBounds; + type LatLngExpression = LatLng | LatLngLiteral | LatLngTuple; - /** - * Creates a LatLngBounds object defined by the geographical points it contains. - * Very useful for zooming the map to fit a particular set of locations with fitBounds. - */ - function latLngBounds(latlngs: LatLngBoundsExpression): LatLngBounds; + export function latLng(latitude: number, longitude: number, altitude?: number): LatLng; - export interface LatLngBoundsStatic { - /** - * Creates a LatLngBounds object by defining south-west and north-east corners - * of the rectangle. - */ - new(southWest: LatLngExpression, northEast: LatLngExpression): LatLngBounds; + export function latLng(coords: LatLngTuple): LatLng; - /** - * Creates a LatLngBounds object defined by the geographical points it contains. - * Very useful for zooming the map to fit a particular set of locations with fitBounds. - */ - new(latlngs: LatLngBoundsExpression): LatLngBounds; - } - export var LatLngBounds: LatLngBoundsStatic; + export function latLng(coords: [number, number, number]): LatLng; + + export function latLng(coords: LatLngLiteral): LatLng; + + export function latLng(coords: {lat: number, lng: number, alt: number}): LatLng; export interface LatLngBounds { - /** - * Extends the bounds to contain the given point. - */ - extend(latlng: LatLngExpression): LatLngBounds; - - /** - * Extends the bounds to contain the given bounds. - */ - extend(latlng: LatLngBoundsExpression): LatLngBounds; - - /** - * Returns the south-west point of the bounds. - */ + extend(latlng: LatLng): this; + extend(latlng: LatLngLiteral): this; + extend(latlng: LatLngTuple): this; + extend(otherBounds: LatLngBounds): this; + extend(otherBounds: LatLngBoundsLiteral): this; + pad(bufferRatio: number): LatLngBounds; // does this modify the current instance or does it return a new one? + getCenter(): LatLng; getSouthWest(): LatLng; - - /** - * Returns the north-east point of the bounds. - */ getNorthEast(): LatLng; - - /** - * Returns the north-west point of the bounds. - */ getNorthWest(): LatLng; - - /** - * Returns the south-east point of the bounds. - */ getSouthEast(): LatLng; - - /** - * Returns the west longitude in degrees of the bounds. - */ - getWest(): number; - - /** - * Returns the east longitude in degrees of the bounds. - */ - getEast(): number; - - /** - * Returns the north latitude in degrees of the bounds. - */ - getNorth(): number; - - /** - * Returns the south latitude in degrees of the bounds. - */ - getSouth(): number; - - /** - * Returns the center point of the bounds. - */ - getCenter(): LatLng; - - /** - * Returns true if the rectangle contains the given one. - */ - contains(otherBounds: LatLngBoundsExpression): boolean; - - /** - * Returns true if the rectangle contains the given point. - */ - contains(latlng: LatLngExpression): boolean; - - /** - * Returns true if the rectangle intersects the given bounds. - */ - intersects(otherBounds: LatLngBoundsExpression): boolean; - - /** - * Returns true if the rectangle is equivalent (within a small margin of error) - * to the given bounds. - */ - equals(otherBounds: LatLngBoundsExpression): boolean; - - /** - * Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' - * format. Useful for sending requests to web services that return geo data. - */ + getWest(): number; + getSouth(): number; + getEast(): number; + getNorth(): number; + contains(otherBounds: LatLngBounds): boolean; + contains(otherBounds: LatLngBoundsLiteral): boolean; + contains(latlng: LatLng): boolean; + contains(latlng: LatLngLiteral): boolean; + contains(latlng: LatLngTuple): boolean; + intersects(otherBounds: LatLngBounds): boolean; + intersects(otherBounds: LatLngLiteral): boolean; + overlaps(otherBounds: Bounds): boolean; // investigate if this is really bounds and not latlngbounds + overlaps(otherBounds: BoundsLiteral): boolean; toBBoxString(): string; - - /** - * Returns bigger bounds created by extending the current bounds by a given - * percentage in each direction. - */ - pad(bufferRatio: number): LatLngBounds; - - /** - * Returns true if the bounds are properly initialized. - */ + equals(otherBounds: LatLngBounds): boolean; + equals(otherBounds: LatLngBoundsLiteral): boolean; isValid(): boolean; - } -} -declare namespace L { + export type LatLngBoundsLiteral = Array; - /** - * Create a layer group, optionally given an initial set of layers. - */ - function layerGroup(layers?: T[]): LayerGroup; + type LatLngBoundsExpression = LatLngBounds | LatLngBoundsLiteral; + export function latLngBounds(southWest: LatLng, northEast: LatLng): LatLngBounds; - export interface LayerGroupStatic extends ClassStatic { - /** - * Create a layer group, optionally given an initial set of layers. - */ - new(layers?: T[]): LayerGroup; + export function latLngBounds(southWest: LatLngLiteral, northEast: LatLngLiteral): LatLngBounds; + + export function latLngBounds(southWest: LatLngTuple, northEast: LatLngTuple): LatLngBounds; + + export function latLngBounds(latlngs: LatLngBoundsLiteral): LatLngBounds; + + export type PointTuple = [number, number]; + + export interface Point { + clone(): Point; + add(otherPoint: Point): Point; // investigate if this mutates or returns a new instance + add(otherPoint: PointTuple): Point; + subtract(otherPoint: Point): Point; + subtract(otherPoint: PointTuple): Point; + divideBy(num: number): Point; + multiplyBy(num: number): Point; + scaleBy(scale: Point): Point; + scaleBy(scale: PointTuple): Point; + unscaleBy(scale: Point): Point; + unscaleBy(scale: PointTuple): Point; + round(): Point; + floor(): Point; + ceil(): Point; + distanceTo(otherPoint: Point): Point; + distanceTo(otherPoint: PointTuple): Point; + equals(otherPoint: Point): boolean; + equals(otherPoint: PointTuple): boolean; + contains(otherPoint: Point): boolean; + contains(otherPoint: PointTuple): boolean; + toString(): string; } - export var LayerGroup: LayerGroupStatic; - export interface LayerGroup extends ILayer { - /** - * Adds the group of layers to the map. - */ - addTo(map: Map): LayerGroup; + type PointExpression = Point | PointTuple; - /** - * Adds a given layer to the group. - */ - addLayer(layer: T): LayerGroup; + export function point(x: number, y: number, round?: boolean): Point; - /** - * Removes a given layer from the group. - */ - removeLayer(layer: T): LayerGroup; + export function point(coords: PointTuple): Point; - /** - * Removes a given layer of the given id from the group. - */ - removeLayer(id: string): LayerGroup; + export function point(coords: {x: number, y: number}): Point; - /** - * Returns true if the given layer is currently added to the group. - */ - hasLayer(layer: T): boolean; + export type BoundsLiteral = Array; - /** - * Returns the layer with the given id. - */ - getLayer(id: string): T; - - /** - * Returns an array of all the layers added to the group. - */ - getLayers(): T[]; - - /** - * Removes all the layers from the group. - */ - clearLayers(): LayerGroup; - - /** - * Iterates over the layers of the group, optionally specifying context of - * the iterator function. - */ - eachLayer(fn: (layer: T) => void, context?: any): LayerGroup; - - /** - * Returns a GeoJSON representation of the layer group (GeoJSON FeatureCollection). - * Note: Descendent classes MultiPolygon & MultiPolyLine return `Feature`s, not `FeatureCollection`s - */ - toGeoJSON(): GeoJSON.FeatureCollection|GeoJSON.Feature; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - } -} - - -declare namespace L { - - export interface LayersOptions { - - /** - * The position of the control (one of the map corners). See control positions. - * - * Default value: 'topright'. - */ - position?: PositionString; - - /** - * If true, the control will be collapsed into an icon and expanded on mouse hover - * or touch. - * - * Default value: true. - */ - collapsed?: boolean; - - /** - * If true, the control will assign zIndexes in increasing order to all of its - * layers so that the order is preserved when switching them on/off. - * - * Default value: true. - */ - autoZIndex?: boolean; - - } -} - -declare namespace L { - - export interface LeafletErrorEvent extends LeafletEvent { - - /** - * Error message. - */ - message: string; - - /** - * Error code (if applicable). - */ - code: number; - } -} - -declare namespace L { - - export interface LeafletEvent { - - /** - * The event type (e.g. 'click'). - */ - type: string; - - /** - * The object that fired the event. - */ - target: any; - } -} - -declare namespace L { - - export interface LeafletGeoJSONEvent extends LeafletEvent { - - /** - * The layer for the GeoJSON feature that is being added to the map. - */ - layer: ILayer; - - /** - * GeoJSON properties of the feature. - */ - properties: any; - - /** - * GeoJSON geometry type of the feature. - */ - geometryType: string; - - /** - * GeoJSON ID of the feature (if present). - */ - id: string; - } -} - -declare namespace L { - - export interface LeafletLayerEvent extends LeafletEvent { - - /** - * The layer that was added or removed. - */ - layer: ILayer; - } -} - -declare namespace L { - - export interface LeafletLayersControlEvent extends LeafletEvent { - - /** - * The layer that was added or removed. - */ - layer: ILayer; - - /** - * The name of the layer that was added or removed. - */ - name: string; - } -} - -declare namespace L { - - export interface LeafletLocationEvent extends LeafletEvent { - - /** - * Detected geographical location of the user. - */ - latlng: LatLng; - - /** - * Geographical bounds of the area user is located in (with respect to the accuracy - * of location). - */ - bounds: LatLngBounds; - - /** - * Accuracy of location in meters. - */ - accuracy: number; - - /** - * Height of the position above the WGS84 ellipsoid in meters. - */ - altitude: number; - - /** - * Accuracy of altitude in meters. - */ - altitudeAccuracy: number; - - /** - * The direction of travel in degrees counting clockwise from true North. - */ - heading: number; - - /** - * Current velocity in meters per second. - */ - speed: number; - - /** - * The time when the position was acquired. - */ - timestamp: number; - - } -} - -declare namespace L { - - export interface LeafletMouseEvent extends LeafletEvent { - - /** - * The geographical point where the mouse event occured. - */ - latlng: LatLng; - - /** - * Pixel coordinates of the point where the mouse event occured relative to - * the map layer. - */ - layerPoint: Point; - - /** - * Pixel coordinates of the point where the mouse event occured relative to - * the map сontainer. - */ - containerPoint: Point; - - /** - * The original DOM mouse event fired by the browser. - */ - originalEvent: MouseEvent; - } -} - -declare namespace L { - - export interface LeafletPopupEvent extends LeafletEvent { - - /** - * The popup that was opened or closed. - */ - popup: Popup; - } -} - -declare namespace L { - - export interface LeafletDragEndEvent extends LeafletEvent { - - /** - * The distance in pixels the draggable element was moved by. - */ - distance: number; - } -} - -declare namespace L { - - export interface LeafletResizeEvent extends LeafletEvent { - - /** - * The old size before resize event. - */ - oldSize: Point; - - /** - * The new size after the resize event. - */ - newSize: Point; - } -} - -declare namespace L { - - export interface LeafletTileEvent extends LeafletEvent { - - /** - * The tile element (image). - */ - tile: HTMLElement; - - /** - * The source URL of the tile. - */ - url: string; - } -} - -declare namespace L { - - namespace LineUtil { - - /** - * Dramatically reduces the number of points in a polyline while retaining - * its shape and returns a new array of simplified points. Used for a huge performance - * boost when processing/displaying Leaflet polylines for each zoom level - * and also reducing visual noise. tolerance affects the amount of simplification - * (lesser value means higher quality but slower and with more points). Also - * released as a separated micro-library Simplify.js. - */ - export function simplify(points: Point[], tolerance: number): Point[]; - - /** - * Returns the distance between point p and segment p1 to p2. - */ - export function pointToSegmentDistance(p: Point, p1: Point, p2: Point): number; - - /** - * Returns the closest point from a point p on a segment p1 to p2. - */ - export function closestPointOnSegment(p: Point, p1: Point, p2: Point): Point; - - /** - * Clips the segment a to b by rectangular bounds. Used by Leaflet to only show - * polyline points that are on the screen or near, increasing performance. Returns - * either false or a length-2 array of clipped points. - */ - export function clipSegment(a: Point, b: Point, bounds: Bounds): Point[] | boolean; - - } -} - -declare namespace L { - - export interface LocateOptions { - - /** - * If true, starts continous watching of location changes (instead of detecting - * it once) using W3C watchPosition method. You can later stop watching using - * map.stopLocate() method. - * - * Default value: false. - */ - watch?: boolean; - - /** - * If true, automatically sets the map view to the user location with respect - * to detection accuracy, or to world view if geolocation failed. - * - * Default value: false. - */ - setView?: boolean; - - /** - * The maximum zoom for automatic view setting when using `setView` option. - * - * Default value: Infinity. - */ - maxZoom?: number; - - /** - * Number of millisecond to wait for a response from geolocation before firing - * a locationerror event. - * - * Default value: 10000. - */ - timeout?: number; - - /** - * Maximum age of detected location. If less than this amount of milliseconds - * passed since last geolocation response, locate will return a cached location. - * - * Default value: 0. - */ - maximumAge?: number; - - /** - * Enables high accuracy, see description in the W3C spec. - * - * Default value: false. - */ - enableHighAccuracy?: boolean; - } -} - -declare namespace L { - - /** - * Instantiates a map object given a div element and optionally an - * object literal with map options described below. - */ - function map(id: HTMLElement, options?: Map.MapOptions): Map; - - /** - * Instantiates a map object given a div element id and optionally an - * object literal with map options described below. - */ - function map(id: string, options?: Map.MapOptions): Map; - - - export interface MapStatic extends ClassStatic { - /** - * Instantiates a map object given a div element and optionally an - * object literal with map options described below. - * - * @constructor - */ - new(id: HTMLElement, options?: Map.MapOptions): Map; - - /** - * Instantiates a map object given a div element id and optionally an - * object literal with map options described below. - * - * @constructor - */ - new(id: string, options?: Map.MapOptions): Map; - } - export var Map: MapStatic; - - export interface Map extends IEventPowered { - // Methods for Modifying Map State - - /** - * Sets the view of the map (geographical center and zoom) with the given - * animation options. - */ - setView(center: LatLngExpression, zoom?: number, options?: Map.ZoomPanOptions): Map; - - /** - * Sets the zoom of the map. - */ - setZoom(zoom: number, options?: Map.ZoomPanOptions): Map; - - /** - * Increases the zoom of the map by delta (1 by default). - */ - zoomIn(delta?: number, options?: Map.ZoomPanOptions): Map; - - /** - * Decreases the zoom of the map by delta (1 by default). - */ - zoomOut(delta?: number, options?: Map.ZoomPanOptions): Map; - - /** - * Zooms the map while keeping a specified point on the map stationary - * (e.g. used internally for scroll zoom and double-click zoom). - */ - setZoomAround(latlng: LatLngExpression, zoom: number, options?: Map.ZoomPanOptions): Map; - - /** - * Sets a map view that contains the given geographical bounds with the maximum - * zoom level possible. - */ - fitBounds(bounds: LatLngBounds, options?: Map.FitBoundsOptions): Map; - - /** - * Sets a map view that mostly contains the whole world with the maximum zoom - * level possible. - */ - fitWorld(options?: Map.FitBoundsOptions): Map; - - /** - * Pans the map to a given center. Makes an animated pan if new center is not more - * than one screen away from the current one. - */ - panTo(latlng: LatLngExpression, options?: PanOptions): Map; - - /** - * Pans the map to the closest view that would lie inside the given bounds (if - * it's not already). - */ - panInsideBounds(bounds: LatLngBounds): Map; - - /** - * Pans the map by a given number of pixels (animated). - */ - panBy(point: Point, options?: PanOptions): Map; - - /** - * Checks if the map container size changed and updates the map if so — call it - * after you've changed the map size dynamically, also animating pan by default. - * If options.pan is false, panning will not occur. - */ - invalidateSize(options: Map.ZoomPanOptions): Map; - - /** - * Checks if the map container size changed and updates the map if so — call it - * after you've changed the map size dynamically, also animating pan by default. - */ - invalidateSize(animate: boolean): Map; - - /** - * Restricts the map view to the given bounds (see map maxBounds option), - * passing the given animation options through to `setView`, if required. - */ - setMaxBounds(bounds: LatLngBounds, options?: Map.ZoomPanOptions): Map; - - /** - * Tries to locate the user using Geolocation API, firing locationfound event - * with location data on success or locationerror event on failure, and optionally - * sets the map view to the user location with respect to detection accuracy - * (or to the world view if geolocation failed). See Locate options for more - * details. - */ - locate(options?: LocateOptions): Map; - - /** - * Stops watching location previously initiated by map.locate({watch: true}) - * and aborts resetting the map view if map.locate was called with {setView: true}. - */ - stopLocate(): Map; - - /** - * Destroys the map and clears all related event listeners. - */ - remove(): Map; - - // Methods for Getting Map State - - /** - * Returns the geographical center of the map view. - */ - getCenter(): LatLng; - - /** - * Returns the current zoom of the map view. - */ - getZoom(): number; - - /** - * Returns the minimum zoom level of the map. - */ - getMinZoom(): number; - - /** - * Returns the maximum zoom level of the map. - */ - getMaxZoom(): number; - - /** - * Returns the LatLngBounds of the current map view. - */ - getBounds(): LatLngBounds; - - /** - * Returns the maximum zoom level on which the given bounds fit to the map view - * in its entirety. If inside (optional) is set to true, the method instead returns - * the minimum zoom level on which the map view fits into the given bounds in its - * entirety. - */ - getBoundsZoom(bounds: LatLngBounds, inside?: boolean): number; - - /** - * Returns the current size of the map container. - */ + export interface Bounds { + extend(point: Point): this; + extend(point: PointTuple): this; + getCenter(round?: boolean): Point; + getBottomLeft(): Point; + getTopRight(): Point; getSize(): Point; + contains(otherBounds: Bounds): boolean; + contains(otherBounds: BoundsLiteral): boolean; + contains(point: Point): boolean; + contains(point: PointTuple): boolean; + intersects(otherBounds: Bounds): boolean; + intersects(otherBounds: BoundsLiteral): boolean; + overlaps(otherBounds: Bounds): boolean; + overlaps(otherBounds: BoundsLiteral): boolean; - /** - * Returns the bounds of the current map view in projected pixel coordinates - * (sometimes useful in layer and overlay implementations). - */ - getPixelBounds(): Bounds; - - /** - * Returns the projected pixel coordinates of the top left point of the map layer - * (useful in custom layer and overlay implementations). - */ - getPixelOrigin(): Point; - - // Methods for Layers and Controls - - /** - * Adds the given layer to the map. If optional insertAtTheBottom is set to true, - * the layer is inserted under all others (useful when switching base tile layers). - */ - addLayer(layer: ILayer, insertAtTheBottom?: boolean): Map; - - /** - * Removes the given layer from the map. - */ - removeLayer(layer: ILayer): Map; - - /** - * Returns true if the given layer is currently added to the map. - */ - hasLayer(layer: ILayer): boolean; - - /** - * Opens the specified popup while closing the previously opened (to make sure - * only one is opened at one time for usability). - */ - openPopup(popup: Popup): Map; - - /** - * Creates a popup with the specified options and opens it in the given point - * on a map. - */ - openPopup(html: string, latlng: LatLngExpression, options?: PopupOptions): Map; - - /** - * Creates a popup with the specified options and opens it in the given point - * on a map. - */ - openPopup(el: HTMLElement, latlng: LatLngExpression, options?: PopupOptions): Map; - - /** - * Closes the popup previously opened with openPopup (or the given one). - */ - closePopup(popup?: Popup): Map; - - /** - * Adds the given control to the map. - */ - addControl(control: IControl): Map; - - /** - * Removes the given control from the map. - */ - removeControl(control: IControl): Map; - - // Conversion Methods - - /** - * Returns the map layer point that corresponds to the given geographical coordinates - * (useful for placing overlays on the map). - */ - latLngToLayerPoint(latlng: LatLngExpression): Point; - - /** - * Returns the geographical coordinates of a given map layer point. - */ - layerPointToLatLng(point: Point): LatLng; - - /** - * Converts the point relative to the map container to a point relative to the - * map layer. - */ - containerPointToLayerPoint(point: Point): Point; - - /** - * Converts the point relative to the map layer to a point relative to the map - * container. - */ - layerPointToContainerPoint(point: Point): Point; - - /** - * Returns the map container point that corresponds to the given geographical - * coordinates. - */ - latLngToContainerPoint(latlng: LatLngExpression): Point; - - /** - * Returns the geographical coordinates of a given map container point. - */ - containerPointToLatLng(point: Point): LatLng; - - /** - * Projects the given geographical coordinates to absolute pixel coordinates - * for the given zoom level (current zoom level by default). - */ - project(latlng: LatLngExpression, zoom?: number): Point; - - /** - * Projects the given absolute pixel coordinates to geographical coordinates - * for the given zoom level (current zoom level by default). - */ - unproject(point: Point, zoom?: number): LatLng; - - /** - * Returns the pixel coordinates of a mouse click (relative to the top left corner - * of the map) given its event object. - */ - mouseEventToContainerPoint(event: LeafletMouseEvent): Point; - - /** - * Returns the pixel coordinates of a mouse click relative to the map layer given - * its event object. - */ - mouseEventToLayerPoint(event: LeafletMouseEvent): Point; - - /** - * Returns the geographical coordinates of the point the mouse clicked on given - * the click's event object. - */ - mouseEventToLatLng(event: LeafletMouseEvent): LatLng; - - // Other Methods - - /** - * Returns the container element of the map. - */ - getContainer(): HTMLElement; - - /** - * Returns an object with different map panes (to render overlays in). - */ - getPanes(): MapPanes; - - // REVIEW: Should we make it more flexible declaring parameter 'fn' as Function? - /** - * Runs the given callback when the map gets initialized with a place and zoom, - * or immediately if it happened already, optionally passing a function context. - */ - whenReady(fn: (map: Map) => void, context?: any): Map; - - // Properties - - /** - * Map dragging handler (by both mouse and touch). - */ - dragging: IHandler; - - /** - * Touch zoom handler. - */ - touchZoom: IHandler; - - /** - * Double click zoom handler. - */ - doubleClickZoom: IHandler; - - /** - * Scroll wheel zoom handler. - */ - scrollWheelZoom: IHandler; - - /** - * Box (shift-drag with mouse) zoom handler. - */ - boxZoom: IHandler; - - /** - * Keyboard navigation handler. - */ - keyboard: IHandler; - - /** - * Mobile touch hacks (quick tap and touch hold) handler. - */ - tap: IHandler; - - /** - * Zoom control. - */ - zoomControl: Control.Zoom; - - /** - * Attribution control. - */ - attributionControl: Control.Attribution; - - /** - * Map state options - */ - options: Map.MapOptions; - - /** - * Iterates over the layers of the map, optionally specifying context - * of the iterator function. - */ - eachLayer(fn: (layer: ILayer) => void, context?: any): Map; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Map; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): Map; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Map; - fire(type: string, data?: any): Map;addEventListener(eventMap: any, context?: any): Map; - removeEventListener(eventMap?: any, context?: any): Map; - clearAllEventListeners(): Map; - on(eventMap: any, context?: any): Map; - off(eventMap?: any, context?: any): Map; + min: Point; + max: Point; } -} -declare namespace L.Map { + type BoundsExpression = Bounds | BoundsLiteral; + + export function bounds(topLeft: Point, bottomRight: Point): Bounds; + + export function bounds(topLeft: PointTuple, bottomRight: PointTuple): Bounds; + + export function bounds(points: Array): Bounds; + + export function bounds(points: BoundsLiteral): Bounds; + + export interface Evented { + + } + + interface LayerOptions { + pane?: string; + } + + interface InteractiveLayerOptions extends LayerOptions { + interactive?: boolean; + } + + export interface Layer extends Evented { + addTo(map: Map): this; + remove(): this; + removeFrom(map: Map): this; + getPane(name?: string): HTMLElement; + + // Popup methods + bindPopup(content: string, options?: PopupOptions): this; + bindPopup(content: HTMLElement, options?: PopupOptions): this; + bindPopup(content: (layer: Layer) => Content, options?: PopupOptions): this; + bindPopup(content: Popup): this; + unbindPopup(): this; + openPopup(): this; + openPopup(latlng: LatLng): this; + openPopup(latlng: LatLngLiteral): this; + openPopup(latlng: LatLngTuple): this; + closePopup(): this; + togglePopup(): this; + isPopupOpen(): boolean; + setPopupContent(content: string): this; + setPopupContent(content: HTMLElement): this; + setPopupContent(content: Popup): this; + getPopup(): Popup; + + // Tooltip methods + bindTooltip(content: string, options?: TooltipOptions): this; + bindTooltip(content: HTMLElement, options?: TooltipOptions): this; + bindTooltip(content: (layer: Layer) => Content, options?: TooltipOptions): this; + bindTooltip(content: Tooltip, options?: TooltipOptions): this; + unbindTooltip(): this; + openTooltip(): this; + openTooltip(latlng: LatLng): this; + openTooltip(latlng: LatLngLiteral): this; + openTooltip(latlng: LatLngTuple): this; + closeTooltip(): this; + toggleTooltip(): this; + isTooltipOpen(): boolean; + setTooltipContent(content: string): this; + setTooltipContent(content: HTMLElement): this; + setTooltipContent(content: Tooltip): this; + getTooltip(): Tooltip; + + // Extension methods + onAdd(map: Map): this; + onRemove(map: Map): this; + getEvents(): {[name: string]: (event: Event) => void}; + getAttribution(): string; + beforeAdd(map: Map): this; + } + + export interface GridLayerOptions { + tileSize?: number | Point; + opacity?: number; + updateWhenIdle?: boolean; + updateWhenZooming?: boolean; + updateInterval?: number; + attribution?: string; + zIndex?: number; + bounds?: LatLngBoundsExpression; + minZoom?: number; + maxZoom?: number; + noWrap?: boolean; + pane?: string; + className?: string; + keepBuffer?: number; + } + + export interface GridLayer extends Layer { + bringToFront(): this; + bringToBack(): this; + getAttribution(): string; + getContainer(): HTMLElement; + setOpacity(opacity: number): this; + setZIndex(zIndex: number): this; + isLoading(): boolean; + redraw(): this; + getTileSize(): Point; + } + + export function gridLayer(options?: GridLayerOptions): GridLayer; + + export interface TileLayerOptions extends GridLayerOptions { + minZoom?: number; + maxZoom?: number; + maxNativeZoom?: number; + subdomains?: string | Array; + errorTileUrl?: string; + zoomOffset?: number; + tms?: boolean; + zoomReverse?: boolean; + detectRetina?: boolean; + crossOrigin?: boolean; + } + + export interface TileLayer extends GridLayer { + setUrl(url: string, noRedraw?: boolean): this; + } + + export function tileLayer(urlTemplate: string, options?: TileLayerOptions): TileLayer; + + export interface WMSOptions extends TileLayerOptions { + layers: string; + styles?: string; + format?: string; + transparent?: boolean; + version?: string; + crs?: CRS; + uppercase?: boolean; + } + + export interface WMS extends TileLayer { + setParams(params: Object, noRedraw?: boolean): this; + } + + export namespace tileLayer { + export function wms(baseUrl: string, options: WMSOptions): WMS; + } + + export interface ImageOverlayOptions extends LayerOptions { + opacity?: number; + alt?: string; + interactive?: boolean; + attribution?: string; + crossOrigin?: boolean; + } + + export interface ImageOverlay extends Layer { + setOpacity(opacity: number): this; + bringToFront(): this; + bringToBack(): this; + setUrl(url: string): this; + } + + export function imageOverlay(imageUrl: string, bounds: LatLngBoundsExpression, options?: ImageOverlayOptions): ImageOverlay; + + export type LineCapShape = 'butt' | 'round' | 'square' | 'inherit'; + + export type LineJoinShape = 'miter' | 'round' | 'bevel' | 'inherit'; + + export type FillRule = 'nonzero' | 'evenodd' | 'inherit'; + + export interface PathOptions extends InteractiveLayerOptions { + stroke?: boolean; + color?: string; + wight?: number; + opacity?: number; + lineCap?: LineCapShape; + lineJoin?: LineJoinShape; + dashArray?: string; + dashOffset?: string; + fill?: boolean; + fillColor?: string; + fillOpacity?: number; + fillRule?: FillRule; + renderer?: Renderer; + className: string; + } + + export interface Path extends Layer { + redraw(): this; + setStyle(style: PathOptions): this; + bringToFront(): this; + bringToBack(): this; + } + + export interface PolylineOptions extends PathOptions { + smoothFactor?: number; + noClip?: boolean; + } + + export interface Polyline extends Path { + toGeoJSON(): Object; // should import GeoJSON typings + getLatLngs(): Array; + setLatLngs(latlngs: Array): this; + setLatLngs(latlngs: Array): this; + setLatLngs(latlngs: Array): this; + isEmpty(): boolean; + getCenter(): LatLng; + getBounds(): LatLngBounds; + addLatLng(latlng: LatLng): this; + addLatLng(latlng: LatLngLiteral): this; + addLatLng(latlng: LatLngTuple): this; + addLatLng(latlng: Array): this; // these three overloads aren't explicitly noted in the docs + addLatLng(latlng: Array): this; + addLatLng(latlng: Array): this; + } + + export function polyline(latlngs: Array, options?: PolylineOptions): Polyline; + + export function polyline(latlngs: Array, options?: PolylineOptions): Polyline; + + export function polyline(latlngs: Array, options?: PolylineOptions): Polyline; + + export function polyline(latlngs: Array>, options?: PolylineOptions): Polyline; + + export function polyline(latlngs: Array>, options?: PolylineOptions): Polyline; + + export function polyline(latlngs: Array>, options?: PolylineOptions): Polyline; + + export interface Polygon extends Polyline { + toGeoJSON(): Object; // should import GeoJSON typings + } + + export function polygon(latlngs: Array, options?: PolylineOptions): Polygon; + + export function polygon(latlngs: Array, options?: PolylineOptions): Polygon; + + export function polygon(latlngs: Array, options?: PolylineOptions): Polygon; + + export function polygon(latlngs: Array>, options?: PolylineOptions): Polygon; + + export function polygon(latlngs: Array>, options?: PolylineOptions): Polygon; + + export function polygon(latlngs: Array>, options?: PolylineOptions): Polygon; + + export interface Rectangle extends Polygon { + setBounds(latLngBounds: LatLngBounds): this; + setBounds(latLngBounds: LatLngBoundsLiteral): this; + } + + export function rectangle(latLngBounds: LatLngBounds, options?: PolylineOptions): Rectangle; + + export function rectangle(latLngBounds: LatLngBoundsLiteral, options?: PolylineOptions): Rectangle; + + export interface CircleMarkerOptions extends PathOptions { + radius?: number; + } + + export interface CircleMarker extends Path { + toGeoJSON(): Object; // should import GeoJSON typings + setLatLng(latLng: LatLng): this; + setLatLng(latLng: LatLngLiteral): this; + setLatLng(latLng: LatLngTuple): this; + getLatLng(): LatLng; + setRadius(radius: number): this; + getRadius(): number; + } + + export function circleMarker(latlng: LatLng, options?: CircleMarkerOptions): CircleMarker; + + export function circleMarker(latlng: LatLngLiteral, options?: CircleMarkerOptions): CircleMarker; + + export function circleMarker(latlng: LatLngLiteral, options?: CircleMarkerOptions): CircleMarker; + + export interface CircleOptions extends PathOptions { + radius?: number; + } + + export interface Circle extends CircleMarker { + setRadius(radius: number): this; + getRadius(): number; + getBounds(): LatLngBounds; + } + + export function circle(latlng: LatLng, options?: CircleOptions): Circle; + + export function circle(latlng: LatLngLiteral, options?: CircleOptions): Circle; + + export function circle(latlng: LatLngTuple, options?: CircleOptions): Circle; + + export function circle(latlng: LatLng, radius: number, options?: CircleOptions): Circle; + + export function circle(latlng: LatLngLiteral, radius: number, options?: CircleOptions): Circle; + + export function circle(latlng: LatLngTuple, radius: number, options?: CircleOptions): Circle; + + export interface RendererOptions extends LayerOptions { + padding?: number; + } + + export interface Renderer extends Layer {} + + export interface SVG extends Renderer {} + + type Zoom = boolean | 'center'; export interface MapOptions { - - // Map State Options - - /** - * Initial geographical center of the map. - */ - center?: LatLng; - - /** - * Initial map zoom. - */ - zoom?: number; - - /** - * Layers that will be added to the map initially. - */ - layers?: ILayer[]; - - /** - * Minimum zoom level of the map. Overrides any minZoom set on map layers. - */ - minZoom?: number; - - /** - * Maximum zoom level of the map. This overrides any maxZoom set on map layers. - */ - maxZoom?: number; - - /** - * When this option is set, the map restricts the view to the given geographical - * bounds, bouncing the user back when he tries to pan outside the view, and also - * not allowing to zoom out to a view that's larger than the given bounds (depending - * on the map size). To set the restriction dynamically, use setMaxBounds method - */ - maxBounds?: LatLngBounds; - - /** - * Coordinate Reference System to use. Don't change this if you're not sure - * what it means. - * - * Default value: L.CRS.EPSG3857. - */ - crs?: ICRS; - - // Interaction Options - - /** - * Whether the map be draggable with mouse/touch or not. - * - * Default value: true. - */ - dragging?: boolean; - - /** - * Whether the map can be zoomed by touch-dragging with two fingers. - * - * Default value: true. - */ - touchZoom?: boolean; - - /** - * Whether the map can be zoomed by using the mouse wheel. - * If passed 'center', it will zoom to the center of the view regardless of - * where the mouse was. - * - * Default value: true. - */ - scrollWheelZoom?: boolean; - - /** - * Whether the map can be zoomed in by double clicking on it and zoomed out - * by double clicking while holding shift. - * If passed 'center', double-click zoom will zoom to the center of the view - * regardless of where the mouse was. - * - * Default value: true. - */ - doubleClickZoom?: boolean; - - /** - * Whether the map can be zoomed to a rectangular area specified by dragging - * the mouse while pressing shift. - * - * Default value: true. - */ - boxZoom?: boolean; - - /** - * Enables mobile hacks for supporting instant taps (fixing 200ms click delay - * on iOS/Android) and touch holds (fired as contextmenu events). - * - * Default value: true. - */ - tap?: boolean; - - /** - * The max number of pixels a user can shift his finger during touch for it - * to be considered a valid tap. - * - * Default value: 15. - */ - tapTolerance?: number; - - /** - * Whether the map automatically handles browser window resize to update itself. - * - * Default value: true. - */ - trackResize?: boolean; - - /** - * With this option enabled, the map tracks when you pan to another "copy" of - * the world and seamlessly jumps to the original one so that all overlays like - * markers and vector layers are still visible. - * - * Default value: false. - */ - worldCopyJump?: boolean; - - /** - * Set it to false if you don't want popups to close when user clicks the map. - * - * Default value: true. - */ - closePopupOnClick?: boolean; - - // Keyboard Navigation Options - - /** - * Makes the map focusable and allows users to navigate the map with keyboard - * arrows and +/- keys. - * - * Default value: true. - */ - keyboard?: boolean; - - /** - * Amount of pixels to pan when pressing an arrow key. - * - * Default value: 80. - */ - keyboardPanOffset?: number; - - /** - * Number of zoom levels to change when pressing + or - key. - * - * Default value: 1. - */ - keyboardZoomOffset?: number; - - // Panning Inertia Options - - /** - * If enabled, panning of the map will have an inertia effect where the map builds - * momentum while dragging and continues moving in the same direction for some - * time. Feels especially nice on touch devices. - * - * Default value: true. - */ - inertia?: boolean; - - /** - * The rate with which the inertial movement slows down, in pixels/second2. - * - * Default value: 3000. - */ - inertiaDeceleration?: number; - - /** - * Max speed of the inertial movement, in pixels/second. - * - * Default value: 1500. - */ - inertiaMaxSpeed?: number; - - /** - * Amount of milliseconds that should pass between stopping the movement and - * releasing the mouse or touch to prevent inertial movement. - * - * Default value: 32 for touch devices and 14 for the rest. - */ - inertiaThreshold?: number; + preferCanvas?: boolean; // Control options - - /** - * Whether the zoom control is added to the map by default. - * - * Default value: true. - */ + attributionControl?: boolean; zoomControl?: boolean; - /** - * Whether the attribution control is added to the map by default. - * - * Default value: true. - */ - attributionControl?: boolean; + // Interaction options + closePopupOnClick?: boolean; + zoomSnap?: number; + zoomDelta?: number; + trackResize?: boolean; + boxZoom?: boolean; + doubleClickZoom?: Zoom; + dragging?: boolean; + + // Map state options + crs?: CRS; + center?: LatLngExpression; + zoom?: number; + minZoom?: number; + maxZoom?: number; + layers?: Array; + maxBounds?: LatLngBoundsExpression; + renderer?: Renderer; // Animation options - - /** - * Whether the tile fade animation is enabled. By default it's enabled in all - * browsers that support CSS3 Transitions except Android. - */ fadeAnimation?: boolean; - - /** - * Whether the tile zoom animation is enabled. By default it's enabled in all - * browsers that support CSS3 Transitions except Android. - */ + markerZoomAnimation?: boolean; + transform3DLimit?: number; zoomAnimation?: boolean; - - /** - * Won't animate zoom if the zoom difference exceeds this value. - * - * Default value: 4. - */ zoomAnimationThreshold?: number; - /** - * Whether markers animate their zoom with the zoom animation, if disabled - * they will disappear for the length of the animation. By default it's enabled - * in all browsers that support CSS3 Transitions except Android. - */ - markerZoomAnimation?: boolean; + // Panning inertia options + inertia?: boolean; + inertiaDeceleration?: number; + inertiaMaxSpeed?: number; + easeLinearity?: number; + worldCopyJump?: boolean; + maxBoundsViscosity?: number; - /** - * Set it to false if you don't want the map to zoom beyond min/max zoom - * and then bounce back when pinch-zooming. - * - * Default value: true. - */ + // Keyboard navigation options + keyboard?: boolean; + keyboardPanDelta?: number; + + // Mousewheel options + scrollWheelZoom?: Zoom; + wheelDebounceTime?: number; + wheelPxPerZoomLevel?: number; + + // Touch interaction options + tap?: boolean; + tapTolerance?: number; + touchZoom?: Zoom; bounceAtZoomLimits?: boolean; } - export interface ZoomOptions { - /** - * If not specified, zoom animation will happen if the zoom origin is inside the current view. - * If true, the map will attempt animating zoom disregarding where zoom origin is. - * Setting false will make it always reset the view completely without animation. - */ - animate?: boolean; + export interface Control { + } - export interface ZoomPanOptions { - - /** - * If true, the map view will be completely reset (without any animations). - * - * Default value: false. - */ - reset?: boolean; - - /** - * Sets the options for the panning (without the zoom change) if it occurs. - */ - pan?: PanOptions; - - /** - * Sets the options for the zoom change if it occurs. - */ - zoom?: ZoomOptions; - - /** - * An equivalent of passing animate to both zoom and pan options (see below). - */ - animate?: boolean; - - /** - * If true, it will delay moveend event so that it doesn't happen many times in a row. - */ - debounceMoveend?: boolean; - - /** - * Duration of animated panning, in seconds. - */ - duration?: number; - - /** - * The curvature factor of panning animation easing (third parameter of the Cubic Bezier curve). - * 1.0 means linear animation, the less the more bowed the curve. - */ - easeLinearity?: number; - - /** - * If true, panning won't fire movestart event on start (used internally for panning inertia). - */ - noMoveStart?: boolean; + interface DivOverlayOptions { + offset?: PointExpression; + zoomAnimation?: boolean; + className?: string; + pane?: string; } - export interface FitBoundsOptions extends ZoomPanOptions { - - /** - * Sets the amount of padding in the top left corner of a map container that - * shouldn't be accounted for when setting the view to fit bounds. Useful if - * you have some control overlays on the map like a sidebar and you don't - * want them to obscure objects you're zooming to. - * - * Default value: [0, 0]. - */ - paddingTopLeft?: Point; - - /** - * The same for bottom right corner of the map. - * - * Default value: [0, 0]. - */ - paddingBottomRight?: Point; - - /** - * Equivalent of setting both top left and bottom right padding to the same value. - * - * Default value: [0, 0]. - */ - padding?: Point; - - /** - * The maximum possible zoom to use. - * - * Default value: null - */ - maxZoom?: number; + export interface PopupOptions extends DivOverlayOptions { + maxWidth?: number; + minWidth?: number; + maxHeight?: number; + autoPan?: boolean; + autoPanPaddingTopLeft?: PointExpression; + autoPanPaddingBottomRight?: PointExpression; + autoPanPadding?: PointExpression; + keepInView?: boolean; + closeButton?: boolean; + autoClose?: boolean; } -} -declare namespace L { + type Content = string | HTMLElement; - export interface MapPanes { - - /** - * Pane that contains all other map panes. - */ - mapPane: HTMLElement; - - /** - * Pane for tile layers. - */ - tilePane: HTMLElement; - - /** - * Pane that contains all the panes except tile pane. - */ - objectsPane: HTMLElement; - - /** - * Pane for overlay shadows (e.g. marker shadows). - */ - shadowPane: HTMLElement; - - /** - * Pane for overlays like polylines and polygons. - */ - overlayPane: HTMLElement; - - /** - * Pane for marker icons. - */ - markerPane: HTMLElement; - - /** - * Pane for popups. - */ - popupPane: HTMLElement; - } -} - -declare namespace L { - - /** - * Instantiates a Marker object given a geographical point and optionally - * an options object. - */ - function marker(latlng: LatLngExpression, options?: MarkerOptions): Marker; - - var Marker: { - /** - * Instantiates a Marker object given a geographical point and optionally - * an options object. - */ - new(latlng: LatLngExpression, options?: MarkerOptions): Marker; - }; - - export interface Marker extends ILayer, IEventPowered { - /** - * Adds the marker to the map. - */ - addTo(map: Map): Marker; - - /** - * Returns the current geographical position of the marker. - */ + export interface Popup extends Layer { getLatLng(): LatLng; - - /** - * Changes the marker position to the given point. - */ - setLatLng(latlng: LatLngExpression): Marker; - - /** - * Changes the marker icon. - */ - setIcon(icon: Icon): Marker; - - /** - * Changes the zIndex offset of the marker. - */ - setZIndexOffset(offset: number): Marker; - - /** - * Changes the opacity of the marker. - */ - setOpacity(opacity: number): Marker; - - /** - * Updates the marker position, useful if coordinates of its latLng object - * were changed directly. - */ - update(): Marker; - - /** - * Binds a popup with a particular HTML content to a click on this marker. You - * can also open the bound popup with the Marker openPopup method. - */ - bindPopup(html: string, options?: PopupOptions): Marker; - - /** - * Binds a popup with a particular HTML content to a click on this marker. You - * can also open the bound popup with the Marker openPopup method. - */ - bindPopup(el: HTMLElement, options?: PopupOptions): Marker; - - /** - * Binds a popup with a particular HTML content to a click on this marker. You - * can also open the bound popup with the Marker openPopup method. - */ - bindPopup(popup: Popup, options?: PopupOptions): Marker; - - /** - * Unbinds the popup previously bound to the marker with bindPopup. - */ - unbindPopup(): Marker; - - /** - * Opens the popup previously bound by the bindPopup method. - */ - openPopup(): Marker; - - /** - * Returns the popup previously bound by the bindPopup method. - */ - getPopup(): Popup; - - /** - * Closes the bound popup of the marker if it's opened. - */ - closePopup(): Marker; - - /** - * Toggles the popup previously bound by the bindPopup method. - */ - togglePopup(): Marker; - - /** - * Sets an HTML content of the popup of this marker. - */ - setPopupContent(html: string, options?: PopupOptions): Marker; - - /** - * Sets an HTML content of the popup of this marker. - */ - setPopupContent(el: HTMLElement, options?: PopupOptions): Marker; - - /** - * Returns a GeoJSON representation of the marker (GeoJSON Point Feature). - */ - toGeoJSON(): GeoJSON.Feature; - - /** - * Marker dragging handler (by both mouse and touch). - */ - dragging: IHandler; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Marker; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): Marker; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Marker; - fire(type: string, data?: any): Marker; - addEventListener(eventMap: any, context?: any): Marker; - removeEventListener(eventMap?: any, context?: any): Marker; - clearAllEventListeners(): Marker; - on(eventMap: any, context?: any): Marker; - off(eventMap?: any, context?: any): Marker; + setLatLng(latlng: LatLngExpression): this; + getContent(): Content; + setContent(htmlContent: string): this; + setContent(htmlContent: HTMLElement): this; + setContent(htmlContent: (source: Layer) => Content): this; + getElement(): Content; + update(): void; + isOpen(): boolean; + bringToFront(): this; + bringToBack(): this; + openOn(map: Map): this; } -} -declare namespace L { + export function popup(options?: PopupOptions, source?: Layer): Popup; - export interface MarkerOptions { + export type Direction = 'right' | 'left' | 'top' | 'bottom' | 'center' | 'auto'; - /** - * Icon class to use for rendering the marker. See Icon documentation for details - * on how to customize the marker icon. - * - * Default value: new L.Icon.Default(). - */ - icon?: Icon; - - /** - * If false, the marker will not emit mouse events and will act as a part of the - * underlying map. - * - * Default value: true. - */ - clickable?: boolean; - - /** - * Whether the marker is draggable with mouse/touch or not. - * - * Default value: false. - */ - draggable?: boolean; - - /** - * Whether the marker can be tabbed to with a keyboard and clicked by pressing enter. - * - * Default value: true. - */ - keyboard?: boolean; - - /** - * Text for the browser tooltip that appear on marker hover (no tooltip by default). - * - * Default value: ''. - */ - title?: string; - - /** - * Text for the alt attribute of the icon image (useful for accessibility). - * - * Default value: ''. - */ - alt?: string; - - /** - * By default, marker images zIndex is set automatically based on its latitude. - * You this option if you want to put the marker on top of all others (or below), - * specifying a high value like 1000 (or high negative value, respectively). - * - * Default value: 0. - */ - zIndexOffset?: number; - - /** - * The opacity of the marker. - * - * Default value: 1.0. - */ + export interface TooltipOptions extends DivOverlayOptions { + pane?: string; + offset?: PointExpression; + direction?: Direction; + permanent?: boolean; + sticky?: boolean; + interactive?: boolean; opacity?: number; - - /** - * If true, the marker will get on top of others when you hover the mouse over it. - * - * Default value: false. - */ - riseOnHover?: boolean; - - /** - * The z-index offset used for the riseOnHover feature. - * - * Default value: 250. - */ - riseOffset?: number; } -} -declare namespace L { + export interface Tooltip extends Layer {} - /** - * Instantiates a multi-polyline object given an array of latlngs arrays (one - * for each individual polygon) and optionally an options object (the same - * as for MultiPolyline). - */ - function multiPolygon(latlngs: LatLng[][], options?: PolylineOptions): MultiPolygon; + export function tooltip(options?: TooltipOptions, source?: Layer): Tooltip; - export interface MultiPolygonStatic extends ClassStatic { - /** - * Instantiates a multi-polyline object given an array of latlngs arrays (one - * for each individual polygon) and optionally an options object (the same - * as for MultiPolyline). - */ - new(latlngs: LatLng[][], options?: PolylineOptions): MultiPolygon; + export interface ZoomOptions { + animate?: boolean; } - export var MultiPolygon: MultiPolygonStatic; - - export interface MultiPolygon extends FeatureGroup { - /** - * Replace all polygons and their paths with the given array of arrays - * of geographical points. - */ - setLatLngs(latlngs: LatLng[][]): MultiPolygon; - - /** - * Returns an array of arrays of geographical points in each polygon. - */ - getLatLngs(): LatLng[][]; - - /** - * Opens the popup previously bound by bindPopup. - */ - openPopup(): MultiPolygon; - - /** - * Returns a GeoJSON representation of the multipolygon (GeoJSON MultiPolygon Feature). - */ - toGeoJSON(): GeoJSON.Feature; - } -} - -declare namespace L { - - /** - * Instantiates a multi-polyline object given an array of arrays of geographical - * points (one for each individual polyline) and optionally an options object. - */ - function multiPolyline(latlngs: LatLng[][], options?: PolylineOptions): MultiPolyline; - - export interface MultiPolylineStatic extends ClassStatic { - /** - * Instantiates a multi-polyline object given an array of arrays of geographical - * points (one for each individual polyline) and optionally an options object. - */ - new(latlngs: LatLng[][], options?: PolylineOptions): MultiPolyline; - } - export var MultiPolyline: MultiPolylineStatic; - - export interface MultiPolyline extends FeatureGroup { - /** - * Replace all polygons and their paths with the given array of arrays - * of geographical points. - */ - setLatLngs(latlngs: LatLng[][]): MultiPolyline; - - /** - * Returns an array of arrays of geographical points in each polygon. - */ - getLatLngs(): LatLng[][]; - - /** - * Opens the popup previously bound by bindPopup. - */ - openPopup(): MultiPolyline; - - /** - * Returns a GeoJSON representation of the multipolyline (GeoJSON MultiLineString Feature). - */ - toGeoJSON(): GeoJSON.Feature; - } -} - -declare namespace L { export interface PanOptions { - - /** - * If true, panning will always be animated if possible. If false, it will not - * animate panning, either resetting the map view if panning more than a screen - * away, or just setting a new offset for the map pane (except for `panBy` - * which always does the latter). - */ animate?: boolean; - - /** - * Duration of animated panning. - * - * Default value: 0.25. - */ duration?: number; - - /** - * The curvature factor of panning animation easing (third parameter of the Cubic - * Bezier curve). 1.0 means linear animation, the less the more bowed the curve. - * - * Default value: 0.25. - */ easeLinearity?: number; - - /** - * If true, panning won't fire movestart event on start (used internally for panning inertia). - * - * Default value: false. - */ noMoveStart?: boolean; } -} -declare namespace L { + export interface ZoomPanOptions extends ZoomOptions, PanOptions {} - export interface Path extends ILayer, IEventPowered { - - /** - * Adds the layer to the map. - */ - addTo(map: Map): Path; - - /** - * Binds a popup with a particular HTML content to a click on this path. - */ - bindPopup(html: string, options?: PopupOptions): Path; - - /** - * Binds a popup with a particular HTML content to a click on this path. - */ - bindPopup(el: HTMLElement, options?: PopupOptions): Path; - - /** - * Binds a popup with a particular HTML content to a click on this path. - */ - bindPopup(popup: Popup, options?: PopupOptions): Path; - - /** - * Unbinds the popup previously bound to the path with bindPopup. - */ - unbindPopup(): Path; - - /** - * Opens the popup previously bound by the bindPopup method in the given point, - * or in one of the path's points if not specified. - */ - openPopup(latlng?: LatLngExpression): Path; - - /** - * Closes the path's bound popup if it is opened. - */ - closePopup(): Path; - - /** - * Changes the appearance of a Path based on the options in the Path options object. - */ - setStyle(object: PathOptions): Path; - - /** - * Returns the LatLngBounds of the path. - */ - getBounds(): LatLngBounds; - - /** - * Brings the layer to the top of all path layers. - */ - bringToFront(): Path; - - /** - * Brings the layer to the bottom of all path layers. - */ - bringToBack(): Path; - - /** - * Redraws the layer. Sometimes useful after you changed the coordinates that - * the path uses. - */ - redraw(): Path; - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Path; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): Path; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Path; - fire(type: string, data?: any): Path; - addEventListener(eventMap: any, context?: any): Path; - removeEventListener(eventMap?: any, context?: any): Path; - clearAllEventListeners(): Path; - on(eventMap: any, context?: any): Path; - off(eventMap?: any, context?: any): Path; - } - - export namespace Path { - /** - * True if SVG is used for vector rendering (true for most modern browsers). - */ - export var SVG: boolean; - - /** - * True if VML is used for vector rendering (IE 6-8). - */ - export var VML: boolean; - - /** - * True if Canvas is used for vector rendering (Android 2). You can also force - * this by setting global variable L_PREFER_CANVAS to true before the Leaflet - * include on your page — sometimes it can increase performance dramatically - * when rendering thousands of circle markers, but currently suffers from - * a bug that causes removing such layers to be extremely slow. - */ - export var CANVAS: boolean; - - /** - * How much to extend the clip area around the map view (relative to its size, - * e.g. 0.5 is half the screen in each direction). Smaller values mean that you - * will see clipped ends of paths while you're dragging the map, and bigger values - * decrease drawing performance. - */ - export var CLIP_PADDING: number; - } -} - -declare namespace L { - - export interface PathOptions { - - /** - * Whether to draw stroke along the path. Set it to false to disable borders on - * polygons or circles. - * - * Default value: true. - */ - stroke?: boolean; - - /** - * Stroke color. - * - * Default value: '#03f'. - */ - color?: string; - - /** - * Stroke width in pixels. - * - * Default value: 5. - */ - weight?: number; - - /** - * Stroke opacity. - * - * Default value: 0.5. - */ - opacity?: number; - - /** - * Whether to fill the path with color. Set it to false to disable filling on polygons - * or circles. - */ - fill?: boolean; - - /** - * Fill color. - * - * Default value: same as color. - */ - fillColor?: string; - - /** - * Fill opacity. - * - * Default value: 0.2. - */ - fillOpacity?: number; - - /** - * A string that defines the stroke dash pattern. Doesn't work on canvas-powered - * layers (e.g. Android 2). - */ - dashArray?: string; - - /** - * A string that defines shape to be used at the end of the stroke. - * - * Default: null. - */ - lineCap?: string; - - /** - * A string that defines shape to be used at the corners of the stroke. - * - * Default: null. - */ - lineJoin?: string; - - /** - * If false, the vector will not emit mouse events and will act as a part of the - * underlying map. - * - * Default value: true. - */ - clickable?: boolean; - - /** - * Sets the pointer-events attribute on the path if SVG backend is used. - */ - pointerEvents?: string; - - /** - * Custom class name set on an element. - * - * Default value: ''. - */ - className?: string; - - /** - * Sets the radius of a circle marker. - */ - radius?: number; - - } -} - -declare namespace L { - - /** - * Creates a Point object with the given x and y coordinates. If optional round - * is set to true, rounds the x and y values. - */ - function point(x: number, y: number, round?: boolean): Point; - - export interface PointStatic { - /** - * Creates a Point object with the given x and y coordinates. If optional round - * is set to true, rounds the x and y values. - */ - new(x: number, y: number, round?: boolean): Point; - } - export var Point: PointStatic; - - export interface Point { - /** - * Returns the result of addition of the current and the given points. - */ - add(otherPoint: Point): Point; - - /** - * Returns the result of subtraction of the given point from the current. - */ - subtract(otherPoint: Point): Point; - - /** - * Returns the result of multiplication of the current point by the given number. - */ - multiplyBy(number: number): Point; - - /** - * Returns the result of division of the current point by the given number. If - * optional round is set to true, returns a rounded result. - */ - divideBy(number: number, round?: boolean): Point; - - /** - * Returns the distance between the current and the given points. - */ - distanceTo(otherPoint: Point): number; - - /** - * Returns a copy of the current point. - */ - clone(): Point; - - /** - * Returns a copy of the current point with rounded coordinates. - */ - round(): Point; - - /** - * Returns true if the given point has the same coordinates. - */ - equals(otherPoint: Point): boolean; - - /** - * Returns a string representation of the point for debugging purposes. - */ - toString(): string; - - /** - * The x coordinate. - */ - x: number; - - /** - * The y coordinate. - */ - y: number; - } -} - -declare namespace L { - - /** - * Instantiates a polygon object given an array of geographical points and - * optionally an options object (the same as for Polyline). You can also create - * a polygon with holes by passing an array of arrays of latlngs, with the first - * latlngs array representing the exterior ring while the remaining represent - * the holes inside. - */ - function polygon(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polygon; - - - export interface PolygonStatic extends ClassStatic { - /** - * Instantiates a polygon object given an array of geographical points and - * optionally an options object (the same as for Polyline). You can also create - * a polygon with holes by passing an array of arrays of latlngs, with the first - * latlngs array representing the exterior ring while the remaining represent - * the holes inside. - */ - new(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polygon; - } - export var Polygon: PolygonStatic; - - export interface Polygon extends Polyline { - } -} - -declare namespace L { - - /** - * Instantiates a polyline object given an array of geographical points and - * optionally an options object. - */ - function polyline(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polyline; - - export interface PolylineStatic extends ClassStatic { - /** - * Instantiates a polyline object given an array of geographical points and - * optionally an options object. - */ - new(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polyline; - } - export var Polyline: PolylineStatic; - - export interface Polyline extends Path { - /** - * Adds a given point to the polyline. - */ - addLatLng(latlng: LatLngExpression): Polyline; - - /** - * Replaces all the points in the polyline with the given array of geographical - * points. - */ - setLatLngs(latlngs: LatLngBoundsExpression): Polyline; - - /** - * Returns an array of the points in the path. - */ - getLatLngs(): LatLng[]; - - /** - * Allows adding, removing or replacing points in the polyline. Syntax is the - * same as in Array#splice. Returns the array of removed points (if any). - */ - spliceLatLngs(index: number, pointsToRemove: number, ...latlngs: LatLng[]): LatLng[]; - - /** - * Returns the LatLngBounds of the polyline. - */ - getBounds(): LatLngBounds; - - /** - * Returns a GeoJSON representation of the polyline (GeoJSON LineString Feature). - */ - toGeoJSON(): GeoJSON.Feature; - } -} - -declare namespace L { - - export interface PolylineOptions extends PathOptions { - - /** - * How much to simplify the polyline on each zoom level. More means better performance - * and smoother look, and less means more accurate representation. - * - * Default value: 1.0. - */ - smoothFactor?: number; - - /** - * Disabled polyline clipping. - * - * Default value: false. - */ - noClip?: boolean; - } -} - -declare namespace L { - - namespace PolyUtil { - - /** - * Clips the polygon geometry defined by the given points by rectangular bounds. - * Used by Leaflet to only show polygon points that are on the screen or near, - * increasing performance. Note that polygon points needs different algorithm - * for clipping than polyline, so there's a seperate method for it. - */ - export function clipPolygon(points: Point[], bounds: Bounds): Point[]; - } -} - -declare namespace L { - - /** - * Instantiates a Popup object given an optional options object that describes - * its appearance and location and an optional object that is used to tag the - * popup with a reference to the source object to which it refers. - */ - function popup(options?: PopupOptions, source?: any): Popup; - - export interface PopupStatic extends ClassStatic { - /** - * Instantiates a Popup object given an optional options object that describes - * its appearance and location and an optional object that is used to tag the - * popup with a reference to the source object to which it refers. - */ - new(options?: PopupOptions, source?: any): Popup; - } - export var Popup: PopupStatic; - - export interface Popup extends ILayer { - /** - * Adds the popup to the map. - */ - addTo(map: Map): Popup; - - /** - * Adds the popup to the map and closes the previous one. The same as map.openPopup(popup). - */ - openOn(map: Map): Popup; - - /** - * Sets the geographical point where the popup will open. - */ - setLatLng(latlng: LatLngExpression): Popup; - - /** - * Returns the geographical point of popup. - */ - getLatLng(): LatLng; - - /** - * Sets the HTML content of the popup. - */ - setContent(html: string): Popup; - - /** - * Sets the HTML content of the popup. - */ - setContent(el: HTMLElement): Popup; - - /** - * Returns the content of the popup. - */ - getContent(): HTMLElement; - //getContent(): string; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - /** - * Updates the popup content, layout and position. Useful for updating the popup after - * something inside changed, e.g. image loaded. - */ - update(): Popup; - } -} - -declare namespace L { - - export interface PopupOptions { - - /** - * Max width of the popup. - * - * Default value: 300. - */ - maxWidth?: number; - - /** - * Min width of the popup. - * - * Default value: 50. - */ - minWidth?: number; - - /** - * If set, creates a scrollable container of the given height inside a popup - * if its content exceeds it. - */ - maxHeight?: number; - - /** - * Set it to false if you don't want the map to do panning animation to fit the opened - * popup. - * - * Default value: true. - */ - autoPan?: boolean; - - /** - * Set it to true if you want to prevent users from panning the popup off of the screen while it is open. - */ - keepInView?: boolean; - - /** - * Controls the presense of a close button in the popup. - * - * Default value: true. - */ - closeButton?: boolean; - - /** - * The offset of the popup position. Useful to control the anchor of the popup - * when opening it on some overlays. - * - * Default value: new Point(0, 6). - */ - offset?: Point; - - /** - * The margin between the popup and the top left corner of the map view after - * autopanning was performed. - * - * Default value: null. - */ - autoPanPaddingTopLeft?: Point; - - /** - * The margin between the popup and the bottom right corner of the map view after - * autopanning was performed. - * - * Default value: null. - */ - autoPanPaddingBottomRight?: Point; - - /** - * The margin between the popup and the edges of the map view after autopanning - * was performed. - * - * Default value: new Point(5, 5). - */ - autoPanPadding?: Point; - - /** - * Whether to animate the popup on zoom. Disable it if you have problems with - * Flash content inside popups. - * - * Default value: true. - */ - zoomAnimation?: boolean; - - /** - * Set it to false if you want to override the default behavior of the popup - * closing when user clicks the map (set globally by the Map closePopupOnClick - * option). - */ - closeOnClick?: boolean; - - /** - * A custom class name to assign to the popup. - */ - className?: string; - } -} - -declare namespace L { - - export interface PosAnimationStatic extends ClassStatic { - /** - * Creates a PosAnimation object. - */ - new(): PosAnimation; - } - export var PosAnimation: PosAnimationStatic; - - export interface PosAnimation extends IEventPowered { - /** - * Run an animation of a given element to a new position, optionally setting - * duration in seconds (0.25 by default) and easing linearity factor (3rd argument - * of the cubic bezier curve, 0.5 by default) - */ - run(element: HTMLElement, newPos: Point, duration?: number, easeLinearity?: number): PosAnimation; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): PosAnimation; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): PosAnimation; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): PosAnimation; - fire(type: string, data?: any): PosAnimation; - addEventListener(eventMap: any, context?: any): PosAnimation; - removeEventListener(eventMap?: any, context?: any): PosAnimation; - clearAllEventListeners(): PosAnimation; - on(eventMap: any, context?: any): PosAnimation; - off(eventMap?: any, context?: any): PosAnimation; - } -} - -declare namespace L { - - namespace Projection { - - /** - * Spherical Mercator projection — the most common projection for online maps, - * used by almost all free and commercial tile providers. Assumes that Earth - * is a sphere. Used by the EPSG:3857 CRS. - */ - export var SphericalMercator: IProjection; - - /** - * Elliptical Mercator projection — more complex than Spherical Mercator. - * Takes into account that Earth is a geoid, not a perfect sphere. Used by the - * EPSG:3395 CRS. - */ - export var Mercator: IProjection; - - /** - * Equirectangular, or Plate Carree projection — the most simple projection, - * mostly used by GIS enthusiasts. Directly maps x as longitude, and y as latitude. - * Also suitable for flat worlds, e.g. game maps. Used by the EPSG:3395 and Simple - * CRS. - */ - export var LonLat: IProjection; - } -} - -declare namespace L { - - /** - * Instantiates a rectangle object with the given geographical bounds and - * optionally an options object. - */ - function rectangle(bounds: LatLngBounds, options?: PathOptions): Rectangle; - - export interface RectangleStatic extends ClassStatic { - /** - * Instantiates a rectangle object with the given geographical bounds and - * optionally an options object. - */ - new(bounds: LatLngBounds, options?: PathOptions): Rectangle; - } - export var Rectangle: RectangleStatic; - - export interface Rectangle extends Polygon { - /** - * Redraws the rectangle with the passed bounds. - */ - setBounds(bounds: LatLngBounds): Rectangle; - } -} - - -declare namespace L { - - export interface ScaleOptions { - - /** - * The position of the control (one of the map corners). See control positions. - * Default value: 'bottomleft'. - */ - position?: PositionString; - - /** - * Maximum width of the control in pixels. The width is set dynamically to show - * round values (e.g. 100, 200, 500). - * Default value: 100. - */ - maxWidth?: number; - - /** - * Whether to show the metric scale line (m/km). - * Default value: true. - */ - metric?: boolean; - - /** - * Whether to show the imperial scale line (mi/ft). - * Default value: true. - */ - imperial?: boolean; - - /** - * If true, the control is updated on moveend, otherwise it's always up-to-date - * (updated on move). - * Default value: false. - */ - updateWhenIdle?: boolean; - } -} - -declare namespace L { - - export interface TileLayerStatic extends ClassStatic { - /** - * Instantiates a tile layer object given a URL template and optionally an options - * object. - */ - new(urlTemplate: string, options?: TileLayerOptions): TileLayer; - - WMS: { - /** - * Instantiates a WMS tile layer object given a base URL of the WMS service and - * a WMS parameters/options object. - */ - new(baseUrl: string, options: WMSOptions): TileLayer.WMS; - }; - - Canvas: { - /** - * Instantiates a Canvas tile layer object given an options object (optionally). - */ - new(options?: TileLayerOptions): TileLayer.Canvas; - }; - } - export var TileLayer: TileLayerStatic; - - export interface TileLayer extends ILayer, IEventPowered { - /** - * Adds the layer to the map. - */ - addTo(map: Map): TileLayer; - - /** - * Brings the tile layer to the top of all tile layers. - */ - bringToFront(): TileLayer; - - /** - * Brings the tile layer to the bottom of all tile layers. - */ - bringToBack(): TileLayer; - - /** - * Changes the opacity of the tile layer. - */ - setOpacity(opacity: number): TileLayer; - - /** - * Sets the zIndex of the tile layer. - */ - setZIndex(zIndex: number): TileLayer; - - /** - * Causes the layer to clear all the tiles and request them again. - */ - redraw(): TileLayer; - - /** - * Updates the layer's URL template and redraws it. - */ - setUrl(urlTemplate: string): TileLayer; - - /** - * Returns the HTML element that contains the tiles for this layer. - */ - getContainer(): HTMLElement; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): TileLayer; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): TileLayer; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): TileLayer; - fire(type: string, data?: any): TileLayer; - addEventListener(eventMap: any, context?: any): TileLayer; - removeEventListener(eventMap?: any, context?: any): TileLayer; - clearAllEventListeners(): TileLayer; - on(eventMap: any, context?: any): TileLayer; - off(eventMap?: any, context?: any): TileLayer; - } - - namespace TileLayer { - export interface WMS extends TileLayer { - /** - * Merges an object with the new parameters and re-requests tiles on the current - * screen (unless noRedraw was set to true). - */ - setParams(params: WMS, noRedraw?: boolean): WMS; - } - - export interface Canvas extends TileLayer { - /** - * You need to define this method after creating the instance to draw tiles; - * canvas is the actual canvas tile on which you can draw, tilePoint represents - * the tile numbers, and zoom is the current zoom. - */ - drawTile(canvas: HTMLCanvasElement, tilePoint: Point, zoom: number): Canvas; - - /** - * Calling redraw will cause the drawTile method to be called for all tiles. - * May be used for updating dynamic content drawn on the Canvas - */ - redraw(): Canvas; - } - } - - export interface TileLayerFactory { - - /** - * Instantiates a tile layer object given a URL template and optionally an options - * object. - */ - (urlTemplate: string, options?: TileLayerOptions): TileLayer; - - /** - * Instantiates a WMS tile layer object given a base URL of the WMS service and - * a WMS parameters/options object. - */ - wms(baseUrl: string, options: WMSOptions): L.TileLayer.WMS; - - /** - * Instantiates a Canvas tile layer object given an options object (optionally). - */ - canvas(options?: TileLayerOptions): L.TileLayer.Canvas; - } - - export var tileLayer: TileLayerFactory; -} - -declare namespace L { - - export interface TileLayerOptions { - - /** - * Minimum zoom number. - * - * Default value: 0. - */ - minZoom?: number; - - /** - * Maximum zoom number. - * - * Default value: 18. - */ + export interface FitBoundsOptions extends ZoomOptions, PanOptions { + paddingTopLeft?: PointExpression; + paddingBottomRight?: PointExpression; + padding?: PointExpression; maxZoom?: number; + } - /** - * Maximum zoom number the tiles source has available. If it is specified, - * the tiles on all zoom levels higher than maxNativeZoom will be loaded from - * maxZoom level and auto-scaled. - * - * Default value: null. - */ - maxNativeZoom?: number; + export interface LocateOptions { + watch?: boolean; + setView?: boolean; + maxZoom?: number; + timeout?: number; + maximumAge?: number; + enableHighAccuracy?: boolean; + } - /** - * Tile size (width and height in pixels, assuming tiles are square). - * - * Default value: 256. - */ - tileSize?: number; + export interface Handler { + enable(): this; + disable(): this; + enabled(): boolean; - /** - * Subdomains of the tile service. Can be passed in the form of one string (where - * each letter is a subdomain name) or an array of strings. - * - * Default value: 'abc'. - */ - subdomains?: string|string[]; + // Extension methods + addHooks(): void; + removeHooks(): void; + } - /** - * URL to the tile image to show in place of the tile that failed to load. - * - * Default value: ''. - */ - errorTileUrl?: string; + export interface Event { + type: string; + target: any; // should this be Object and have users cast? + } - /** - * e.g. "© CloudMade" — the string used by the attribution control, describes - * the layer data. - * - * Default value: ''. - */ - attribution?: string; + export interface MouseEvent extends Event { + latlng: LatLng; + layerPoint: Point; + containerPoint: Point; + originalEvent: MouseEvent; // how can I reference the global MouseEvent? + } - /** - * If true, inverses Y axis numbering for tiles (turn this on for TMS services). - * - * Default value: false. - */ - tms?: boolean; + export interface LocationEvent extends Event { + latlng: LatLng; + bounds: LatLngBounds; + accuracy: number; + altitude: number; + altitudeAccuracy: number; + heading: number; + speed: number; + timestamp: number; + } - /** - * If set to true, the tile coordinates won't be wrapped by world width (-180 - * to 180 longitude) or clamped to lie within world height (-90 to 90). Use this - * if you use Leaflet for maps that don't reflect the real world (e.g. game, indoor - * or photo maps). - * - * Default value: false. - */ - continuousWorld?: boolean; + export interface ErrorEvent extends Event { + message: string; + code: number; + } - /** - * If set to true, the tiles just won't load outside the world width (-180 to 180 - * longitude) instead of repeating. - * - * Default value: false. - */ - noWrap?: boolean; + export interface LayerEvent extends Event { + layer: Layer; + } - /** - * The zoom number used in tile URLs will be offset with this value. - * - * Default value: 0. - */ - zoomOffset?: number; + export interface LayersControlEvent extends LayerEvent { + name: string; + } - /** - * If set to true, the zoom number used in tile URLs will be reversed (maxZoom - * - zoom instead of zoom) - * - * Default value: false. - */ - zoomReverse?: boolean; + export interface TileEvent extends Event { + tile: HTMLImageElement; + coords: Point; // apparently not a normal point, since docs say it has z (zoom) + } - /** - * The opacity of the tile layer. - * - * Default value: 1.0. - */ + export interface TileErrorEvent extends TileEvent { + error: Error; + } + + export interface ResizeEvent extends Event { + oldSize: Point; + newSize: Point; + } + + export interface GeoJSONEvent extends Event { + layer: Layer; + properties: any; // any or Object? + geometryType: string; + id: string; + } + + export interface PopupEvent extends Event { + popup: Popup; + } + + export interface TooltipEvent extends Event { + tooltip: Tooltip; + } + + export interface DragEndEvent extends Event { + distance: number; + } + + interface DefaultMapPanes { + mapPane: HTMLElement; + tilePane: HTMLElement; + overlayPane: HTMLElement; + shadowPane: HTMLElement; + markerPane: HTMLElement; + tooltipPane: HTMLElement; + popupPane: HTMLElement; + } + + export interface Map extends Evented { + getRenderer(layer: Path): Renderer; + + // Methods for layers and controls + addControl(control: Control): this; + removeControl(control: Control): this; + addLayer(layer: Layer): this; + removeLayer(layer: Layer): this; + hasLayer(layer: Layer): boolean; + eachLayer(fn: (layer: Layer) => void, context?: Object): this; + openPopup(popup: Popup): this; + openPopup(content: string, latlng: LatLng, options?: PopupOptions): this; + openPopup(content: string, latlng: LatLngLiteral, options?: PopupOptions): this; + openPopup(content: string, latlng: LatLngTuple, options?: PopupOptions): this; + openPopup(content: HTMLElement, latlng: LatLng, options?: PopupOptions): this; + openPopup(content: HTMLElement, latlng: LatLngLiteral, options?: PopupOptions): this; + openPopup(content: HTMLElement, latlng: LatLngTuple, options?: PopupOptions): this; + closePopup(popup?: Popup): this; + openTooltip(tooltip: Tooltip): this; + openTooltip(content: string, latlng: LatLng, options?: TooltipOptions): this; + openTooltip(content: string, latlng: LatLngLiteral, options?: TooltipOptions): this; + openTooltip(content: string, latlng: LatLngTuple, options?: TooltipOptions): this; + openTooltip(content: HTMLElement, latlng: LatLng, options?: TooltipOptions): this; + openTooltip(content: HTMLElement, latlng: LatLngLiteral, options?: TooltipOptions): this; + openTooltip(content: HTMLElement, latlng: LatLngTuple, options?: TooltipOptions): this; + closeTooltip(tooltip?: Tooltip): this; + + // Methods for modifying map state + setView(center: LatLng, zoom: number, options?: ZoomPanOptions): this; + setView(center: LatLngLiteral, zoom: number, options?: ZoomPanOptions): this; + setView(center: LatLngTuple, zoom: number, options?: ZoomPanOptions): this; + setZoom(zoom: number, options: ZoomPanOptions): this; + zoomIn(delta?: number, options?: ZoomOptions): this; + zoomOut(delta?: number, options?: ZoomOptions): this; + setZoomAround(latlng: LatLng, zoom: number, options: ZoomOptions): this; + setZoomAround(latlng: LatLngLiteral, zoom: number, options: ZoomOptions): this; + setZoomAround(latlng: LatLngTuple, zoom: number, options: ZoomOptions): this; // will the latlng version using tuple take precedence or will the point tuple version? + setZoomAround(offset: Point, zoom: number, options: ZoomOptions): this; + fitBounds(bounds: LatLngBounds, options: FitBoundsOptions): this; + fitBounds(bounds: LatLngBoundsLiteral, options: FitBoundsOptions): this; + fitWorld(options?: FitBoundsOptions): this; + panTo(latlng: LatLng, options?: PanOptions): this; + panTo(latlng: LatLngLiteral, options?: PanOptions): this; + panTo(latlng: LatLngTuple, options?: PanOptions): this; + panBy(offset: Point): this; + panBy(offset: PointTuple): this; + setMaxBounds(bounds: Bounds): this; // is this really bounds and not lanlngbounds? + setMaxBounds(bounds: BoundsLiteral): this; + setMinZoom(zoom: number): this; + setMaxZoom(zoom: number): this; + panInsideBounds(bounds: LatLngBounds, options?: PanOptions): this; + panInsideBounds(bounds: LatLngBoundsLiteral, options?: PanOptions): this; + invalidateSize(options: ZoomPanOptions): this; + invalidateSize(animate: boolean): this; + stop(): this; + flyTo(latlng: LatLng, zoom?: number, options?: ZoomPanOptions): this; + flyTo(latlng: LatLngLiteral, zoom?: number, options?: ZoomPanOptions): this; + flyTo(latlng: LatLngTuple, zoom?: number, options?: ZoomPanOptions): this; + flyToBounds(bounds: LatLngBounds, options?: FitBoundsOptions): this; + flyToBounds(bounds: LatLngBoundsLiteral, options?: FitBoundsOptions): this; + + // Other methods + addHandler(name: string, HandlerClass: () => Handler): this; // HandlerClass is actually a constructor function, is this the right way? + remove(): this; + createPane(name: string, container?: HTMLElement): HTMLElement; + getPane(pane: string): HTMLElement; + getPane(pane: HTMLElement): HTMLElement; + getPanes(): {[name: string]: HTMLElement} & DefaultMapPanes; + getContainer(): HTMLElement; + whenReady(fn: () => void, context?: Object): this; + + // Methods for getting map state + getCenter(): LatLng; + getZoom(): number; + getBounds(): LatLngBounds; + getMinZoom(): number; + getMaxZoom(): number; + getBoundsZoom(bounds: LatLngBounds, inside?: boolean): number; + getBoundsZoom(bounds: LatLngBoundsLiteral, inside?: boolean): number; + getSize(): Point; + getPixelBounds(): Bounds; + getPixelOrigin(): Point; + getPixelWorldBounds(zoom?: number): Bounds; + + // Conversion methods + getZoomScale(toZoom: number, fromZoom: number): number; + getScaleZoom(scale: number, fromZoom: number): number; + project(latlng: LatLng, zoom: number): Point; + project(latlng: LatLngLiteral, zoom: number): Point; + project(latlng: LatLngTuple, zoom: number): Point; + unproject(point: Point, zoom: number): LatLng; + unproject(point: PointTuple, zoom: number): LatLng; + layerPointToLatLng(point: Point): LatLng; + layerPointToLatLng(point: PointTuple): LatLng; + latLngToLayerPoint(latlng: LatLng): Point; + latLngToLayerPoint(latlng: LatLngLiteral): Point; + latLngToLayerPoint(latlng: LatLngTuple): Point; + wrapLatLng(latlng: LatLng): LatLng; + wrapLatLng(latlng: LatLngLiteral): LatLng; + wrapLatLng(latlng: LatLngTuple): LatLng; + distance(latlng1: LatLng, latlng2: LatLng): number; + distance(latlng1: LatLngLiteral, latlng2: LatLngLiteral): number; + distance(latlng1: LatLngTuple, latlng2: LatLngTuple): number; + containerPointToLayerPoint(point: Point): Point; + containerPointToLayerPoint(point: PointTuple): Point; + layerPointToContainerPoint(point: Point): Point; + layerPointToContainerPoint(point: PointTuple): Point; + latLngToContainerPoint(latlng: LatLng): Point; + latLngToContainerPoint(latlng: LatLngLiteral): Point; + latLngToContainerPoint(latlng: LatLngTuple): Point; + mouseEventToContainerPoint(ev: MouseEvent): Point; + mouseEventToLayerPoint(ev: MouseEvent): Point; + mouseEventToLatLng(ev: MouseEvent): LatLng; + + // Geolocation methods + locate(options?: LocateOptions): this; + stopLocate(): this; + + // Properties + boxZoom: Handler; + doubleClickZoom: Handler; + dragging: Handler; + keyboard: Handler; + scrollWheelZoom: Handler; + tap: Handler; + touchZoom: Handler; + } + + export function map(id: string, options?: MapOptions): Map; + + export function map(el: HTMLElement, options?: MapOptions): Map; + + export interface IconOptions extends LayerOptions { + iconUrl: string; + iconRetinaUrl?: string; + iconSize?: PointExpression; + iconAnchor?: PointExpression; + popupAnchor?: PointExpression; + shadowUrl?: string; + shadowRetinaUrl?: string; + shadowSize?: PointExpression; + shadowAnchor?: PointExpression; + className?: string; + } + + export interface Icon extends Layer { + createIcon(oldIcon?: HTMLElement): HTMLElement; + createShadow(oldIcon?: HTMLElement): HTMLElement; + } + + export namespace Icon { + export const Default: Icon; + } + + export function icon(options: IconOptions): Icon; + + export interface DivIconOptions extends LayerOptions { + html?: string; + bgPos?: PointExpression; + iconSize?: PointExpression; + iconAnchor?: PointExpression; + popupAnchor?: PointExpression; + className?: string; + } + + export interface DivIcon extends Icon {} + + export function divIcon(options: DivIconOptions): DivIcon; + + export interface MarkerOptions extends InteractiveLayerOptions { + icon?: Icon; + draggable?: boolean; + keyboard?: boolean; + title?: string; + alt?: string; + zIndexOffset?: number; opacity?: number; - - /** - * The explicit zIndex of the tile layer. Not set by default. - */ - zIndex?: number; - - /** - * If true, all the tiles that are not visible after panning are removed (for - * better performance). true by default on mobile WebKit, otherwise false. - */ - unloadInvisibleTiles?: boolean; - - /** - * If false, new tiles are loaded during panning, otherwise only after it (for - * better performance). true by default on mobile WebKit, otherwise false. - */ - updateWhenIdle?: boolean; - - /** - * If true and user is on a retina display, it will request four tiles of half the - * specified size and a bigger zoom level in place of one to utilize the high resolution. - * - * Default value: false. - */ - detectRetina?: boolean; - - /** - * If true, all the tiles that are not visible after panning are placed in a reuse - * queue from which they will be fetched when new tiles become visible (as opposed - * to dynamically creating new ones). This will in theory keep memory usage - * low and eliminate the need for reserving new memory whenever a new tile is - * needed. - * - * Default value: false. - */ - reuseTiles?: boolean; - - /** - * When this option is set, the TileLayer only loads tiles that are in the given geographical bounds. - */ - bounds?: LatLngBounds; - - /** - * Custom keys may be specified in TileLayerOptions so they can be used in a provided URL template. - */ - [additionalKeys: string]: any; + riseOnHover?: boolean; + riseOffset?: number; } + + export interface Marker extends Layer { + getLatLng(): LatLng; + setLatLng(latlng: LatLng): this; + setLatLng(latlng: LatLngLiteral): this; + setLatLng(latlng: LatLngTuple): this; + setZIndexOffset(offset: number): this; + setIcon(icon: Icon): this; + setOpacity(opacity: number): this; + + // Properties + dragging: Handler; + } + + export function marker(latlng: LatLng, options?: MarkerOptions): Marker; + + export function marker(latlng: LatLngLiteral, options?: MarkerOptions): Marker; + + export function marker(latlng: LatLngTuple, options?: MarkerOptions): Marker; } -declare namespace L { - export interface TransformationStatic { - /** - * Creates a transformation object with the given coefficients. - */ - new(a: number, b: number, c: number, d: number): Transformation; - } - export var Transformation: TransformationStatic; - - export interface Transformation { - /** - * Returns a transformed point, optionally multiplied by the given scale. - * Only accepts real L.Point instances, not arrays. - */ - transform(point: Point, scale?: number): Point; - - /** - * Returns the reverse transformation of the given point, optionally divided - * by the given scale. Only accepts real L.Point instances, not arrays. - */ - untransform(point: Point, scale?: number): Point; - } +declare module 'leaflet' { + export = L; } - -declare namespace L { - - namespace Util { - - /** - * Merges the properties of the src object (or multiple objects) into dest object - * and returns the latter. Has an L.extend shortcut. - */ - export function extend(dest: any, ...sources: any[]): any; - - /** - * Returns a function which executes function fn with the given scope obj (so - * that this keyword refers to obj inside the function code). Has an L.bind shortcut. - */ - export function bind(fn: T, obj: any): T; - - /** - * Applies a unique key to the object and returns that key. Has an L.stamp shortcut. - */ - export function stamp(obj: any): string; - - /** - * Returns a wrapper around the function fn that makes sure it's called not more - * often than a certain time interval time, but as fast as possible otherwise - * (for example, it is used for checking and requesting new tiles while dragging - * the map), optionally passing the scope (context) in which the function will - * be called. - */ - export function limitExecByInterval(fn: T, time: number, context?: any): T; - - /** - * Returns a function which always returns false. - */ - export function falseFn(): () => boolean; - - /** - * Returns the number num rounded to digits decimals. - */ - export function formatNum(num: number, digits: number): number; - - /** - * Trims and splits the string on whitespace and returns the array of parts. - */ - export function splitWords(str: string): string[]; - - /** - * Merges the given properties to the options of the obj object, returning the - * resulting options. See Class options. Has an L.setOptions shortcut. - */ - export function setOptions(obj: any, options: any): any; - - /** - * Converts an object into a parameter URL string, e.g. {a: "foo", b: "bar"} - * translates to '?a=foo&b=bar'. - */ - export function getParamString(obj: any): string; - - /** - * Simple templating facility, creates a string by applying the values of the - * data object of a form {a: 'foo', b: 'bar', …} to a template string of the form - * 'Hello {a}, {b}' — in this example you will get 'Hello foo, bar'. - */ - export function template(str: string, data: any): string; - - /** - * Returns true if the given object is an array. - */ - export function isArray(obj: any): boolean; - - /** - * Trims the whitespace from both ends of the string and returns the result. - */ - export function trim(str: string): string; - - /** - * Data URI string containing a base64-encoded empty GIF image. Used as a hack - * to free memory from unused images on WebKit-powered mobile devices (by setting - * image src to this string). - */ - export var emptyImageUrl: string; - } -} - - -declare namespace L { - - export interface WMSOptions { - - /** - * (required) Comma-separated list of WMS layers to show. - * - * Default value: ''. - */ - layers?: string; - - /** - * Comma-separated list of WMS styles. - * - * Default value: 'image/jpeg'. - */ - styles?: string; - - /** - * WMS image format (use 'image/png' for layers with transparency). - * - * Default value: false. - */ - format?: string; - - /** - * If true, the WMS service will return images with transparency. - * - * Default value: '1.1.1'. - */ - transparent?: boolean; - - /** - * Version of the WMS service to use. - */ - version?: string; - - } -} - -/** - * Forces Leaflet to use the Canvas back-end (if available) for vector layers - * instead of SVG. This can increase performance considerably in some cases - * (e.g. many thousands of circle markers on the map). - */ -declare var L_PREFER_CANVAS: boolean; - -/** - * Forces Leaflet to not use touch events even if it detects them. - */ -declare var L_NO_TOUCH: boolean; - -/** - * Forces Leaflet to not use hardware-accelerated CSS 3D transforms for positioning - * (which may cause glitches in some rare environments) even if they're supported. - */ -declare var L_DISABLE_3D: boolean; - -declare module "leaflet" { - export = L; -} - -// vim: et ts=4 sw=4 diff --git a/mapbox/mapbox.d.ts b/mapbox/mapbox.d.ts index 9d341174ea..83e51ebf0e 100644 --- a/mapbox/mapbox.d.ts +++ b/mapbox/mapbox.d.ts @@ -3,7 +3,7 @@ // Definitions by: Maxime Fabre // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// ////////////////////////////////////////////////////////////////////// ///////////////////////////// MAP OBJECT ///////////////////////////// diff --git a/material-ui/material-ui.d.ts b/material-ui/material-ui.d.ts index f9dcbcfb38..af69e80b1f 100644 --- a/material-ui/material-ui.d.ts +++ b/material-ui/material-ui.d.ts @@ -344,6 +344,9 @@ declare namespace __MaterialUI { disabledTextColor?: string; connectorLineColor?: string; }; + svgIcon?: { + color?: string, + }; table?: { backgroundColor?: string; }; @@ -513,8 +516,8 @@ declare namespace __MaterialUI { iconClassNameRight?: string; iconElementLeft?: React.ReactElement; iconElementRight?: React.ReactElement; - iconStyleRight?: string; - iconStyleLeft?: string; + iconStyleRight?: React.CSSProperties; + iconStyleLeft?: React.CSSProperties; onLeftIconButtonTouchTap?: TouchTapEventHandler; onRightIconButtonTouchTap?: TouchTapEventHandler; onTitleTouchTap?: TouchTapEventHandler; diff --git a/mongoose-sequence/mongoose-sequence-tests.ts b/mongoose-sequence/mongoose-sequence-tests.ts new file mode 100644 index 0000000000..7962afeeb4 --- /dev/null +++ b/mongoose-sequence/mongoose-sequence-tests.ts @@ -0,0 +1,52 @@ +/// +/// +/// + +/** + * Based on the examples on: https://github.com/ramiel/mongoose-sequence + * Created by Linus Brolin . + */ + +import { SequenceDocument, SequenceOptions, SequenceSchema, Document, Schema, Model, model } from 'mongoose'; +import * as mongooseSequence from 'mongoose-sequence'; + +//#region Test Models +interface User extends SequenceDocument { + name: string; + country: string; + city: string; + inhabitant_number: number; +} + +const UserSchema: SequenceSchema = new Schema({ + name: String, + country: String, + city: String, + inhabitant_number: Number +}); + +let seqOpts: SequenceOptions = { id: 'inhabitant_seq', inc_field: 'inhabitant_number', reference_fields: ['country', 'city'] }; +UserSchema.plugin(mongooseSequence, seqOpts); + +let UserModel: Model = model('User', UserSchema); +//#endregion + +//#region Test Sequence +let user: User = new UserModel({ + name: 'Patrice', + country: 'France', + city: 'Paris' +}); +user.save(); +console.log(user.inhabitant_number); + +user.setNext('inhabitant_seq', function(err: any, user: User) { + if (err) { + console.log(err); + return; + } + if (user) { + console.log(user.inhabitant_number); + } +}); +//#endregion diff --git a/mongoose-sequence/mongoose-sequence.d.ts b/mongoose-sequence/mongoose-sequence.d.ts new file mode 100644 index 0000000000..b0dec033bd --- /dev/null +++ b/mongoose-sequence/mongoose-sequence.d.ts @@ -0,0 +1,36 @@ +// Type definitions for mongoose-sequence 3.0.2 +// Project: https://github.com/ramiel/mongoose-sequence +// Definitions by: Linus Brolin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'mongoose' { + export interface SequenceOptions { + inc_field: string; // The name of the field to increment. Mandatory, default is _id + id?: string; // Id of the sequence. Is mandatory only for scoped sequences but its use is strongly encouraged. + reference_fields?: Array; // The field to reference for a scoped counter. Optional + disable_hooks?: boolean; // If true, the counter will not be incremented on saving a new document. Default to false + collection_name?: string; // By default the collection name to mantain the status of the counters is counters. You can override it using this option + } + + export interface SequenceDocument extends Document { + setNext(sequenceId: string, callback: (err: any, res: SequenceDocument) => void): void; + } + + export interface SequenceSchema extends Schema { + plugin( + plugin: (schema: SequenceSchema, options: SequenceOptions) => void, + options: SequenceOptions + ): this; + + // overload for the default mongoose plugin function + plugin(plugin: (schema: Schema, options?: Object) => void, opts?: Object): this; + } +} + +declare module 'mongoose-sequence' { + import mongoose = require('mongoose'); + var _: (schema: mongoose.Schema, options?: Object) => void; + export = _; +} diff --git a/navigation/navigation-tests.ts b/navigation/navigation-tests.ts index c1b6e45ff9..52e6bfded4 100644 --- a/navigation/navigation-tests.ts +++ b/navigation/navigation-tests.ts @@ -37,10 +37,11 @@ namespace NavigationTests { person.navigated = (data) => {}; person.urlEncode = function urlEncode(state: Navigation.State, key: string, val: string, queryString: boolean): string { return queryString ? val.replace(/\s/g, '+') : encodeURIComponent(val); - } + }; person.urlDecode = function urlDecode(state: Navigation.State, key: string, val: string, queryString: boolean): string { return queryString ? val.replace(/\+/g, ' ') : decodeURIComponent(val); - } + }; + person.validate = (data: any) => data.id > 0; // Navigation Event var navigationListener = (oldState: Navigation.State, state: Navigation.State, data: any, asyncData: any) => { diff --git a/navigation/navigation.d.ts b/navigation/navigation.d.ts index ad3c1c8e23..1ae460a9f3 100644 --- a/navigation/navigation.d.ts +++ b/navigation/navigation.d.ts @@ -138,6 +138,12 @@ declare namespace Navigation { * @param queryString A value indicating the Url value's location */ urlDecode(state: State, key: string, val: string, queryString: boolean): string; + /** + * Validates the NavigationData before navigating to the new State + * @param data The new NavigationData + * @returns Validation success indicator + */ + validate(data: any): boolean; /** * Truncates the crumb trail whenever a repeated or initial State is * encountered @@ -178,9 +184,9 @@ declare namespace Navigation { */ getHref(url: string): string; /** - * Gets a Url from the anchor + * Gets a Url from the anchor or location */ - getUrl(anchor: HTMLAnchorElement): string; + getUrl(hrefElement: HTMLAnchorElement | Location): string; /** * Removes browser history event listeners */ @@ -230,9 +236,9 @@ declare namespace Navigation { */ getHref(url: string): string; /** - * Gets a Url from the anchor + * Gets a Url from the anchor or location */ - getUrl(anchor: HTMLAnchorElement): string; + getUrl(hrefElement: HTMLAnchorElement | Location): string; /** * Removes a listener for the hashchange event */ @@ -281,9 +287,9 @@ declare namespace Navigation { */ getHref(url: string): string; /** - * Gets a Url from the anchor + * Gets a Url from the anchor or location */ - getUrl(anchor: HTMLAnchorElement): string; + getUrl(hrefElement: HTMLAnchorElement | Location): string; /** * Removes a listener for the popstate event */ @@ -381,10 +387,6 @@ declare namespace Navigation { * Crumb first */ crumbs: Crumb[]; - /** - * Gets the crumb trail - */ - crumbTrail: string[]; /** * Gets the next crumb */ diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 0162951454..26e201c910 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -28,37 +28,36 @@ import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer /// Assert Tests : https://nodejs.org/api/assert.html /// ////////////////////////////////////////////////////////// -namespace assert_tests{ +namespace assert_tests { { assert(1 + 1 - 2 === 0, "The universe isn't how it should."); - + assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP"); - - // TODO: assert.deepStrictEqual - + + assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator"); + assert.doesNotThrow(() => { const b = false; if (b) { throw "a hammer at your face"; } }, undefined, "What the...*crunch*"); - + assert.equal(3, "3", "uses == comparator"); - // TODO: assert.fail - - // TODO: assert.ifError - - assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses === comparator"); - - // TODO: assert.notDeepStrictEqual - - // TODO: assert.notEqual - + assert.fail(1, 2, undefined, '>'); + + assert.ifError(0); + + assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator"); + + assert.notEqual(1, 2, "uses != comparator"); + assert.notStrictEqual(2, "2", "uses === comparator"); - - // TODO: assert.ok - - // TODO: assert.strictEqual - + + assert.ok(true); + assert.ok(1); + + assert.strictEqual(1, 1, "uses === comparator"); + assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); } } @@ -109,6 +108,16 @@ namespace events_tests { result = emitter.emit(event, any, any); result = emitter.emit(event, any, any, any); } + + { + class Networker extends events.EventEmitter { + constructor() { + super(); + + this.emit("mingling"); + } + } + } } //////////////////////////////////////////////////// @@ -136,13 +145,13 @@ namespace fs_tests { var buffer: Buffer; content = fs.readFileSync('testfile', 'utf8'); - content = fs.readFileSync('testfile', {encoding : 'utf8'}); + content = fs.readFileSync('testfile', { encoding: 'utf8' }); buffer = fs.readFileSync('testfile'); - buffer = fs.readFileSync('testfile', {flag : 'r'}); + buffer = fs.readFileSync('testfile', { flag: 'r' }); fs.readFile('testfile', 'utf8', (err, data) => content = data); - fs.readFile('testfile', {encoding : 'utf8'}, (err, data) => content = data); + fs.readFile('testfile', { encoding: 'utf8' }, (err, data) => content = data); fs.readFile('testfile', (err, data) => buffer = data); - fs.readFile('testfile', {flag : 'r'}, (err, data) => buffer = data); + fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data); } { @@ -168,21 +177,13 @@ namespace fs_tests { } -class Networker extends events.EventEmitter { - constructor() { - super(); - - this.emit("mingling"); - } -} - /////////////////////////////////////////////////////// /// Buffer tests : https://nodejs.org/api/buffer.html /////////////////////////////////////////////////////// function bufferTests() { var utf8Buffer = new Buffer('test'); - var base64Buffer = new Buffer('','base64'); + var base64Buffer = new Buffer('', 'base64'); var octets: Uint8Array = null; var octetBuffer = new Buffer(octets); var sharedBuffer = new Buffer(octets.buffer); @@ -196,7 +197,7 @@ function bufferTests() { // Class Method: Buffer.from(array) { - const buf: Buffer = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + const buf: Buffer = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); } // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) @@ -261,8 +262,8 @@ function bufferTests() { // Buffer has Uint8Array's buffer field (an ArrayBuffer). { - let buffer = new Buffer('123'); - let octets = new Uint8Array(buffer.buffer); + let buffer = new Buffer('123'); + let octets = new Uint8Array(buffer.buffer); } } @@ -274,14 +275,14 @@ function bufferTests() { namespace url_tests { { url.format(url.parse('http://www.example.com/xyz')); - + // https://google.com/search?q=you're%20a%20lizard%2C%20gary url.format({ protocol: 'https', host: "google.com", pathname: 'search', query: { q: "you're a lizard, gary" } - }); + }); } { @@ -298,7 +299,7 @@ namespace util_tests { { // Old and new util.inspect APIs util.inspect(["This is nice"], false, 5); - util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); + util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); } } @@ -315,113 +316,121 @@ function stream_readable_pipe_test() { r.close(); } -//////////////////////////////////////////////////// -/// Crypto tests : http://nodejs.org/api/crypto.html -//////////////////////////////////////////////////// +//////////////////////////////////////////////////////// +/// Crypto tests : http://nodejs.org/api/crypto.html /// +//////////////////////////////////////////////////////// -var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); +namespace crypto_tests { + { + var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); + } -{ - let hmac: crypto.Hmac; - (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { - let hash: Buffer|string = hmac.read(); + { + let hmac: crypto.Hmac; + (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { + let hash: Buffer | string = hmac.read(); + }); + } + + { + //crypto_cipher_decipher_string_test + let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let clearText: string = "This is the clear text."; + let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherText: string = cipher.update(clearText, "utf8", "hex"); + cipherText += cipher.final("hex"); + + let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let clearText2: string = decipher.update(cipherText, "hex", "utf8"); + clearText2 += decipher.final("utf8"); + + assert.equal(clearText2, clearText); + } + + { + //crypto_cipher_decipher_buffer_test + let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let clearText: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); + let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherBuffers: Buffer[] = []; + cipherBuffers.push(cipher.update(clearText)); + cipherBuffers.push(cipher.final()); + + let cipherText: Buffer = Buffer.concat(cipherBuffers); + + let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let decipherBuffers: Buffer[] = []; + decipherBuffers.push(decipher.update(cipherText)); + decipherBuffers.push(decipher.final()); + + let clearText2: Buffer = Buffer.concat(decipherBuffers); + + assert.deepEqual(clearText2, clearText); + } +} + +////////////////////////////////////////////////// +/// TLS tests : http://nodejs.org/api/tls.html /// +////////////////////////////////////////////////// + +namespace tls_tests { + var ctx: tls.SecureContext = tls.createSecureContext({ + key: "NOT REALLY A KEY", + cert: "SOME CERTIFICATE", }); -} + var blah = ctx.context; -function crypto_cipher_decipher_string_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:string = "This is the clear text."; - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherText:string = cipher.update(clearText, "utf8", "hex"); - cipherText += cipher.final("hex"); - - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var clearText2:string = decipher.update(cipherText, "hex", "utf8"); - clearText2 += decipher.final("utf8"); - - assert.equal(clearText2, clearText); -} - -function crypto_cipher_decipher_buffer_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherBuffers:Buffer[] = []; - cipherBuffers.push(cipher.update(clearText)); - cipherBuffers.push(cipher.final()); - - var cipherText:Buffer = Buffer.concat(cipherBuffers); - - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var decipherBuffers:Buffer[] = []; - decipherBuffers.push(decipher.update(cipherText)); - decipherBuffers.push(decipher.final()); - - var clearText2:Buffer = Buffer.concat(decipherBuffers); - - assert.deepEqual(clearText2, clearText); + var connOpts: tls.ConnectionOptions = { + host: "127.0.0.1", + port: 55 + }; + var tlsSocket = tls.connect(connOpts); } //////////////////////////////////////////////////// -/// TLS tests : http://nodejs.org/api/tls.html +/// Http tests : http://nodejs.org/api/http.html /// //////////////////////////////////////////////////// -var ctx: tls.SecureContext = tls.createSecureContext({ - key: "NOT REALLY A KEY", - cert: "SOME CERTIFICATE", -}); -var blah = ctx.context; - -var tlsOpts: tls.TlsOptions = { - host: "127.0.0.1", - port: 55 -}; -var tlsSocket = tls.connect(tlsOpts); - - -//////////////////////////////////////////////////// - -// Make sure .listen() and .close() retuern a Server instance -http.createServer().listen(0).close().address(); -net.createServer().listen(0).close().address(); - -var request = http.request('http://0.0.0.0'); -request.once('error', function () {}); -request.setNoDelay(true); -request.abort(); - -//////////////////////////////////////////////////// -/// Http tests : http://nodejs.org/api/http.html -//////////////////////////////////////////////////// namespace http_tests { - // Status codes - var code = 100; - var codeMessage = http.STATUS_CODES['400']; - var codeMessage = http.STATUS_CODES[400]; + { + // Status codes + var codeMessage = http.STATUS_CODES['400']; + var codeMessage = http.STATUS_CODES[400]; + } - var agent: http.Agent = new http.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256 - }); + { + var agent: http.Agent = new http.Agent({ + keepAlive: true, + keepAliveMsecs: 10000, + maxSockets: Infinity, + maxFreeSockets: 256 + }); - var agent: http.Agent = http.globalAgent; + var agent: http.Agent = http.globalAgent; - http.request({ - agent: false - }); - http.request({ - agent: agent - }); - http.request({ - agent: undefined - }); + http.request({ agent: false }); + http.request({ agent: agent }); + http.request({ agent: undefined }); + } + + { + // Make sure .listen() and .close() retuern a Server instance + http.createServer().listen(0).close().address(); + net.createServer().listen(0).close().address(); + } + + { + var request = http.request('http://0.0.0.0'); + request.once('error', function() { }); + request.setNoDelay(true); + request.abort(); + } } -//////////////////////////////////////////////////// -/// Https tests : http://nodejs.org/api/https.html -//////////////////////////////////////////////////// +////////////////////////////////////////////////////// +/// Https tests : http://nodejs.org/api/https.html /// +////////////////////////////////////////////////////// + namespace https_tests { var agent: https.Agent = new https.Agent({ keepAlive: true, @@ -478,7 +487,7 @@ namespace dgram_tests { //////////////////////////////////////////////////// namespace querystring_tests { - type SampleObject = {a: string; b: number;} + type SampleObject = { a: string; b: number; } { let obj: SampleObject; @@ -531,7 +540,7 @@ namespace path_tests { try { path.join('foo', {}, 'bar'); } - catch(error) { + catch (error) { } @@ -645,11 +654,11 @@ namespace path_tests { // } path.format({ - root : "/", - dir : "/home/user/dir", - base : "file.txt", - ext : ".txt", - name : "file" + root: "/", + dir: "/home/user/dir", + base: "file.txt", + ext: ".txt", + name: "file" }); // returns // '/home/user/dir/file.txt' @@ -715,7 +724,7 @@ namespace readline_tests { } { - let data: string|Buffer; + let data: string | Buffer; let key: readline.Key; rl.write(data); @@ -732,8 +741,8 @@ namespace readline_tests { { let stream: NodeJS.WritableStream; - let dx: number|string; - let dy: number|string; + let dx: number | string; + let dy: number | string; readline.moveCursor(stream, dx, dy); } @@ -771,7 +780,7 @@ namespace string_decoder_tests { namespace child_process_tests { { childProcess.exec("echo test"); - childProcess.spawnSync("echo test"); + childProcess.spawnSync("echo test"); } } @@ -779,7 +788,7 @@ namespace child_process_tests { /// cluster tests: https://nodejs.org/api/cluster.html /// ////////////////////////////////////////////////////////////////////// -namespace cluster_tests { +namespace cluster_tests  { { cluster.fork(); Object.keys(cluster.workers).forEach(key => { @@ -831,7 +840,7 @@ namespace os_tests { } { - let result: {[index: string]: os.NetworkInterfaceInfo[]}; + let result: { [index: string]: os.NetworkInterfaceInfo[] }; result = os.networkInterfaces(); } @@ -905,14 +914,13 @@ namespace errors_tests { /////////////////////////////////////////////////////////// import * as p from "process"; -namespace process_tests{ +namespace process_tests { { var eventEmitter: events.EventEmitter; eventEmitter = process; // Test that process implements EventEmitter... - + var _p: NodeJS.Process = process; _p = p; - assert(p === process); } } @@ -921,8 +929,20 @@ namespace process_tests{ /////////////////////////////////////////////////////////// import * as c from "console"; -namespace console_tests{ +namespace console_tests { { - assert(c === console); + var _c: Console = console; + _c = c; + } +} + +/////////////////////////////////////////////////// +/// Net Tests : https://nodejs.org/api/net.html /// +/////////////////////////////////////////////////// + +namespace net_tests { + { + // Make sure .listen() and .close() retuern a Server instance + net.createServer().listen(0).close().address(); } } diff --git a/node/node-4.d.ts b/node/node-4.d.ts index daebb4585e..f05444336d 100644 --- a/node/node-4.d.ts +++ b/node/node-4.d.ts @@ -430,7 +430,7 @@ declare namespace NodeJS { interface NodeBuffer extends Uint8Array { write(string: string, offset?: number, length?: number, encoding?: string): number; toString(encoding?: string, start?: number, end?: number): string; - toJSON(): any; + toJSON(): {type: 'Buffer', data: any[]}; equals(otherBuffer: Buffer): boolean; compare(otherBuffer: Buffer): number; copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; diff --git a/node/node-tests.ts b/node/node-tests.ts index 651df8ca09..1fcf149e99 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -30,37 +30,36 @@ import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer /// Assert Tests : https://nodejs.org/api/assert.html /// ////////////////////////////////////////////////////////// -namespace assert_tests{ +namespace assert_tests { { assert(1 + 1 - 2 === 0, "The universe isn't how it should."); - + assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP"); - - // TODO: assert.deepStrictEqual - + + assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator"); + assert.doesNotThrow(() => { const b = false; if (b) { throw "a hammer at your face"; } }, undefined, "What the...*crunch*"); - + assert.equal(3, "3", "uses == comparator"); - // TODO: assert.fail - - // TODO: assert.ifError - - assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses === comparator"); - - // TODO: assert.notDeepStrictEqual - - // TODO: assert.notEqual - + assert.fail(1, 2, undefined, '>'); + + assert.ifError(0); + + assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator"); + + assert.notEqual(1, 2, "uses != comparator"); + assert.notStrictEqual(2, "2", "uses === comparator"); - - // TODO: assert.ok - - // TODO: assert.strictEqual - + + assert.ok(true); + assert.ok(1); + + assert.strictEqual(1, 1, "uses === comparator"); + assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); } } @@ -119,6 +118,16 @@ namespace events_tests { result = emitter.eventNames(); } + + { + class Networker extends events.EventEmitter { + constructor() { + super(); + + this.emit("mingling"); + } + } + } } //////////////////////////////////////////////////// @@ -130,31 +139,31 @@ namespace fs_tests { fs.writeFile("thebible.txt", "Do unto others as you would have them do unto you.", assert.ifError); - + fs.write(1234, "test"); - + fs.writeFile("Harry Potter", "\"You be wizzing, Harry,\" jived Dumbledore.", { encoding: "ascii" }, - assert.ifError); + assert.ifError); } { var content: string; var buffer: Buffer; - + content = fs.readFileSync('testfile', 'utf8'); - content = fs.readFileSync('testfile', {encoding : 'utf8'}); + content = fs.readFileSync('testfile', { encoding: 'utf8' }); buffer = fs.readFileSync('testfile'); - buffer = fs.readFileSync('testfile', {flag : 'r'}); + buffer = fs.readFileSync('testfile', { flag: 'r' }); fs.readFile('testfile', 'utf8', (err, data) => content = data); - fs.readFile('testfile', {encoding : 'utf8'}, (err, data) => content = data); + fs.readFile('testfile', { encoding: 'utf8' }, (err, data) => content = data); fs.readFile('testfile', (err, data) => buffer = data); - fs.readFile('testfile', {flag : 'r'}, (err, data) => buffer = data); + fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data); } - + { var errno: string; fs.readFile('testfile', (err, data) => { @@ -163,71 +172,63 @@ namespace fs_tests { } }); } - + { fs.mkdtemp('/tmp/foo-', (err, folder) => { console.log(folder); // Prints: /tmp/foo-itXde2 }); } - + { var tempDir: string; tempDir = fs.mkdtempSync('/tmp/foo-'); } - + { fs.watch('/tmp/foo-', (event, filename) => { - console.log(event, filename); + console.log(event, filename); }); - + fs.watch('/tmp/foo-', 'utf8', (event, filename) => { - console.log(event, filename); + console.log(event, filename); }); - + fs.watch('/tmp/foo-', { - recursive: true, - persistent: true, - encoding: 'utf8' + recursive: true, + persistent: true, + encoding: 'utf8' }, (event, filename) => { - console.log(event, filename); + console.log(event, filename); }); } - + { - fs.access('/path/to/folder', (err) => {}); - - fs.access(Buffer.from(''), (err) => {}); - - fs.access('/path/to/folder', fs.constants.F_OK | fs.constants.R_OK, (err) => {}); - - fs.access(Buffer.from(''), fs.constants.F_OK | fs.constants.R_OK, (err) => {}); - + fs.access('/path/to/folder', (err) => { }); + + fs.access(Buffer.from(''), (err) => { }); + + fs.access('/path/to/folder', fs.constants.F_OK | fs.constants.R_OK, (err) => { }); + + fs.access(Buffer.from(''), fs.constants.F_OK | fs.constants.R_OK, (err) => { }); + fs.accessSync('/path/to/folder'); - + fs.accessSync(Buffer.from('')); - + fs.accessSync('path/to/folder', fs.constants.W_OK | fs.constants.X_OK); - + fs.accessSync(Buffer.from(''), fs.constants.W_OK | fs.constants.X_OK); } } -class Networker extends events.EventEmitter { - constructor() { - super(); - - this.emit("mingling"); - } -} - /////////////////////////////////////////////////////// /// Buffer tests : https://nodejs.org/api/buffer.html /////////////////////////////////////////////////////// function bufferTests() { var utf8Buffer = new Buffer('test'); - var base64Buffer = new Buffer('','base64'); + var base64Buffer = new Buffer('', 'base64'); var octets: Uint8Array = null; var octetBuffer = new Buffer(octets); var sharedBuffer = new Buffer(octets.buffer); @@ -249,7 +250,7 @@ function bufferTests() { // Class Method: Buffer.from(array) { - const buf: Buffer = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + const buf: Buffer = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); } // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) @@ -372,8 +373,8 @@ function bufferTests() { // Buffer has Uint8Array's buffer field (an ArrayBuffer). { - let buffer = new Buffer('123'); - let octets = new Uint8Array(buffer.buffer); + let buffer = new Buffer('123'); + let octets = new Uint8Array(buffer.buffer); } } @@ -385,14 +386,14 @@ function bufferTests() { namespace url_tests { { url.format(url.parse('http://www.example.com/xyz')); - + // https://google.com/search?q=you're%20a%20lizard%2C%20gary url.format({ protocol: 'https', host: "google.com", pathname: 'search', query: { q: "you're a lizard, gary" } - }); + }); } { @@ -409,7 +410,7 @@ namespace util_tests { { // Old and new util.inspect APIs util.inspect(["This is nice"], false, 5); - util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); + util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); } } @@ -429,18 +430,18 @@ function stream_readable_pipe_test() { // Simplified constructors function simplified_stream_ctor_test() { new stream.Readable({ - read: function (size) { + read: function(size) { size.toFixed(); } }); new stream.Writable({ - write: function (chunk, enc, cb) { + write: function(chunk, enc, cb) { chunk.slice(1); enc.charAt(0); cb() }, - writev: function (chunks, cb) { + writev: function(chunks, cb) { chunks[0].chunk.slice(0); chunks[0].encoding.charAt(0); cb(); @@ -448,15 +449,15 @@ function simplified_stream_ctor_test() { }); new stream.Duplex({ - read: function (size) { + read: function(size) { size.toFixed(); }, - write: function (chunk, enc, cb) { + write: function(chunk, enc, cb) { chunk.slice(1); enc.charAt(0); cb() }, - writev: function (chunks, cb) { + writev: function(chunks, cb) { chunks[0].chunk.slice(0); chunks[0].encoding.charAt(0); cb(); @@ -466,23 +467,23 @@ function simplified_stream_ctor_test() { }); new stream.Transform({ - transform: function (chunk, enc, cb) { + transform: function(chunk, enc, cb) { chunk.slice(1); enc.charAt(0); cb(); }, - flush: function (cb) { + flush: function(cb) { cb() }, - read: function (size) { + read: function(size) { size.toFixed(); }, - write: function (chunk, enc, cb) { + write: function(chunk, enc, cb) { chunk.slice(1); enc.charAt(0); cb() }, - writev: function (chunks, cb) { + writev: function(chunks, cb) { chunks[0].chunk.slice(0); chunks[0].encoding.charAt(0); cb(); @@ -490,113 +491,121 @@ function simplified_stream_ctor_test() { }) } -//////////////////////////////////////////////////// -/// Crypto tests : http://nodejs.org/api/crypto.html -//////////////////////////////////////////////////// +//////////////////////////////////////////////////////// +/// Crypto tests : http://nodejs.org/api/crypto.html /// +//////////////////////////////////////////////////////// -var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); +namespace crypto_tests { + { + var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); + } -{ - let hmac: crypto.Hmac; - (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { - let hash: Buffer|string = hmac.read(); + { + let hmac: crypto.Hmac; + (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { + let hash: Buffer | string = hmac.read(); + }); + } + + { + //crypto_cipher_decipher_string_test + let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let clearText: string = "This is the clear text."; + let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherText: string = cipher.update(clearText, "utf8", "hex"); + cipherText += cipher.final("hex"); + + let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let clearText2: string = decipher.update(cipherText, "hex", "utf8"); + clearText2 += decipher.final("utf8"); + + assert.equal(clearText2, clearText); + } + + { + //crypto_cipher_decipher_buffer_test + let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let clearText: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); + let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherBuffers: Buffer[] = []; + cipherBuffers.push(cipher.update(clearText)); + cipherBuffers.push(cipher.final()); + + let cipherText: Buffer = Buffer.concat(cipherBuffers); + + let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let decipherBuffers: Buffer[] = []; + decipherBuffers.push(decipher.update(cipherText)); + decipherBuffers.push(decipher.final()); + + let clearText2: Buffer = Buffer.concat(decipherBuffers); + + assert.deepEqual(clearText2, clearText); + } +} + +////////////////////////////////////////////////// +/// TLS tests : http://nodejs.org/api/tls.html /// +////////////////////////////////////////////////// + +namespace tls_tests { + var ctx: tls.SecureContext = tls.createSecureContext({ + key: "NOT REALLY A KEY", + cert: "SOME CERTIFICATE", }); -} + var blah = ctx.context; -function crypto_cipher_decipher_string_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:string = "This is the clear text."; - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherText:string = cipher.update(clearText, "utf8", "hex"); - cipherText += cipher.final("hex"); - - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var clearText2:string = decipher.update(cipherText, "hex", "utf8"); - clearText2 += decipher.final("utf8"); - - assert.equal(clearText2, clearText); -} - -function crypto_cipher_decipher_buffer_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherBuffers:Buffer[] = []; - cipherBuffers.push(cipher.update(clearText)); - cipherBuffers.push(cipher.final()); - - var cipherText:Buffer = Buffer.concat(cipherBuffers); - - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var decipherBuffers:Buffer[] = []; - decipherBuffers.push(decipher.update(cipherText)); - decipherBuffers.push(decipher.final()); - - var clearText2:Buffer = Buffer.concat(decipherBuffers); - - assert.deepEqual(clearText2, clearText); + var connOpts: tls.ConnectionOptions = { + host: "127.0.0.1", + port: 55 + }; + var tlsSocket = tls.connect(connOpts); } //////////////////////////////////////////////////// -/// TLS tests : http://nodejs.org/api/tls.html +/// Http tests : http://nodejs.org/api/http.html /// //////////////////////////////////////////////////// -var ctx: tls.SecureContext = tls.createSecureContext({ - key: "NOT REALLY A KEY", - cert: "SOME CERTIFICATE", -}); -var blah = ctx.context; - -var connOpts: tls.ConnectionOptions = { - host: "127.0.0.1", - port: 55 -}; -var tlsSocket = tls.connect(connOpts); - - -//////////////////////////////////////////////////// - -// Make sure .listen() and .close() retuern a Server instance -http.createServer().listen(0).close().address(); -net.createServer().listen(0).close().address(); - -var request = http.request('http://0.0.0.0'); -request.once('error', function () {}); -request.setNoDelay(true); -request.abort(); - -//////////////////////////////////////////////////// -/// Http tests : http://nodejs.org/api/http.html -//////////////////////////////////////////////////// namespace http_tests { - // Status codes - var code = 100; - var codeMessage = http.STATUS_CODES['400']; - var codeMessage = http.STATUS_CODES[400]; + { + // Status codes + var codeMessage = http.STATUS_CODES['400']; + var codeMessage = http.STATUS_CODES[400]; + } - var agent: http.Agent = new http.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256 - }); + { + var agent: http.Agent = new http.Agent({ + keepAlive: true, + keepAliveMsecs: 10000, + maxSockets: Infinity, + maxFreeSockets: 256 + }); - var agent: http.Agent = http.globalAgent; + var agent: http.Agent = http.globalAgent; - http.request({ - agent: false - }); - http.request({ - agent: agent - }); - http.request({ - agent: undefined - }); + http.request({ agent: false }); + http.request({ agent: agent }); + http.request({ agent: undefined }); + } + + { + // Make sure .listen() and .close() retuern a Server instance + http.createServer().listen(0).close().address(); + net.createServer().listen(0).close().address(); + } + + { + var request = http.request('http://0.0.0.0'); + request.once('error', function() { }); + request.setNoDelay(true); + request.abort(); + } } -//////////////////////////////////////////////////// -/// Https tests : http://nodejs.org/api/https.html -//////////////////////////////////////////////////// +////////////////////////////////////////////////////// +/// Https tests : http://nodejs.org/api/https.html /// +////////////////////////////////////////////////////// + namespace https_tests { var agent: https.Agent = new https.Agent({ keepAlive: true, @@ -656,7 +665,7 @@ namespace dgram_tests { //////////////////////////////////////////////////// namespace querystring_tests { - type SampleObject = {a: string; b: number;} + type SampleObject = { a: string; b: number; } { let obj: SampleObject; @@ -709,7 +718,7 @@ namespace path_tests { try { path.join('foo', {}, 'bar'); } - catch(error) { + catch (error) { } @@ -823,11 +832,11 @@ namespace path_tests { // } path.format({ - root : "/", - dir : "/home/user/dir", - base : "file.txt", - ext : ".txt", - name : "file" + root: "/", + dir: "/home/user/dir", + base: "file.txt", + ext: ".txt", + name: "file" }); // returns // '/home/user/dir/file.txt' @@ -893,7 +902,7 @@ namespace readline_tests { } { - let data: string|Buffer; + let data: string | Buffer; let key: readline.Key; rl.write(data); @@ -910,8 +919,8 @@ namespace readline_tests { { let stream: NodeJS.WritableStream; - let dx: number|string; - let dy: number|string; + let dx: number | string; + let dy: number | string; readline.moveCursor(stream, dx, dy); } @@ -952,7 +961,7 @@ namespace string_decoder_tests { namespace child_process_tests { { childProcess.exec("echo test"); - childProcess.spawnSync("echo test"); + childProcess.spawnSync("echo test"); } } @@ -960,7 +969,7 @@ namespace child_process_tests { /// cluster tests: https://nodejs.org/api/cluster.html /// ////////////////////////////////////////////////////////////////////// -namespace cluster_tests { +namespace cluster_tests  { { cluster.fork(); Object.keys(cluster.workers).forEach(key => { @@ -1012,7 +1021,7 @@ namespace os_tests { } { - let result: {[index: string]: os.NetworkInterfaceInfo[]}; + let result: { [index: string]: os.NetworkInterfaceInfo[] }; result = os.networkInterfaces(); } @@ -1073,19 +1082,19 @@ namespace vm_tests { namespace timers_tests { { - let immediateId = timers.setImmediate(function(){ console.log("immediate"); }); + let immediateId = timers.setImmediate(function() { console.log("immediate"); }); timers.clearImmediate(immediateId); } { let counter = 0; - let timeout = timers.setInterval(function(){ console.log("interval"); }, 20); + let timeout = timers.setInterval(function() { console.log("interval"); }, 20); timeout.unref(); timeout.ref(); timers.clearInterval(timeout); } { let counter = 0; - let timeout = timers.setTimeout(function(){ console.log("timeout"); }, 20); + let timeout = timers.setTimeout(function() { console.log("timeout"); }, 20); timeout.unref(); timeout.ref(); timers.clearTimeout(timeout); @@ -1111,14 +1120,13 @@ namespace errors_tests { /////////////////////////////////////////////////////////// import * as p from "process"; -namespace process_tests{ +namespace process_tests { { var eventEmitter: events.EventEmitter; eventEmitter = process; // Test that process implements EventEmitter... - + var _p: NodeJS.Process = process; _p = p; - assert(p === process); } } @@ -1127,9 +1135,21 @@ namespace process_tests{ /////////////////////////////////////////////////////////// import * as c from "console"; -namespace console_tests{ +namespace console_tests { { - assert(c === console); + var _c: Console = console; + _c = c; + } +} + +/////////////////////////////////////////////////// +/// Net Tests : https://nodejs.org/api/net.html /// +/////////////////////////////////////////////////// + +namespace net_tests { + { + // Make sure .listen() and .close() retuern a Server instance + net.createServer().listen(0).close().address(); } } diff --git a/node/node.d.ts b/node/node.d.ts index 820521e43c..888da5cec4 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -281,8 +281,8 @@ declare namespace NodeJS { } export interface ReadWriteStream extends ReadableStream, WritableStream { - pause(): ReadWriteStream; - resume(): ReadWriteStream; + pause(): ReadWriteStream; + resume(): ReadWriteStream; } export interface Events extends EventEmitter { } @@ -456,7 +456,7 @@ declare namespace NodeJS { } } -interface IterableIterator {} +interface IterableIterator { } /** * @deprecated @@ -464,7 +464,7 @@ interface IterableIterator {} interface NodeBuffer extends Uint8Array { write(string: string, offset?: number, length?: number, encoding?: string): number; toString(encoding?: string, start?: number, end?: number): string; - toJSON(): any; + toJSON(): {type: 'Buffer', data: any[]}; equals(otherBuffer: Buffer): boolean; compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; @@ -588,10 +588,11 @@ declare module "http" { agent?: Agent | boolean; } - export interface Server extends events.EventEmitter, net.Server { + export interface Server extends net.Server { setTimeout(msecs: number, callback: Function): void; maxHeadersCount: number; timeout: number; + listening: boolean; } /** * @deprecated Use IncomingMessage @@ -599,7 +600,7 @@ declare module "http" { export interface ServerRequest extends IncomingMessage { connection: net.Socket; } - export interface ServerResponse extends events.EventEmitter, stream.Writable { + export interface ServerResponse extends stream.Writable { // Extended base methods write(buffer: Buffer): boolean; write(buffer: Buffer, cb?: Function): boolean; @@ -629,7 +630,7 @@ declare module "http" { end(str: string, encoding?: string, cb?: Function): void; end(data?: any, encoding?: string): void; } - export interface ClientRequest extends events.EventEmitter, stream.Writable { + export interface ClientRequest extends stream.Writable { // Extended base methods write(buffer: Buffer): boolean; write(buffer: Buffer, cb?: Function): boolean; @@ -655,11 +656,11 @@ declare module "http" { end(str: string, encoding?: string, cb?: Function): void; end(data?: any, encoding?: string): void; } - export interface IncomingMessage extends events.EventEmitter, stream.Readable { + export interface IncomingMessage extends stream.Readable { httpVersion: string; httpVersionMajor: string; httpVersionMinor: string; - connection: any; + connection: net.Socket; headers: any; rawHeaders: string[]; trailers: any; @@ -741,17 +742,30 @@ declare module "http" { declare module "cluster" { import * as child from "child_process"; import * as events from "events"; + import * as net from "net"; + // interfaces export interface ClusterSettings { + execArgv?: string[]; // default: process.execArgv exec?: string; args?: string[]; silent?: boolean; + stdio?: any[]; + uid?: number; + gid?: number; + } + + export interface ClusterSetupMasterSettings { + exec?: string; // default: process.argv[1] + args?: string[]; // default: process.argv.slice(2) + silent?: boolean; // default: false + stdio?: any[]; } export interface Address { address: string; port: number; - addressType: string; + addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" } export class Worker extends events.EventEmitter { @@ -764,35 +778,205 @@ declare module "cluster" { disconnect(): void; isConnected(): boolean; isDead(): boolean; + exitedAfterDisconnect: boolean; + + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: Function): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (code: number, signal: string) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + + on(event: string, listener: Function): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (code: number, signal: string) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (code: number, signal: string) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (code: number, signal: string) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; } - export var settings: ClusterSettings; + export interface Cluster extends events.EventEmitter { + Worker: Worker; + disconnect(callback?: Function): void; + fork(env?: any): Worker; + isMaster: boolean; + isWorker: boolean; + // TODO: cluster.schedulingPolicy + settings: ClusterSettings; + setupMaster(settings?: ClusterSetupMasterSettings): void; + worker: Worker; + workers: { + [index: string]: Worker + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: Function): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: any) => void): this; + + on(event: string, listener: Function): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: any) => void): this; + + once(event: string, listener: Function): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: any) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: any) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: any) => void): this; + + } + + export function disconnect(callback ?: Function): void; + export function fork(env?: any): Worker; export var isMaster: boolean; export var isWorker: boolean; - export function setupMaster(settings?: ClusterSettings): void; - export function fork(env?: any): Worker; - export function disconnect(callback?: Function): void; + // TODO: cluster.schedulingPolicy + export var settings: ClusterSettings; + export function setupMaster(settings?: ClusterSetupMasterSettings): void; export var worker: Worker; export var workers: { [index: string]: Worker }; - // Event emitter - export function addListener(event: string, listener: Function): void; - export function on(event: "disconnect", listener: (worker: Worker) => void): void; - export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): void; - export function on(event: "fork", listener: (worker: Worker) => void): void; - export function on(event: "listening", listener: (worker: Worker, address: any) => void): void; - export function on(event: "message", listener: (worker: Worker, message: any) => void): void; - export function on(event: "online", listener: (worker: Worker) => void): void; - export function on(event: "setup", listener: (settings: any) => void): void; - export function on(event: string, listener: Function): any; - export function once(event: string, listener: Function): void; - export function removeListener(event: string, listener: Function): void; - export function removeAllListeners(event?: string): void; - export function setMaxListeners(n: number): void; + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + export function addListener(event: string, listener: Function): Cluster; + export function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function addListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function on(event: string, listener: Function): Cluster; + export function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function on(event: "fork", listener: (worker: Worker) => void): Cluster; + export function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function on(event: "online", listener: (worker: Worker) => void): Cluster; + export function on(event: "setup", listener: (settings: any) => void): Cluster; + + export function once(event: string, listener: Function): Cluster; + export function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function once(event: "fork", listener: (worker: Worker) => void): Cluster; + export function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function once(event: "online", listener: (worker: Worker) => void): Cluster; + export function once(event: "setup", listener: (settings: any) => void): Cluster; + + export function removeListener(event: string, listener: Function): Cluster; + export function removeAllListeners(event?: string): Cluster; + export function setMaxListeners(n: number): Cluster; + export function getMaxListeners(): number; export function listeners(event: string): Function[]; export function emit(event: string, ...args: any[]): boolean; + export function listenerCount(type: string): number; + + export function prependListener(event: string, listener: Function): Cluster; + export function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function prependOnceListener(event: string, listener: Function): Cluster; + export function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function eventNames(): string[]; } declare module "zlib" { @@ -1019,8 +1203,6 @@ declare module "os" { export function arch(): string; export function platform(): string; export function tmpdir(): string; - export function tmpDir(): string; - export function getNetworkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; export var EOL: string; export function endianness(): "BE" | "LE"; } @@ -1042,7 +1224,7 @@ declare module "https" { requestCert?: boolean; rejectUnauthorized?: boolean; NPNProtocols?: any; - SNICallback?: (servername: string, cb:(err:Error,ctx:tls.SecureContext)=>any) => any; + SNICallback?: (servername: string, cb: (err: Error, ctx: tls.SecureContext) => any) => any; } export interface RequestOptions extends http.RequestOptions { @@ -1398,18 +1580,24 @@ declare module "url" { } declare module "dns" { + export interface MxRecord { + exchange: string, + priority: number + } + export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string; export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string; export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolve6(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveMx(domain: string, callback: (err: Error, addresses: MxRecord[]) =>void ): string[]; export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function reverse(ip: string, callback: (err: Error, domains: string[]) => void): string[]; + export function setServers(servers: string[]): void; //Error codes export var NODATA: string; @@ -1600,16 +1788,92 @@ declare module "fs" { interface FSWatcher extends events.EventEmitter { close(): void; + + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: Function): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "error", listener: (code: number, signal: string) => void): this; + + on(event: string, listener: Function): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "error", listener: (code: number, signal: string) => void): this; + + once(event: string, listener: Function): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "error", listener: (code: number, signal: string) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "error", listener: (code: number, signal: string) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this; } export interface ReadStream extends stream.Readable { close(): void; destroy(): void; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: Function): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: Function): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; } + export interface WriteStream extends stream.Writable { close(): void; bytesWritten: number; path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: Function): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: Function): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; } /** @@ -1855,7 +2119,7 @@ declare module "fs" { } export const constants: Constants; - + /** Tests a user's permissions for the file specified by path. */ export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; @@ -2198,7 +2462,7 @@ declare module "tls" { requestCert?: boolean; rejectUnauthorized?: boolean; NPNProtocols?: string[] | Buffer; - SNICallback?: (servername: string, cb:(err:Error,ctx:SecureContext)=>any) => any; + SNICallback?: (servername: string, cb: (err: Error, ctx: SecureContext) => any) => any; ecdhCurve?: string; dhparam?: string | Buffer; handshakeTimeout?: number; @@ -2214,7 +2478,7 @@ declare module "tls" { port?: number; socket?: net.Socket; pfx?: string | Buffer - key?: string |string[] | Buffer | Buffer[]; + key?: string | string[] | Buffer | Buffer[]; passphrase?: string; cert?: string | string[] | Buffer | Buffer[]; ca?: string | Buffer | (string | Buffer)[]; @@ -2436,6 +2700,7 @@ declare module "crypto" { setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void; } export function createECDH(curve_name: string): ECDH; + export var DEFAULT_ENCODING: string; } declare module "stream" { @@ -2446,7 +2711,7 @@ declare module "stream" { } namespace internal { - export class Stream extends internal {} + export class Stream extends internal { } export interface ReadableOptions { highWaterMark?: number; @@ -2468,14 +2733,73 @@ declare module "stream" { unshift(chunk: any): void; wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; push(chunk: any, encoding?: string): boolean; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. readable + * 5. error + **/ + addListener(event: string, listener: Function): this; + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + + removeListener(event: string, listener: Function): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: Buffer | string) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; } export interface WritableOptions { highWaterMark?: number; decodeStrings?: boolean; objectMode?: boolean; - write?: (chunk: string|Buffer, encoding: string, callback: Function) => any; - writev?: (chunks: {chunk: string|Buffer, encoding: string}[], callback: Function) => any; + write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; + writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; } export class Writable extends events.EventEmitter implements NodeJS.WritableStream { @@ -2487,6 +2811,72 @@ declare module "stream" { end(): void; end(chunk: any, cb?: Function): void; end(chunk: any, encoding?: string, cb?: Function): void; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + **/ + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "drain", chunk: Buffer | string): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + + removeListener(event: string, listener: Function): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; } export interface DuplexOptions extends ReadableOptions, WritableOptions { @@ -2512,7 +2902,7 @@ declare module "stream" { } export interface TransformOptions extends ReadableOptions, WritableOptions { - transform?: (chunk: string|Buffer, encoding: string, callback: Function) => any; + transform?: (chunk: string | Buffer, encoding: string, callback: Function) => any; flush?: (callback: Function) => any; } @@ -2598,7 +2988,7 @@ declare module "assert" { }); } - export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; + export function fail(actual: any, expected: any, message: string, operator: string): void; export function ok(value: any, message?: string): void; export function equal(actual: any, expected: any, message?: string): void; export function notEqual(actual: any, expected: any, message?: string): void; @@ -2950,7 +3340,7 @@ declare module "v8" { space_available_size: number; physical_space_size: number; } - export function getHeapStatistics() : {total_heap_size: number, total_heap_size_executable: number, total_physical_size: number, total_avaialble_size: number, used_heap_size: number, heap_size_limit: number}; + export function getHeapStatistics(): { total_heap_size: number, total_heap_size_executable: number, total_physical_size: number, total_avaialble_size: number, used_heap_size: number, heap_size_limit: number }; export function getHeapSpaceStatistics(): HeapSpaceInfo[]; export function setFlagsFromString(flags: string): void; } diff --git a/nvd3/nvd3.d.ts b/nvd3/nvd3.d.ts index 769d900399..75e6693bdc 100644 --- a/nvd3/nvd3.d.ts +++ b/nvd3/nvd3.d.ts @@ -159,6 +159,8 @@ declare namespace nv { interpolate(value: string): this; rightAlignYAxis(): boolean; rightAlignYAxis(value: boolean): this; + syncBrushing(): boolean; + syncBrushing(value: boolean): this; } interface Nvd3Axis extends d3.svg.Axis { diff --git a/passport-local-mongoose/passport-local-mongoose.d.ts b/passport-local-mongoose/passport-local-mongoose.d.ts index ab2539a709..a3b5414c84 100644 --- a/passport-local-mongoose/passport-local-mongoose.d.ts +++ b/passport-local-mongoose/passport-local-mongoose.d.ts @@ -74,6 +74,9 @@ declare module 'mongoose' { plugin: (schema: PassportLocalSchema, options?: PassportLocalOptions) => void, options?: PassportLocalOptions ): this; + + // overload for the default mongoose plugin function + plugin(plugin: (schema: Schema, options?: Object) => void, opts?: Object): this; } export function model( diff --git a/point-in-polygon/point-in-polygon-tests.ts b/point-in-polygon/point-in-polygon-tests.ts new file mode 100644 index 0000000000..39851bd00e --- /dev/null +++ b/point-in-polygon/point-in-polygon-tests.ts @@ -0,0 +1,6 @@ +/// + +import inside from 'point-in-polygon'; + +const polygon = [ [ 1, 1 ], [ 1, 2 ], [ 2, 2 ], [ 2, 1 ] ]; +const inPolygon: boolean = inside([ 1.5, 1.5 ], polygon); diff --git a/point-in-polygon/point-in-polygon.d.ts b/point-in-polygon/point-in-polygon.d.ts new file mode 100644 index 0000000000..ceb85ecdec --- /dev/null +++ b/point-in-polygon/point-in-polygon.d.ts @@ -0,0 +1,8 @@ +// Type definitions for point-in-polygon +// Project: https://github.com/substack/point-in-polygon +// Definitions by: kogai +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'point-in-polygon' { + export default function inside(point: number[], polygon: number[][]): boolean; +} diff --git a/polylabel/polylabel-tests.ts b/polylabel/polylabel-tests.ts index 9e23d20d38..e428dbfdb3 100644 --- a/polylabel/polylabel-tests.ts +++ b/polylabel/polylabel-tests.ts @@ -1,10 +1,8 @@ /// -/// -import polylabel = require('polylabel'); +import * as polylabel from 'polylabel'; const polygon = [[[3116,3071],[3118,3068],[3108,3102],[3751,927]]] -let p: number[] -p = polylabel(polygon) -p = polylabel(polygon, 1.0) -p = polylabel(polygon, 1.0, true) -p = polylabel(polygon, 1.0, false) +polylabel(polygon) +polylabel(polygon, 1.0) +polylabel(polygon, 1.0, true) +polylabel(polygon, 1.0, false) diff --git a/polylabel/polylabel.d.ts b/polylabel/polylabel.d.ts index 21f50d1b41..1fe6aec3df 100644 --- a/polylabel/polylabel.d.ts +++ b/polylabel/polylabel.d.ts @@ -15,7 +15,7 @@ * - guarantees finding global optimum within the given precision * - is many times faster (10-40x) */ -declare module 'polylabel' { +declare module "polylabel" { /** * Polylabel returns the pole of inaccessibility coordinate in [x, y] format. * @@ -28,6 +28,7 @@ declare module 'polylabel' { * @example * var p = polylabel(polygon, 1.0); */ - function polylabel (polygon: number[][][], precision?: number, debug?: boolean): number[]; + function polylabel(polygon: number[][][], precision?: number, debug?: boolean): number[]; + namespace polylabel {} export = polylabel; } diff --git a/proj4/proj4-tests.ts b/proj4/proj4-tests.ts new file mode 100644 index 0000000000..c2d5a286b3 --- /dev/null +++ b/proj4/proj4-tests.ts @@ -0,0 +1,50 @@ +/// +import * as proj4 from 'proj4' + +/////////////////////////////////////////// +// Tests data initialisation +/////////////////////////////////////////// +const name = 'WGS84' +const epsg = { + 4269: '+title=NAD83 (long/lat) +proj=longlat +a=6378137.0 +b=6356752.31414036 +ellps=GRS80 +datum=NAD83 +units=degrees', + 4326: '+title=WGS 84 (long/lat) +proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees', +} +const point1 = [-71, 41] +const point2 = {x: 2, y: 5} +const mgrs = "24XWT783908" + +/////////////////////////////////////////// +// Tests Measurement +/////////////////////////////////////////// +proj4(epsg['4269'], epsg['4326'], point1) +proj4(epsg['4269'], point1) +proj4(epsg['4269'], epsg['4326']).forward(point2) +proj4(epsg['4269'], epsg['4326']).inverse(point2) + +/////////////////////////////////// +// Named Projections +/////////////////////////////////// +proj4.defs('WGS84', epsg['4326']) +proj4.defs([ + ['EPSG:4326', epsg['4326']], + ['EPSG:4269', epsg['4269']] +]) +proj4.defs('urn:x-ogc:def:crs:EPSG:4326', proj4.defs('EPSG:4326')) + +/////////////////////////////////// +// Utils +/////////////////////////////////// +// WGS84 +proj4.WGS84 + +// Proj +proj4.Proj('WGS84') + +// toPoint +proj4.toPoint([1, 2]) +proj4.toPoint([1, 2, 3]) +proj4.toPoint([1, 2, 3, 4]) + +// Point +// WARNING: Deprecated in v3 +proj4.Point([1, 2, 3, 4]) \ No newline at end of file diff --git a/proj4/proj4.d.ts b/proj4/proj4.d.ts new file mode 100644 index 0000000000..70de08b5a6 --- /dev/null +++ b/proj4/proj4.d.ts @@ -0,0 +1,116 @@ +// Type definitions for proj4 2.3.15 +// Project: https://github.com/proj4js/proj4js +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "proj4" { + const TemplateCoordinates: Array | InterfaceCoordinates; + + interface InterfaceCoordinates { + x: number, + y: number, + z?: number, + m?: number + } + + interface InterfaceDatum { + datum_type: number + a: number + b: number + es: number + ep2: number + } + + interface Proj4Static { + forward(coordinates: typeof TemplateCoordinates): Array + inverse(coordinates: typeof TemplateCoordinates): Array + } + + interface InterfaceProjection { + title: string + projName: string + ellps: string + datumCode: string + units: string + a: number + rf: number + ellipseName: string + b: number + a2: number + b2: number + es: number + e: number + ep2: number + k0: number + axis: string + datum: InterfaceDatum + init: typeof proj4.Proj, + forward(coordinates: typeof TemplateCoordinates): Array + inverse(coordinates: typeof TemplateCoordinates): Array + names: Array + to_meter(value: number): any + from_greenwich(value: number): any + } + + namespace proj4 { + /** + * @name defaultDatum + */ + export const defaultDatum: string; + + /** + * @name Proj + */ + export function Proj(srsCode:any, callback?: any): InterfaceProjection; + + /** + * @name WGS84 + */ + export const WGS84: any; + + /** + * Depecrated v3 + * @name Point + */ + export function Point(x: number, y: number, z?: number): InterfaceCoordinates; + export function Point(coordinates: Array): InterfaceCoordinates; + export function Point(coordinates: InterfaceCoordinates): InterfaceCoordinates; + export function Point(coordinates: string): InterfaceCoordinates; + + /** + * @name toPoint + */ + export function toPoint(array: Array): InterfaceCoordinates; + + /** + * @name defs + */ + export function defs(name: string): any; + export function defs(name: string, projection: string): any; + export function defs(name: Array>): any; + + /** + * @name transform + */ + export function transform(source: InterfaceProjection, dest: InterfaceProjection, point: typeof TemplateCoordinates): any; + + /** + * @name mgrs + */ + export function mgrs(coordinates: Array, accuracy: number): string; + + /** + * @name version + */ + export const version: string; + } + + /** + * @name proj4 + */ + function proj4(fromProjection: string): Proj4Static; + function proj4(fromProjection: string, toProjection: string): Proj4Static; + function proj4(fromProjection: string, coordinates: typeof TemplateCoordinates): Array; + function proj4(fromProjection: string, toProjection: string, coordinates: typeof TemplateCoordinates): Array; + export = proj4 +} diff --git a/protractor-helpers/protractor-helpers.d.ts b/protractor-helpers/protractor-helpers.d.ts index 20aad94c54..3966acd36e 100644 --- a/protractor-helpers/protractor-helpers.d.ts +++ b/protractor-helpers/protractor-helpers.d.ts @@ -108,4 +108,3 @@ declare module "protractor-helpers" { function getFilteredConsoleErrors() : webdriver.promise.IThenable; // TODO - discuss handling in IE } - diff --git a/pug/pug-tests.ts b/pug/pug-tests.ts new file mode 100644 index 0000000000..5ba7d9ad06 --- /dev/null +++ b/pug/pug-tests.ts @@ -0,0 +1,103 @@ +/// +import * as pug from 'pug'; + + +//////////////////////////////////////////////////////////// +/// Options https://pugjs.org/api/reference.html#options /// +//////////////////////////////////////////////////////////// +namespace options_tests { + let opts: pug.Options; + let str = 'string' + let bool = false; + let strArray = ['string']; + + opts.filename = str; + + opts.basedir = str; + + opts.doctype = str; + + opts.pretty = str; + opts.pretty = bool; + + opts.filters = {}; + + opts.self = bool; + + opts.debug = bool; + opts.compileDebug = bool; + + opts.globals = strArray; + + opts.cache = bool; + + opts.inlineRuntimeFunctions = bool; + + opts.name = str; +} + +//////////////////////////////////////////////////////////// +/// Methods https://pugjs.org/api/reference.html#methods /// +//////////////////////////////////////////////////////////// +namespace methods_tests { + let source = `p #{ name } 's Pug source code!`; + let path = "foo.pug"; + let compileTemplate: pug.compileTemplate; + let template: string; + let clientFunctionString: pug.ClientFunctionString; + let str: string; + + { + /// pug.compile(source, ?options) https://pugjs.org/api/reference.html#pugcompilesource-options + compileTemplate = pug.compile(source); + template = compileTemplate(); + } + + { + /// pug.compileFile(path, ?options) https://pugjs.org/api/reference.html#pugcompilefilepath-options + compileTemplate = pug.compileFile(path); + template = compileTemplate(); + } + + { + /// pug.compileClient(source, ?options) https://pugjs.org/api/reference.html#pugcompileclientsource-options + clientFunctionString = pug.compileClient(path); + str = pug.compileClient(path); + } + + { + /// pug.compileClientWithDependenciesTracked(source, ?options) https://pugjs.org/api/reference.html#pugcompileclientwithdependenciestrackedsource-options + let obj = pug.compileClientWithDependenciesTracked(source); + clientFunctionString = obj.body; + str = obj.body; + let strArray: string[] = obj.dependencies; + } + + { + /// pug.compileFileClient(path, ?options) https://pugjs.org/api/reference.html#pugcompilefileclientpath-options + clientFunctionString = pug.compileFileClient(path); + str = pug.compileFileClient(path); + } + + { + /// pug.render(source, ?options, ?callback) https://pugjs.org/api/reference.html#pugrendersource-options-callback + str = pug.render(source); + + // test type for callback paraments + pug.render(source, {}, (err, html) => { + let e: Error = err; + str = html; + }); + } + + { + /// pug.renderFile(path, ?options, ?callback) https://pugjs.org/api/reference.html#pugrenderfilepath-options-callback + str = pug.renderFile(path); + + // test type for callback paraments + pug.renderFile(path, {}, (err, html) => { + let e: Error = err; + str = html; + }); + } +} diff --git a/pug/pug.d.ts b/pug/pug.d.ts new file mode 100644 index 0000000000..8902aa7cf4 --- /dev/null +++ b/pug/pug.d.ts @@ -0,0 +1,50 @@ +// Type definitions for pug 2.0.0-beta6 +// Project: https://github.com/pugjs/pug +// Definitions by: TonyYang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Table of Contents + * + * - Options https://pugjs.org/api/reference.html#options + * - Methods https://pugjs.org/api/reference.html#methods + * + * The order of contents is according to pugjs API document. + */ +declare module 'pug' { + //////////////////////////////////////////////////////////// + /// Options https://pugjs.org/api/reference.html#options /// + //////////////////////////////////////////////////////////// + export interface Options { + filename?: string; + basedir?: string; + doctype?: string; + pretty?: boolean | string; + filters?: any; + self?: boolean; + debug?: boolean; + compileDebug?: boolean; + globals?: string[]; + cache?: boolean; + inlineRuntimeFunctions?: boolean; + name?: string; + } + + //////////////////////////////////////////////////////////// + /// Methods https://pugjs.org/api/reference.html#methods /// + //////////////////////////////////////////////////////////// + export function compile(source: string, options?: Options): (locals?: any) => string; + export function compileFile(path: string, options?: Options): (locals?: any) => string; + export function compileClient(source: string, options?: Options): ClientFunctionString; + export function compileClientWithDependenciesTracked(source: string, options?: Options): { + body: ClientFunctionString; + dependencies: string[]; + }; + export function compileFileClient(path: string, options?: Options): ClientFunctionString; + export function render(source: string, options?: Options, callback?: (err: Error, html: string) => void): string; + export function renderFile(path: string, options?: Options, callback?: (err: Error, html: string) => void): string; + + // else + export type ClientFunctionString = string; // ex: 'function (locals) {...}' + export type compileTemplate = (locals?: any) => string; +} diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index fb19dca42d..dd4e59af1c 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -39,10 +39,10 @@ declare namespace ReactRouter { type RouteComponent = Component // use the following interface in an app code to get access to route param values, history, location... - // interface MyComponentProps extends ReactRouter.RouteComponentProps<{}, { id: number }> {} + // interface MyComponentProps extends ReactRouter.RouteComponentProps<{}, { id: string }> {} // somewhere in MyComponent // ... - // let id = this.props.routeParams.id + // let id = parseInt(this.props.routeParams.id, 10); // ... // this.props.history. ... // ... @@ -247,7 +247,7 @@ declare namespace ReactRouter { isActive: (pathOrLoc: H.LocationDescriptor, indexOnly?: boolean) => boolean } - function withRouter>(component: C): C + function withRouter | React.StatelessComponent | React.PureComponent>(component: C): C /* utils */ diff --git a/react-virtualized/react-virtualized-tests.tsx b/react-virtualized/react-virtualized-tests.tsx new file mode 100644 index 0000000000..d3ee9c3590 --- /dev/null +++ b/react-virtualized/react-virtualized-tests.tsx @@ -0,0 +1,309 @@ +/// +/// +/// + +import * as React from "react"; +import * as ReactDOM from "react-dom"; + +import { + Collection, + FlexTable, + FlexColumn, + SortDirection, + Grid, + VirtualScroll, + ArrowKeyStepper, + AutoSizer, + CellMeasurer, + ColumnSizer, + InfiniteLoader, + ScrollSync, + WindowScroller, +} from "react-virtualized"; + +/* + * Collection + */ + +function CollectionTest() { + const list = [ + { name: "Brian Vaughn", x: 13, y: 34, width: 123, size: 234, height: 123 } + ]; + + // Render your grid + ReactDOM.render( + list[index].name} + cellSizeAndPositionGetter={({ index }) => { + const datum = list[index]; + return { + height: datum.height, + width: datum.width, + x: datum.x, + y: datum.y + }; + } } + height={300} + width={300} + />, + document.getElementById("example") + ); +} + + +function FlexTableTest() { + const list = [ + { name: 'Brian Vaughn', description: 'Software engineer' } + // And so on... + ]; + + // Render your table + ReactDOM.render( + list[index] + } + > + + + , + document.getElementById("example") + ); +} + +function GridTest() { + // Grid data as an array of arrays + const list = [ + ['Brian Vaughn', 'Software Engineer', 'San Jose', 'CA', 95125 /* ... */] + // And so on... + ]; + + // Render your grid + ReactDOM.render( + list[rowIndex][columnIndex]} + />, + document.getElementById('example') + ); +} + +function VirtualScrollTest() { + // List data as an array of strings + const list = [ + 'Brian Vaughn' + // And so on... + ]; + + // Render your list + ReactDOM.render( + list[index]} + />, + document.getElementById('example') + ); +} + +function ArrowKeyStepperTest() { + const columnCount = 12; + const rowCount = 3; + + ReactDOM.render( + + {({ onSectionRendered, scrollToColumn, scrollToRow }) => ( + + ) } + , + document.getElementById('example') + ); +} + +function AutoSizerTest() { + // List data as an array of strings + const list = [ + 'Brian Vaughn' + // And so on... + ]; + + // Render your list + ReactDOM.render( + + {({ height, width }) => ( + list[index] // Could also be a DOM element + } + /> + ) } + , + document.getElementById('example') + ); +} + +function CellMeasurerTest() { + const columnCount = 12; + const rowCount = 3; + const cellRenderer = ({ columnIndex, rowIndex }) => `${rowIndex}, ${columnIndex}`; + const fixedRowHeight = 42; + const height = 12; + const width = 12; + + ReactDOM.render( + + {({ getColumnWidth }) => ( + + ) } + , + document.getElementById('example') + ); +} + +function ColumnSizerTest() { + ReactDOM.render( + + {({ adjustedWidth, getColumnWidth, registerChild }) => ( + "test"} + rowHeight={50} + rowCount={12} + width={adjustedWidth} + /> + ) } + , + document.getElementById('example') + ); +} + +function InfiniteLoaderTest() { + const list: string[] = []; + + function isRowLoaded({ index }) { + return !!list[index]; + } + + function loadMoreRows({ startIndex, stopIndex }) { + return list.push('test'); + } + + // Render your list + ReactDOM.render( + + {({ onRowsRendered, registerChild }) => ( + list[index] // Could also be a DOM element + } + /> + ) } + , + document.getElementById('example') + ); +} + +function ScrollSyncTest() { + return ( + + {({ clientHeight, clientWidth, onScroll, scrollHeight, scrollLeft, scrollTop, scrollWidth }) => ( +
+
+ "test"} + rowCount={42} + height={12} + width={12} + rowHeight={120} + scrollTop={scrollTop}/> + /> +
+
+ +
+
+ ) } +
+ ); +} + +function WindowScrollerTest() { + ReactDOM.render( + + {({ height, isScrolling, scrollTop }) => ( + 'test'} + scrollTop={scrollTop} + width={120}/> + ) } + , + document.getElementById('example') + ); +} diff --git a/react-virtualized/react-virtualized.d.ts b/react-virtualized/react-virtualized.d.ts new file mode 100644 index 0000000000..aad19c44a3 --- /dev/null +++ b/react-virtualized/react-virtualized.d.ts @@ -0,0 +1,123 @@ +// Type definitions for react-virtualized +// Project: https://github.com/bvaughn/react-virtualized +// Definitions by: Ian Ker-Seymer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "react-virtualized" { + import * as React from "react"; + + /* + * Components + */ + + interface VirtualScrollProps { + className?: string; + autoHeight?: boolean; + estimatedRowSize?: number; + height: number; + noRowsRenderer?: Function; + onRowsRendered?: (info: { overscanStartIndex: number, overscanStopIndex: number, startIndex: number, stopIndex: number }) => void; + onScroll?: (info: { clientHeight: number, scrollHeight: number, scrollTop: number }) => void; + overscanRowCount?: number; + rowHeight: number | ((info: { index: number }) => number); + rowRenderer: (info: { index: number, isScrolling: boolean }) => React.ReactNode; + rowClassName?: string | ((info: { index: number }) => string); + rowCount: number; + rowStyle?: React.CSSProperties | ((info: { index: number }) => React.CSSProperties); + scrollToAlignment?: string; + scrollToIndex?: number; + scrollTop?: number; + style?: React.CSSProperties; + tabIndex?: number; + width: number; + } + export class VirtualScroll extends React.Component { } + + type CollectionProps = any; + export class Collection extends React.Component { } + + type FlexTableProps = any; + export class FlexTable extends React.Component { } + + type FlexColumnProps = any; + export class FlexColumn extends React.Component { } + + type SortDirectionProps = any; + export class SortDirection extends React.Component { } + + type GridProps = any; + export class Grid extends React.Component { } + + + /* + * Higher-Order Components + */ + + interface AutoSizerProps { + disableHeight?: boolean; + disableWidth?: boolean; + onResize?: (info: { height: number, width: number }) => any; + } + export class AutoSizer extends React.Component { } + + interface ArrowKeyStepperProps { + children?: React.StatelessComponent<{ + onSectionRendered: Function, + scrollToColumn: number, + scrollToRow: number + }>; + className?: string; + columnCount: number; + rowCount: number; + } + export class ArrowKeyStepper extends React.Component { } + + interface CellMeasurerProps { + cellRenderer: (info: { columnIndex: number, rowIndex: number }) => React.ReactNode; + cellSizeCache?: { + clearAllColumnWidths(): void; + clearAllRowHeights(): void; + clearColumnWidth(index: number): void; + clearRowHeight(index: number): void; + getColumnWidth(index: number): number; + getRowHeight(index: number): number; + hasColumnWidth(index: number): boolean; + hasRowHeight(index: number): boolean; + setColumnWidth(index: number, width: number): void; + setRowHeight(index: number, height: number): void; + }; + children?: React.StatelessComponent<{ + getColumnWidth: () => number, + getRowHeight: () => number, + resetMeasurements: () => any, + resetMeasurementsForColumn: (index: number) => any, + resetMeasurementsForRow: (index: number) => any, + }>; + columnCount: number; + container?: React.ReactType; + height?: number; + rowCount: number; + width?: number; + } + export class CellMeasurer extends React.Component { } + + interface ColumnSizerProps { + children?: React.StatelessComponent<{ adjustedWidth: number, getColumnWidth: () => number, registerChild: any }>; + columnMaxWidth?: number; + columnMinWidth?: number; + columnCount?: number; + width: number; + } + export class ColumnSizer extends React.Component { } + + type InfiniteLoaderProps = any; + export class InfiniteLoader extends React.Component { } + + type ScrollSyncProps = any; + export class ScrollSync extends React.Component { } + + type WindowScrollerProps = any; + export class WindowScroller extends React.Component { } +} diff --git a/redux-promise/redux-promise-tests.ts b/redux-promise/redux-promise-tests.ts index 724f695261..92a672488b 100644 --- a/redux-promise/redux-promise-tests.ts +++ b/redux-promise/redux-promise-tests.ts @@ -4,7 +4,7 @@ import {createAction} from 'redux-actions'; import { createStore, applyMiddleware, PromiseAction } from 'redux'; -import promise from 'redux-promise'; +import promise = require('redux-promise'); declare var userReducer: any; diff --git a/redux-promise/redux-promise.d.ts b/redux-promise/redux-promise.d.ts index f3fbea7240..7656def908 100644 --- a/redux-promise/redux-promise.d.ts +++ b/redux-promise/redux-promise.d.ts @@ -19,5 +19,5 @@ declare namespace ReduxPromise { declare module "redux-promise" { var promise: ReduxPromise.Promise; - export default promise; -} \ No newline at end of file + export = promise; +} diff --git a/requirejs/require.d.ts b/requirejs/require.d.ts index 1c5b4088c1..ac116494f3 100644 --- a/requirejs/require.d.ts +++ b/requirejs/require.d.ts @@ -206,7 +206,7 @@ interface RequireConfig { * } * }); **/ - urlArgs?: string | { (id: string, url: string): string; }; + urlArgs?: string | ((id: string, url: string) => string); /** * Specify the value for the type="" attribute used for script diff --git a/restangular/restangular.d.ts b/restangular/restangular.d.ts index 8daa5c0b08..b0ae6b7ca5 100644 --- a/restangular/restangular.d.ts +++ b/restangular/restangular.d.ts @@ -84,8 +84,8 @@ declare namespace restangular { one(route: string, id?: number): IElement; one(route: string, id?: string): IElement; oneUrl(route: string, url: string): IElement; - all(route: string): IElement; - allUrl(route: string, url: string): IElement; + all(route: string): ICollection; + allUrl(route: string, url: string): ICollection; copy(fromElement: any): IElement; withConfig(configurer: (RestangularProvider: IProvider) => any): IService; restangularizeElement(parent: any, element: any, route: string, collection?: any, reqParams?: any): IElement; @@ -104,8 +104,6 @@ declare namespace restangular { put(queryParams?: any, headers?: any): IPromise; post(subElement: any, elementToPost: any, queryParams?: any, headers?: any): IPromise; post(subElement: any, elementToPost: T, queryParams?: any, headers?: any): IPromise; - post(elementToPost: any, queryParams?: any, headers?: any): IPromise; - post(elementToPost: T, queryParams?: any, headers?: any): IPromise; remove(queryParams?: any, headers?: any): IPromise; head(queryParams?: any, headers?: any): IPromise; trace(queryParams?: any, headers?: any): IPromise; diff --git a/restify/restify.d.ts b/restify/restify.d.ts index d8e1a37576..65b3f44d47 100644 --- a/restify/restify.d.ts +++ b/restify/restify.d.ts @@ -452,6 +452,7 @@ declare module "restify" { responseTimeFormatter ?: (durationInMilliseconds: number) => any; handleUpgrades ?: boolean; router ?: Router; + httpsServerOptions?: any; } interface ClientOptions { diff --git a/rpio/rpio-tests.ts b/rpio/rpio-tests.ts new file mode 100644 index 0000000000..fc0d79a71f --- /dev/null +++ b/rpio/rpio-tests.ts @@ -0,0 +1,105 @@ +/// + +rpio.init({gpiomem: false}); /* Use /dev/mem for i²c/PWM/SPI */ +rpio.init({mapping: 'gpio'}); /* Use the GPIOxx numbering */ + +/* Configure P11 as input with the internal pulldown resistor enabled */ +rpio.open(11, rpio.INPUT, rpio.PULL_DOWN); + +/* Configure P12 as output with the initiate state set high */ +rpio.open(12, rpio.OUTPUT, rpio.HIGH); + +/* Configure P13 as output, but leave it in its initial undefined state */ +rpio.open(13, rpio.OUTPUT); + +rpio.mode(12, rpio.INPUT); /* Switch P12 back to input mode */ + +console.log('Pin 12 = %d', rpio.read(12)); + +var buf = new Buffer(10000); + +/* Read the value of Pin 12 10,000 times in a row, storing the values in buf */ +rpio.readbuf(12, buf); + +rpio.write(13, rpio.HIGH); + +/* Write 1 0 1 0 1 0 1 0 to Pin 13 */ +var buf = new Buffer(8).fill(rpio.LOW); +buf[0] = buf[2] = buf[4] = buf[6] = rpio.HIGH; +rpio.writebuf(13, buf); + +var curpad = rpio.readpad(rpio.PAD_GROUP_0_27); + +var slew = ((curpad & rpio.PAD_SLEW_UNLIMITED) == rpio.PAD_SLEW_UNLIMITED); +var hysteresis = ((curpad & rpio.PAD_HYSTERESIS) == rpio.PAD_HYSTERESIS); +var drive = (curpad & 0x7); + +/* Disable input hysteresis but retain other current settings. */ +var control = rpio.readpad(rpio.PAD_GROUP_0_27); +control &= ~rpio.PAD_HYSTERESIS; +rpio.writepad(rpio.PAD_GROUP_0_27, control); + +rpio.pud(11, rpio.PULL_UP); +rpio.pud(12, rpio.PULL_DOWN); + +function nuke_button(pin: number) +{ + console.log('Nuke button on pin %d pressed', pin); + + /* No need to nuke more than once. */ + rpio.poll(pin, null); +} + +function regular_button(pin: number) +{ + /* Watch pin 11 forever. */ + console.log('Button event on pin %d, is now %d', pin, rpio.read(pin)); +} + +/* + * Pin 11 watches for both high and low transitions. Pin 12 only watches for + * high transitions (e.g. the nuke button is pushed). + */ +rpio.poll(11, regular_button); +rpio.poll(12, nuke_button, rpio.POLL_HIGH); + +rpio.close(11); + +rpio.i2cBegin(); + +rpio.i2cSetSlaveAddress(0x20); + +rpio.i2cSetBaudRate(100000); /* 100kHz */ +rpio.i2cSetClockDivider(2500); /* 250MHz / 2500 = 100kHz */ + +var txbuf = new Buffer([0x0b, 0x0e, 0x0e, 0x0f]); +var rxbuf = new Buffer(32); + +rpio.i2cWrite(txbuf); /* Sends 4 bytes */ +rpio.i2cRead(rxbuf, 16); /* Reads 16 bytes */ + +rpio.i2cEnd(); + +rpio.open(12, rpio.PWM); /* Use pin 12 */ + +rpio.pwmSetClockDivider(64); /* Set PWM refresh rate to 300kHz */ + +rpio.pwmSetRange(12, 1024); + +rpio.pwmSetData(12, 512); + +rpio.spiBegin(); /* Switch GPIO7-GPIO11 to SPI mode */ + +rpio.spiSetCSPolarity(0, rpio.HIGH); /* Set CE0 high to activate */ + +rpio.spiSetClockDivider(128); /* Set SPI speed to 1.95MHz */ + +rpio.spiTransfer(txbuf, rxbuf, txbuf.length); + +rpio.spiWrite(txbuf, txbuf.length); + +rpio.spiEnd(); + +rpio.sleep(1); /* Sleep for n seconds */ +rpio.msleep(1); /* Sleep for n milliseconds */ +rpio.usleep(1); /* Sleep for n microseconds */ diff --git a/rpio/rpio.d.ts b/rpio/rpio.d.ts new file mode 100644 index 0000000000..0bba37b918 --- /dev/null +++ b/rpio/rpio.d.ts @@ -0,0 +1,372 @@ +// Type definitions for node-rpio +// Project: https://github.com/jperkin/node-rpio +// Definitions by: Dominik Palo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare var rpio: Rpio; + +declare module 'rpio' { + export = rpio; +} + +interface Rpio { + /** + * Initialise the bcm2835 library. This will be called automatically by .open() using the default option values if not called explicitly. + * @param options + */ + init(options: RPIO.Options): void; + + /** + * Open a pin for input or output. Valid modes are: + * INPUT: pin is input (read-only). + * OUTPUT: pin is output (read-write). + * PWM: configure pin for hardware PWM. + * + * For input pins, option can be used to configure the internal pullup or pulldown resistors using options as described in the .pud() documentation below. + * + * For output pins, option defines the initial isMotionDetected of the pin, rather than having to issue a separate .write() call. This can be critical for devices which must have a stable value, rather than relying on the initial floating value when a pin is enabled for output but hasn't yet been configured with a value. + * @param pin + * @param mode + * @param options + */ + open(pin: number, mode: number, options?: number): void; + + /** + * Switch a pin that has already been opened in one mode to a different mode. + * This is provided primarily for performance reasons, as it avoids some of the setup work done by .open(). + * @param pin + * @param mode + */ + mode(pin: number, mode: number): void; + + /** + * Read the current value of pin, returning either 1 (high) or 0 (low). + * @param pin + */ + read(pin: number): number; + + /** + * Read length bits from pin into buffer as fast as possible. If length isn't specified it defaults to buffer.length. + * @param pin + * @param buffer + * @param length + */ + readbuf(pin: number, buffer: Buffer, length?: number): void; + + /** + * Set the specified pin either high or low, using either the HIGH/LOW constants, or simply 1 or 0. + * @param pin + * @param value + */ + write(pin: number, value: number): void; + + /** + * Write length bits to pin from buffer as fast as possible. If length isn't specified it defaults to buffer.length. + + * @param pin + * @param buffer + * @param length + */ + writebuf(pin: number, buffer: Buffer, length?: number): void; + + /** + * Read the current isMotionDetected of the GPIO pad control for the specified GPIO group. On current models of Raspberry Pi there are three groups with corresponding defines: + * PAD_GROUP_0_27: GPIO0 - GPIO27. Use this for the main GPIO header. + * PAD_GROUP_28_45: GPIO28 - GPIO45. Use this to configure the P5 header. + * PAD_GROUP_46_53: GPIO46 - GPIO53. Internal, you probably won't need this. + * + * The value returned will be a bit mask of the following defines: + * PAD_SLEW_UNLIMITED: 0x10. Slew rate unlimited if set. + * PAD_HYSTERESIS: 0x08. Hysteresis is enabled if set. + * + * The bottom three bits determine the drive current: + * PAD_DRIVE_2mA: 0b000 + * PAD_DRIVE_4mA: 0b001 + * PAD_DRIVE_6mA: 0b010 + * PAD_DRIVE_8mA: 0b011 + * PAD_DRIVE_10mA: 0b100 + * PAD_DRIVE_12mA: 0b101 + * PAD_DRIVE_14mA: 0b110 + * PAD_DRIVE_16mA: 0b111 + * + * @note Note that the pad control registers are not available via /dev/gpiomem, so you will need to use .init({gpiomem: false}) and run as root. + * @param group + */ + readpad(group: number): number; + + /** + * Write control settings to the pad control for group. Uses the same defines as above for .readpad(). + * @param group + * @param control + */ + writepad(group: number, control: number): void; + + /** + * Configure the pin's internal pullup or pulldown resistors, using the following isMotionDetected constants: + * PULL_OFF: disable configured resistors. + * PULL_DOWN: enable the pulldown resistor. + * PULL_UP: enable the pullup resistor. + * + * @param pin + * @param state + */ + pud(pin: number, state: number): void; + + /** + * Watch pin for changes and execute the callback cb() on events. cb() takes a single argument, the pin which triggered the callback. + * + * The optional direction argument can be used to watch for specific events: + * POLL_LOW: poll for falling edge transitions to low. + * POLL_HIGH: poll for rising edge transitions to high. + * POLL_BOTH: poll for both transitions (the default). + * + * Due to hardware/kernel limitations we can only poll for changes, and the event detection only says that an event occurred, not which one. The poll interval is a 1ms setInterval() and transitions could come in between detecting the event and reading the value. Therefore this interface is only useful for events which transition slower than approximately 1kHz. + * + * To stop watching for pin changes, call .poll() again, setting the callback to null. + * @param pin + * @param cb + * @param direction + */ + poll(pin: number, cb: RPIO.CallbackFunction, direction?: number): void; + + /** + * Reset pin to INPUT and clear any pullup/pulldown resistors and poll events. + * @param pin + */ + close(pin: number): void; + + // I²C + + /** + * Assign pins 3 and 5 to i²c use. Until .i2cEnd() is called they won't be available for GPIO use. + * + * The pin assignments are: + * Pin 3: SDA (Serial Data) + * Pin 5: SCL (Serial Clock) + */ + i2cBegin(): void; + + /** + * Configure the slave address. This is between 0 - 0x7f, and it can be helpful to + * run the i2cdetect program to figure out where your devices are if you are unsure. + * @param address + */ + i2cSetSlaveAddress(address: number): void; + + /** + * Set the baud rate - directly set the speed in hertz. + * @param baudRate + */ + i2cSetBaudRate(baudRate: number): void; + + /** + * Read from the i²c slave. + * Function takes a buffer and optional length argument, defaulting to the length of the buffer if not specified. + * @param buffer + * @param length + */ + i2cRead(buffer: Buffer, length?: number): void; + + /** + * Write to the i²c slave. + * Function takes a buffer and optional length argument, defaulting to the length of the buffer if not specified. + * @param biffer + * @param length + */ + i2cWrite(biffer: Buffer, length?: number): void; + + /** + * Set the baud rate - based on a divisor of the base 250MHz rate. + * @param clockDivider + */ + i2cSetClockDivider(clockDivider: number): void; + + + + + /** + * Turn off the i²c interface and return the pins to GPIO. + */ + i2cEnd(): void; + + // PWM + + /** + * Set the PWM refresh rate. + * @param clockDivider: power-of-two divisor of the base 19.2MHz rate, with a maximum value of 4096 (4.6875kHz). + */ + pwmSetClockDivider(clockDivider: number): void; + + /** + * Set the PWM range for a pin. This determines the maximum pulse width. + * @param pin + * @param range + */ + pwmSetRange(pin: number, range: number): void; + + /** + * Set the PWM width for a pin. + * @param pin + * @param data + */ + pwmSetData(pin: number, data: number): void; + + // SPI + + /** + * Switch pins 119, 21, 23, 24 and 25 (GPIO7-GPIO11) to SPI mode + * + * Pin | Function + * -----|---------- + * 19 | MOSI + * 21 | MISO + * 23 | SCLK + * 24 | CE0 + * 25 | CE1 + */ + spiBegin(): void; + + /** + * Choose which of the chip select / chip enable pins to control. + * + * Value | Pin + * ------|--------------------- + * 0 | SPI_CE0 (24 / GPIO8) + * 1 | SPI_CE1 (25 / GPIO7) + * 2 | Both + * + * @param chip + */ + spiChipSelect(cePin: number): void; + + /** + * Commonly chip enable (CE) pins are active low, and this is the default. + * If your device's CE pin is active high, use spiSetCSPolarity() to change the polarity. + * @param cePin + * @param polarity + */ + spiSetCSPolarity(cePin: number, polarity: number): void; + + /** + * Set the SPI clock speed with. + * @param clockDivider: an even divisor of the base 250MHz rate ranging between 0 and 65536. + */ + spiSetClockDivider(clockDivider: number): void; + + /** + * Transfer data. Data is sent and received in 8-bit chunks via buffers which should be the same size. + * @param txBuffer + * @param rxBuffer + * @param txLength + */ + spiTransfer(txBuffer: Buffer, rxBuffer: Buffer, txLength: number): void; + + /** + * Send data and do not care about the data coming back. + * @param txBuffer + * @param txLength + */ + spiWrite(txBuffer: Buffer, txLength: number): void; + + /** + * Release the pins back to general purpose use. + */ + spiEnd(): void; + + // Misc + + /** + * Sleep for n seconds. + * @param n: number of seconds to sleep + */ + sleep(n: number): void; + + /** + * Sleep for n milliseconds. + * @param n: number of milliseconds to sleep + */ + msleep(n: number): void; + + /** + * Sleep for n microseconds. + * @param n: number of microseconds to sleep + */ + usleep(n: number): void; + + + // Constants: + + HIGH: number; + LOW: number; + + INPUT: number; + OUTPUT: number; + PWM: number; + + PULL_OFF: number; + PULL_DOWN: number; + PULL_UP: number; + + PAD_GROUP_0_27: number; + PAD_GROUP_28_45: number; + PAD_GROUP_46_53: number; + + PAD_SLEW_UNLIMITED: number; + PAD_HYSTERESIS: number; + + PAD_DRIVE_2mA: number; + PAD_DRIVE_4mA: number; + PAD_DRIVE_6mA: number; + PAD_DRIVE_8mA: number; + PAD_DRIVE_10mA: number; + PAD_DRIVE_12mA: number; + PAD_DRIVE_14mA: number; + PAD_DRIVE_16mA: number; + + POLL_LOW: number; + POLL_HIGH: number; + POLL_BOTH: number; + +} + +declare namespace RPIO { + + interface Options { + + /** + * There are two device nodes for GPIO access. The default is /dev/gpiomem which, when configured with gpio group access, allows users in that group to read/write directly to that device. This removes the need to run as root, but is limited to GPIO functions. + * For non-GPIO functions (i²c, PWM, SPI) the /dev/mem device is required for full access to the Broadcom peripheral address range and the program needs to be executed as the root user (e.g. via sudo). If you do not explicitly call .init() when using those functions, the library will do it for you with gpiomem: false. + * You may also need to use gpiomem: false if you are running on an older Linux kernel which does not support the gpiomem module. + * rpio will throw an exception if you try to use one of the non-GPIO functions after already opening with /dev/gpiomem, as well as checking to see if you have the necessary permissions. + * + * Valid options: + * true: use /dev/gpiomem for non-root but GPIO-only access + * false: use /dev/mem for full access but requires root + */ + gpiomem?: boolean; + + /** + * There are two naming schemes when referring to GPIO pins: + * By their physical header location: Pins 1 to 26 (A/B) or Pins 1 to 40 (A+/B+) + * Using the Broadcom hardware map: GPIO 0-25 (B rev1), GPIO 2-27 (A/B rev2, A+/B+) + * + * Confusingly however, the Broadcom GPIO map changes between revisions, so for example P3 maps to GPIO0 on Model B Revision 1 models, but maps to GPIO2 on all later models. + * This means the only sane default mapping is the physical layout, so that the same code will work on all models regardless of the underlying GPIO mapping. + * If you prefer to use the Broadcom GPIO scheme for whatever reason (e.g. to use the P5 header pins on the Raspberry Pi 1 revision 2.0 model which aren't currently mapped to the physical layout), you can set mapping to gpio to switch to the GPIOxx naming. + * + * Valid options: + * gpio: use the Broadcom GPIOxx naming + * physical: use the physical P01-P40 header layou + */ + mapping?: "gpio" | "physical"; + } + + interface CallbackFunction { + /** + * @param pin: The pin which triggered the callback. + */ + (pin: number): void; + } +} diff --git a/samchon-framework/samchon-framework.d.ts b/samchon-framework/samchon-framework.d.ts index a6d03758dd..70d9dda38f 100644 --- a/samchon-framework/samchon-framework.d.ts +++ b/samchon-framework/samchon-framework.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Samchon Framework v2.0.0-beta.1 +// Type definitions for Samchon Framework v2.0.0-beta.8 // Project: https://github.com/samchon/framework // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -82,19 +82,15 @@ declare namespace samchon.collection { /** * @hidden */ - protected insert_by_repeating_val(position: std.VectorIterator, n: number, val: T): std.VectorIterator; + protected _Insert_by_repeating_val(position: std.VectorIterator, n: number, val: T): std.VectorIterator; /** * @hidden */ - protected insert_by_range>(position: std.VectorIterator, begin: InputIterator, end: InputIterator): std.VectorIterator; - /** - * @inheritdoc - */ - pop_back(): void; + protected _Insert_by_range>(position: std.VectorIterator, begin: InputIterator, end: InputIterator): std.VectorIterator; /** * @hidden */ - protected erase_by_range(first: std.VectorIterator, last: std.VectorIterator): std.VectorIterator; + protected _Erase_by_range(first: std.VectorIterator, last: std.VectorIterator): std.VectorIterator; /** * @hidden */ @@ -110,7 +106,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -126,28 +122,28 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; addEventListener(type: "insert", listener: CollectionEventListener): void; addEventListener(type: "erase", listener: CollectionEventListener): void; addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; removeEventListener(type: "insert", listener: CollectionEventListener): void; removeEventListener(type: "erase", listener: CollectionEventListener): void; removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; @@ -176,13 +172,9 @@ declare namespace samchon.library { * @reference https://developer.mozilla.org/en-US/docs/Web/API/Event * @author Jeongho Nam */ - class BasicEvent implements Event { - NONE: number; - CAPTURING_PHASE: number; - AT_TARGET: number; - BUBBLING_PHASE: number; - private type_; - private target_; + class BasicEvent { + protected type_: string; + protected target_: IEventDispatcher; private currentTarget_; protected trusted_: boolean; protected bubbles_: boolean; @@ -198,7 +190,6 @@ declare namespace samchon.library { /** * @inheritdoc */ - preventDefault(): void; /** * @inheritdoc */ @@ -256,22 +247,12 @@ declare namespace samchon.library { */ returnValue: boolean; } - class ProgressEvent extends library.BasicEvent { - static PROGRESS: string; - protected numerator_: number; - protected denominator_: number; - constructor(type: string, numerator: number, denominator: number); - numerator: number; - denominator: number; - } } declare namespace samchon.collection { /** * Type of function pointer for listener of {@link CollectionEvent CollectionEvents}. */ - interface CollectionEventListener extends EventListener { - (event: CollectionEvent): void; - } + type CollectionEventListener = (event: CollectionEvent) => void; } declare namespace samchon.collection { /** @@ -281,11 +262,13 @@ declare namespace samchon.collection { /** * @hidden */ - private first_; + protected first_: std.Iterator; /** * @hidden */ - private last_; + protected last_: std.Iterator; + private temporary_container_; + private origin_first_; /** * Initialization Constructor. * @@ -298,9 +281,9 @@ declare namespace samchon.collection { constructor(type: "erase", first: std.Iterator, last: std.Iterator); constructor(type: "refresh", first: std.Iterator, last: std.Iterator); /** - * Get associative container. + * Get associative target, the container. */ - container: ICollection; + target: ICollection; /** * Get range of the first. */ @@ -309,12 +292,19 @@ declare namespace samchon.collection { * Get range of the last. */ last: std.Iterator; + /** + * @inheritdoc + */ + preventDefault(): void; } } +/** + * @hidden + */ declare namespace samchon.collection.CollectionEvent { - const INSERT: string; - const ERASE: string; - const REFRESH: string; + const INSERT: "insert"; + const ERASE: "erase"; + const REFRESH: "refresh"; } declare namespace samchon.collection { /** @@ -357,11 +347,11 @@ declare namespace samchon.collection { /** * @hidden */ - protected insert_by_repeating_val(position: std.DequeIterator, n: number, val: T): std.DequeIterator; + protected _Insert_by_repeating_val(position: std.DequeIterator, n: number, val: T): std.DequeIterator; /** * @hidden */ - protected insert_by_range>(position: std.DequeIterator, begin: InputIterator, end: InputIterator): std.DequeIterator; + protected _Insert_by_range>(position: std.DequeIterator, begin: InputIterator, end: InputIterator): std.DequeIterator; /** * @inheritdoc */ @@ -369,7 +359,7 @@ declare namespace samchon.collection { /** * @hidden */ - protected erase_by_range(first: std.DequeIterator, last: std.DequeIterator): std.DequeIterator; + protected _Erase_by_range(first: std.DequeIterator, last: std.DequeIterator): std.DequeIterator; /** * @hidden */ @@ -385,7 +375,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -401,28 +391,28 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; addEventListener(type: "insert", listener: CollectionEventListener): void; addEventListener(type: "erase", listener: CollectionEventListener): void; addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; removeEventListener(type: "insert", listener: CollectionEventListener): void; removeEventListener(type: "erase", listener: CollectionEventListener): void; removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; @@ -462,11 +452,11 @@ declare namespace samchon.collection { /** * @inheritdoc */ - protected handle_insert(first: std.MapIterator, last: std.MapIterator): void; + protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; /** * @inheritdoc */ - protected handle_erase(first: std.MapIterator, last: std.MapIterator): void; + protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; /** * @inheritdoc */ @@ -474,7 +464,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -490,31 +480,31 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener>): void; - addEventListener(type: "erase", listener: CollectionEventListener>): void; - addEventListener(type: "refresh", listener: CollectionEventListener>): void; + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: MapCollectionEventListener): void; + addEventListener(type: "erase", listener: MapCollectionEventListener): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener>): void; - removeEventListener(type: "erase", listener: CollectionEventListener>): void; - removeEventListener(type: "refresh", listener: CollectionEventListener>): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; } } declare namespace samchon.collection { @@ -544,11 +534,11 @@ declare namespace samchon.collection { /** * @inheritdoc */ - protected handle_insert(first: std.MapIterator, last: std.MapIterator): void; + protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; /** * @inheritdoc */ - protected handle_erase(first: std.MapIterator, last: std.MapIterator): void; + protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; /** * @inheritdoc */ @@ -556,7 +546,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -572,31 +562,31 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener>): void; - addEventListener(type: "erase", listener: CollectionEventListener>): void; - addEventListener(type: "refresh", listener: CollectionEventListener>): void; + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: MapCollectionEventListener): void; + addEventListener(type: "erase", listener: MapCollectionEventListener): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener>): void; - removeEventListener(type: "erase", listener: CollectionEventListener>): void; - removeEventListener(type: "refresh", listener: CollectionEventListener>): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; } } declare namespace samchon.collection { @@ -623,6 +613,14 @@ declare namespace samchon.collection { * A chain object taking responsibility of dispatching events. */ private event_dispatcher_; + /** + * @inheritdoc + */ + protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; /** * @inheritdoc */ @@ -630,7 +628,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -646,28 +644,28 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; addEventListener(type: "insert", listener: CollectionEventListener): void; addEventListener(type: "erase", listener: CollectionEventListener): void; addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; removeEventListener(type: "insert", listener: CollectionEventListener): void; removeEventListener(type: "erase", listener: CollectionEventListener): void; removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; @@ -701,11 +699,11 @@ declare namespace samchon.collection { /** * @inheritdoc */ - protected handle_insert(first: std.SetIterator, last: std.SetIterator): void; + protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; /** * @inheritdoc */ - protected handle_erase(first: std.SetIterator, last: std.SetIterator): void; + protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; /** * @inheritdoc */ @@ -713,7 +711,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -729,28 +727,28 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; addEventListener(type: "insert", listener: CollectionEventListener): void; addEventListener(type: "erase", listener: CollectionEventListener): void; addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; removeEventListener(type: "insert", listener: CollectionEventListener): void; removeEventListener(type: "erase", listener: CollectionEventListener): void; removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; @@ -830,32 +828,39 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; addEventListener(type: "insert", listener: CollectionEventListener): void; addEventListener(type: "erase", listener: CollectionEventListener): void; addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; removeEventListener(type: "insert", listener: CollectionEventListener): void; removeEventListener(type: "erase", listener: CollectionEventListener): void; removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; } + /** + * @hidden + */ + namespace ICollection { + function _Dispatch_CollectionEvent(collection: ICollection, type: string, first: std.Iterator, last: std.Iterator): void; + function _Dispatch_MapCollectionEvent(collection: ICollection>, type: string, first: std.MapIterator, last: std.MapIterator): void; + } } declare namespace samchon.collection { /** @@ -908,11 +913,11 @@ declare namespace samchon.collection { /** * @hidden */ - protected insert_by_repeating_val(position: std.ListIterator, n: number, val: T): std.ListIterator; + protected _Insert_by_repeating_val(position: std.ListIterator, n: number, val: T): std.ListIterator; /** * @hidden */ - protected insert_by_range>(position: std.ListIterator, begin: InputIterator, end: InputIterator): std.ListIterator; + protected _Insert_by_range>(position: std.ListIterator, begin: InputIterator, end: InputIterator): std.ListIterator; /** * @inheritdoc */ @@ -924,7 +929,7 @@ declare namespace samchon.collection { /** * @hidden */ - protected erase_by_range(first: std.ListIterator, last: std.ListIterator): std.ListIterator; + protected _Erase_by_range(first: std.ListIterator, last: std.ListIterator): std.ListIterator; /** * @hidden */ @@ -940,7 +945,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -956,33 +961,46 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; addEventListener(type: "insert", listener: CollectionEventListener): void; addEventListener(type: "erase", listener: CollectionEventListener): void; addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; removeEventListener(type: "insert", listener: CollectionEventListener): void; removeEventListener(type: "erase", listener: CollectionEventListener): void; removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; } } +declare namespace samchon.collection { + type MapCollectionEventListener = (event: MapCollectionEvent) => void; + class MapCollectionEvent extends CollectionEvent> { + /** + * @inheritdoc + */ + first: std.MapIterator; + /** + * @inheritdoc + */ + last: std.MapIterator; + } +} declare namespace samchon.collection { /** * A {@link TreeMap} who can detect element I/O events. @@ -1017,11 +1035,11 @@ declare namespace samchon.collection { /** * @inheritdoc */ - protected handle_insert(first: std.MapIterator, last: std.MapIterator): void; + protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; /** * @inheritdoc */ - protected handle_erase(first: std.MapIterator, last: std.MapIterator): void; + protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; /** * @inheritdoc */ @@ -1029,7 +1047,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -1045,31 +1063,31 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener>): void; - addEventListener(type: "erase", listener: CollectionEventListener>): void; - addEventListener(type: "refresh", listener: CollectionEventListener>): void; + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: MapCollectionEventListener): void; + addEventListener(type: "erase", listener: MapCollectionEventListener): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener>): void; - removeEventListener(type: "erase", listener: CollectionEventListener>): void; - removeEventListener(type: "refresh", listener: CollectionEventListener>): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; } } declare namespace samchon.collection { @@ -1099,11 +1117,11 @@ declare namespace samchon.collection { /** * @inheritdoc */ - protected handle_insert(first: std.MapIterator, last: std.MapIterator): void; + protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; /** * @inheritdoc */ - protected handle_erase(first: std.MapIterator, last: std.MapIterator): void; + protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; /** * @inheritdoc */ @@ -1111,7 +1129,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -1127,31 +1145,31 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener>): void; - addEventListener(type: "erase", listener: CollectionEventListener>): void; - addEventListener(type: "refresh", listener: CollectionEventListener>): void; + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: MapCollectionEventListener): void; + addEventListener(type: "erase", listener: MapCollectionEventListener): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener>): void; - removeEventListener(type: "erase", listener: CollectionEventListener>): void; - removeEventListener(type: "refresh", listener: CollectionEventListener>): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; } } declare namespace samchon.collection { @@ -1181,11 +1199,11 @@ declare namespace samchon.collection { /** * @inheritdoc */ - protected handle_insert(first: std.SetIterator, last: std.SetIterator): void; + protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; /** * @inheritdoc */ - protected handle_erase(first: std.SetIterator, last: std.SetIterator): void; + protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; /** * @inheritdoc */ @@ -1193,7 +1211,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -1209,28 +1227,28 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; addEventListener(type: "insert", listener: CollectionEventListener): void; addEventListener(type: "erase", listener: CollectionEventListener): void; addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; removeEventListener(type: "insert", listener: CollectionEventListener): void; removeEventListener(type: "erase", listener: CollectionEventListener): void; removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; @@ -1261,6 +1279,14 @@ declare namespace samchon.collection { * A chain object taking responsibility of dispatching events. */ private event_dispatcher_; + /** + * @inheritdoc + */ + protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; /** * @inheritdoc */ @@ -1268,7 +1294,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -1284,28 +1310,28 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; addEventListener(type: "insert", listener: CollectionEventListener): void; addEventListener(type: "erase", listener: CollectionEventListener): void; addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; removeEventListener(type: "insert", listener: CollectionEventListener): void; removeEventListener(type: "erase", listener: CollectionEventListener): void; removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; @@ -1323,8 +1349,8 @@ declare namespace samchon.library { * *

Relationships between XML and XMLList

*
    - *
  • XML contains XMLList from dictionary of XMLList.
  • - *
  • XMLList contains XML from vector of XML.
  • + *
  • XML is std.HashMap
  • + *
  • XMLList is std.Deque
  • *
* *

Note

@@ -1337,17 +1363,28 @@ declare namespace samchon.library { * * * - * <memberList>
- *      <member id='jhnam88' name='Jeongho+Nam' birthdate='1988-03-11' />
- *      <member id='master' name='Administartor' birthdate='2011-07-28' />
- * </memberList> + * + * + * + * + * + * * * - * <member>
- *      <id>jhnam88</id>
- *      <name>Jeongho+Nam</name>
- *      <birthdate>1988-03-11</birthdate>
- * </member> + * + * + * + * jhnam88 + * Jeongho Nam + * 1988-03-11 + * + * + * master + * Administartor + * 2011-07-28 + * + * + * * * * @@ -1363,7 +1400,7 @@ declare namespace samchon.library { *
  • \<price high='1500' low='1300' open='1450' close='1320' /\>: tag => \"price\"
  • * */ - private tag; + private tag_; /** *

    Value of the XML.

    * @@ -1372,7 +1409,7 @@ declare namespace samchon.library { *
  • \: value => null
  • * */ - private value; + private value_; /** *

    Properties belongs to the XML.

    *

    A Dictionary of properties accessing each property by its key.

    @@ -1385,7 +1422,7 @@ declare namespace samchon.library { * {\"comment\", \"Hello. My name is Jeongho Nam \"}} * */ - private properties; + private property_map_; /** *

    Default Constructor.

    * @@ -1703,11 +1740,11 @@ declare namespace samchon.collection { /** * @hidden */ - protected insert_by_repeating_val(position: std.DequeIterator, n: number, val: library.XML): std.DequeIterator; + protected _Insert_by_repeating_val(position: std.DequeIterator, n: number, val: library.XML): std.DequeIterator; /** * @hidden */ - protected insert_by_range>(position: std.DequeIterator, begin: InputIterator, end: InputIterator): std.DequeIterator; + protected _Insert_by_range>(position: std.DequeIterator, begin: InputIterator, end: InputIterator): std.DequeIterator; /** * @inheritdoc */ @@ -1715,7 +1752,7 @@ declare namespace samchon.collection { /** * @hidden */ - protected erase_by_range(first: std.DequeIterator, last: std.DequeIterator): std.DequeIterator; + protected _Erase_by_range(first: std.DequeIterator, last: std.DequeIterator): std.DequeIterator; /** * @hidden */ @@ -1731,7 +1768,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -1747,28 +1784,28 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; addEventListener(type: "insert", listener: CollectionEventListener): void; addEventListener(type: "erase", listener: CollectionEventListener): void; addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; removeEventListener(type: "insert", listener: CollectionEventListener): void; removeEventListener(type: "erase", listener: CollectionEventListener): void; removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; @@ -1887,6 +1924,7 @@ declare namespace samchon.library { } } declare namespace samchon.library { + type BasicEventListener = (event: BasicEvent) => void; /** *

    The IEventDispatcher interface defines methods for adding or removing event listeners, checks * whether specific types of event listeners are registered, and dispatches events.

    @@ -1975,7 +2013,7 @@ declare namespace samchon.library { * This function must accept an Event object as its only parameter and must return * nothing. */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; /** *

    Registers an event listener object with an EventDispatcher object so that the listener * receives notification of an event. You can register event listeners on all nodes in the display @@ -2020,7 +2058,7 @@ declare namespace samchon.library { * nothing. * @param thisArg The object to be used as the this object. */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; /** * Removes a listener from the EventDispatcher object. If there is no matching listener registered * with the EventDispatcher object, a call to this method has no effect. @@ -2028,7 +2066,7 @@ declare namespace samchon.library { * @param type The type of event. * @param listener The listener object to remove. */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; /** * Removes a listener from the EventDispatcher object. If there is no matching listener registered * with the EventDispatcher object, a call to this method has no effect. @@ -2037,7 +2075,7 @@ declare namespace samchon.library { * @param listener The listener object to remove. * @param thisArg The object to be used as the this object. */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; } /** *

    Registers an event listener object with an EventDispatcher object so that the listener @@ -2091,7 +2129,7 @@ declare namespace samchon.library { /** * Container of listeners. */ - protected event_listeners_: std.HashMap>>; + protected event_listeners_: std.HashMap>>; /** * Default Constructor. */ @@ -2109,23 +2147,23 @@ declare namespace samchon.library { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; } } declare namespace samchon.library { @@ -2247,6 +2285,10 @@ declare namespace samchon.library { *

    */ modificationDate: Date; + /** + * @hidden + */ + _Set_file(val: File): void; /** *

    Displays a file-browsing dialog box that lets the user select a file to upload. The dialog box is native * to the user's browser system. The user can select a file on the local computer or from other systems, for @@ -2418,7 +2460,7 @@ declare namespace samchon.library { /** * Whether each element (Gene) is unique in their GeneArray. */ - private unique; + private unique_; /** * Rate of mutation. * @@ -2432,11 +2474,11 @@ declare namespace samchon.library { * * */ - private mutation_rate; + private mutation_rate_; /** * Number of tournaments in selection. */ - private tournament; + private tournament_; /** * Initialization Constructor. * @@ -2567,7 +2609,7 @@ declare namespace samchon.library { /** * Genes representing the population. */ - private children; + private children_; /** *

    A comparison function returns whether left gene is more optimal, greater.

    * @@ -2586,7 +2628,7 @@ declare namespace samchon.library { *

    If you don't want to follow the rule or want a custom comparison function, you have to realize a * comparison function.

    */ - private compare; + private compare_; /** *

    Private constructor with population.

    * @@ -2622,6 +2664,7 @@ declare namespace samchon.library { * @param compare A comparison function returns whether left gene is more optimal. */ constructor(geneArray: GeneArray, size: number, compare: (left: GeneArray, right: GeneArray) => boolean); + _Get_children(): std.Vector; /** * Test fitness of each GeneArray in the {@link population}. * @@ -2924,6 +2967,13 @@ declare namespace samchon.protocol { */ toXML(): library.XML; } + /** + * @hidden + */ + namespace IEntity { + function construct(entity: IEntity, xml: library.XML, ...prohibited_names: string[]): void; + function toXML(entity: IEntity, ...prohibited_names: string[]): library.XML; + } /** *

    An entity, a standard data class.

    * @@ -3104,7 +3154,8 @@ declare namespace samchon.protocol { /** * Close connection. */ - close(): any; + close(): void; + isConnected(): boolean; sendData(invoke: protocol.Invoke): void; replyData(invoke: protocol.Invoke): void; } @@ -3114,19 +3165,20 @@ declare namespace samchon.protocol { /** * @hidden */ - protected listener: IProtocol; + protected listener_: IProtocol; /** * @inheritdoc */ onClose: Function; + protected connected_: boolean; /** * @hidden */ - private binary_invoke; + private binary_invoke_; /** * @hidden */ - private binary_parameters; + private binary_parameters_; /** * @hidden */ @@ -3135,11 +3187,20 @@ declare namespace samchon.protocol { * Default Constructor. */ constructor(); + /** + * Construct from listener. + * + * @param listener An {@link IProtocol} object to listen {@link Invoke} messages. + */ constructor(listener: IProtocol); /** * @inheritdoc */ abstract close(): void; + /** + * @inheritdoc + */ + isConnected(): boolean; protected is_binary_invoke(): boolean; abstract sendData(invoke: Invoke): void; replyData(invoke: Invoke): void; @@ -3148,27 +3209,27 @@ declare namespace samchon.protocol { } } declare namespace samchon.protocol { - class Communicator extends CommunicatorBase { + abstract class Communicator extends CommunicatorBase { /** * @hidden */ - protected socket: socket.socket; + protected socket_: socket.socket; /** * @hidden */ - private header_bytes; + private header_bytes_; /** * @hidden */ - private data; + private data_; /** * @hidden */ - private data_index; + private data_index_; /** * @hidden */ - private listening; + private listening_; /** * @inheritdoc */ @@ -3223,11 +3284,11 @@ declare namespace samchon.protocol { * * @author Jeongho Nam */ - class WebCommunicator extends CommunicatorBase { + abstract class WebCommunicator extends CommunicatorBase { /** * Connection driver, a socket for web-socket. */ - protected connection: websocket.connection; + protected connection_: websocket.connection; /** * Close the connection. */ @@ -3249,8 +3310,8 @@ declare namespace samchon.protocol { } } declare namespace samchon.protocol { - class SharedWorkerCommunicator extends CommunicatorBase { - protected port: MessagePort; + abstract class SharedWorkerCommunicator extends CommunicatorBase { + protected port_: MessagePort; close(): void; /** * @inheritdoc @@ -3481,12 +3542,12 @@ declare namespace samchon.protocol { /** * Requested path. */ - private path; + private path_; /** * Session ID, an identifier of the remote client. */ - private session_id; - private listening; + private session_id_; + private listening_; /** * Initialization Constructor. * @@ -3556,6 +3617,11 @@ declare namespace samchon.protocol { } } declare namespace samchon.protocol { + /** + * A container of entity, and it's a type of entity, too. + * + * @author Jeongho Nam + */ interface IEntityGroup extends IEntity, std.base.IContainer { /** *

    Construct data of the Entity from an XML object.

    @@ -3578,6 +3644,7 @@ declare namespace samchon.protocol { * * @return A new child Entity belongs to EntityArray. */ + createChild(xml: library.XML): T; /** *

    Get iterator to element.

    * @@ -3644,6 +3711,24 @@ declare namespace samchon.protocol { */ toXML(): library.XML; } + /** + * @hidden + */ + namespace IEntityGroup { + /** + * @hidden + */ + function construct(entityGroup: IEntityGroup, xml: library.XML, ...prohibited_names: string[]): void; + /** + * @hidden + */ + function toXML(entityGroup: IEntityGroup, ...prohibited_names: string[]): library.XML; + function has(entityGroup: IEntityGroup, key: any): boolean; + function count(entityGroup: IEntityGroup, key: any): number; + function get(entityGroup: IEntityGroup, key: any): T; + } +} +declare namespace samchon.protocol { /** * @inheritdoc */ @@ -3653,22 +3738,13 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - *

    Factory method of a child Entity.

    - * - *

    EntityArray::createChild() is a factory method creating a new child Entity which is belonged - * to the EntityArray. This method is called by EntityArray::construct(). The children construction - * methods Entity::construct() will be called by abstract method of the EntityArray::construct().

    - * - * @return A new child Entity belongs to EntityArray. + * @inheritdoc */ - protected abstract createChild(xml: library.XML): T; + abstract createChild(xml: library.XML): T; /** * @inheritdoc */ key(): any; - /** - * @inheritdoc - */ /** * @inheritdoc */ @@ -3694,6 +3770,8 @@ declare namespace samchon.protocol { */ toXML(): library.XML; } +} +declare namespace samchon.protocol { /** * @inheritdoc */ @@ -3703,22 +3781,13 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - *

    Factory method of a child Entity.

    - * - *

    EntityArray::createChild() is a factory method creating a new child Entity which is belonged - * to the EntityArray. This method is called by EntityArray::construct(). The children construction - * methods Entity::construct() will be called by abstract method of the EntityArray::construct().

    - * - * @return A new child Entity belongs to EntityArray. + * @inheritdoc */ - protected abstract createChild(xml: library.XML): T; + abstract createChild(xml: library.XML): T; /** * @inheritdoc */ key(): any; - /** - * @inheritdoc - */ /** * @inheritdoc */ @@ -3744,6 +3813,8 @@ declare namespace samchon.protocol { */ toXML(): library.XML; } +} +declare namespace samchon.protocol { /** * @inheritdoc */ @@ -3753,22 +3824,13 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - *

    Factory method of a child Entity.

    - * - *

    EntityArray::createChild() is a factory method creating a new child Entity which is belonged - * to the EntityArray. This method is called by EntityArray::construct(). The children construction - * methods Entity::construct() will be called by abstract method of the EntityArray::construct().

    - * - * @return A new child Entity belongs to EntityArray. + * @inheritdoc */ - protected abstract createChild(xml: library.XML): T; + abstract createChild(xml: library.XML): T; /** * @inheritdoc */ key(): any; - /** - * @inheritdoc - */ /** * @inheritdoc */ @@ -3801,6 +3863,8 @@ declare namespace samchon.protocol { */ interface IEntityCollection extends IEntityGroup, collection.ICollection { } +} +declare namespace samchon.protocol { /** * @inheritdoc */ @@ -3810,22 +3874,13 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - *

    Factory method of a child Entity.

    - * - *

    EntityArray::createChild() is a factory method creating a new child Entity which is belonged - * to the EntityArray. This method is called by EntityArray::construct(). The children construction - * methods Entity::construct() will be called by abstract method of the EntityArray::construct().

    - * - * @return A new child Entity belongs to EntityArray. + * @inheritdoc */ - protected abstract createChild(xml: library.XML): T; + abstract createChild(xml: library.XML): T; /** * @inheritdoc */ key(): any; - /** - * @inheritdoc - */ /** * @inheritdoc */ @@ -3851,6 +3906,8 @@ declare namespace samchon.protocol { */ toXML(): library.XML; } +} +declare namespace samchon.protocol { /** * @inheritdoc */ @@ -3860,22 +3917,13 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - *

    Factory method of a child Entity.

    - * - *

    EntityArray::createChild() is a factory method creating a new child Entity which is belonged - * to the EntityArray. This method is called by EntityArray::construct(). The children construction - * methods Entity::construct() will be called by abstract method of the EntityArray::construct().

    - * - * @return A new child Entity belongs to EntityArray. + * @inheritdoc */ - protected abstract createChild(xml: library.XML): T; + abstract createChild(xml: library.XML): T; /** * @inheritdoc */ key(): any; - /** - * @inheritdoc - */ /** * @inheritdoc */ @@ -3901,6 +3949,8 @@ declare namespace samchon.protocol { */ toXML(): library.XML; } +} +declare namespace samchon.protocol { /** * @inheritdoc */ @@ -3910,22 +3960,13 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - *

    Factory method of a child Entity.

    - * - *

    EntityArray::createChild() is a factory method creating a new child Entity which is belonged - * to the EntityArray. This method is called by EntityArray::construct(). The children construction - * methods Entity::construct() will be called by abstract method of the EntityArray::construct().

    - * - * @return A new child Entity belongs to EntityArray. + * @inheritdoc */ - protected abstract createChild(xml: library.XML): T; + abstract createChild(xml: library.XML): T; /** * @inheritdoc */ key(): any; - /** - * @inheritdoc - */ /** * @inheritdoc */ @@ -4232,7 +4273,7 @@ declare namespace samchon.protocol { /** *

    Listener, represent function's name.

    */ - protected listener: string; + private listener; /** * Default Constructor. */ @@ -4254,7 +4295,7 @@ declare namespace samchon.protocol { /** * @inheritdoc */ - protected createChild(xml: library.XML): InvokeParameter; + createChild(xml: library.XML): InvokeParameter; /** * Get listener. */ @@ -4322,10 +4363,10 @@ declare namespace samchon.protocol { * @inheritdoc */ construct(xml: library.XML): void; - setValue(value: number): any; - setValue(value: string): any; - setValue(value: library.XML): any; - setValue(value: Uint8Array): any; + setValue(value: number): void; + setValue(value: string): void; + setValue(value: library.XML): void; + setValue(value: Uint8Array): void; /** * @inheritdoc */ @@ -4365,25 +4406,31 @@ declare namespace samchon.protocol { /** * */ - private startTime; + private start_time_; /** * */ - private endTime; + private end_time_; /** * Default Constructor. */ constructor(); constructor(invoke: Invoke); construct(xml: library.XML): void; - notifyEnd(): void; + complete(): void; key(): number; getUID(): number; getListener(): string; getStartTime(): Date; getEndTime(): Date; computeElapsedTime(): number; + /** + * @inheritdoc + */ TAG(): string; + /** + * @inheritdoc + */ toXML(): library.XML; toInvoke(): Invoke; } @@ -4525,15 +4572,15 @@ declare namespace samchon.protocol { /** * A server handler. */ - private http_server; + private http_server_; /** * Sequence number for issuing session id. */ - private sequence; + private sequence_; /** * @hidden */ - private my_port; + private my_port_; /** * Default Constructor. */ @@ -4685,7 +4732,7 @@ declare namespace samchon.protocol { * @author Jeongho Nam */ class ServerBase extends Server implements IServerBase { - private target; + private target_; constructor(target: IServer); addClient(driver: IClientDriver): void; } @@ -4730,7 +4777,7 @@ declare namespace samchon.protocol { * @author Jeongho Nam */ class WebServerBase extends WebServer implements IServerBase { - private target; + private target_; constructor(target: IServer); addClient(driver: IClientDriver): void; } @@ -4776,7 +4823,7 @@ declare namespace samchon.protocol { * @author Jeongho Nam */ class SharedWorkerServerBase extends SharedWorkerServer implements IServerBase { - private target; + private target_; constructor(target: IServer); addClient(driver: IClientDriver): void; } @@ -4849,13 +4896,13 @@ declare namespace samchon.protocol { * *

    Note that, {@link socket} is only used in web-browser environment.

    */ - private browser_socket; + private browser_socket_; /** *

    A driver for server connection.

    * *

    Note that, {@link node_client} is only used in NodeJS environment.

    */ - private node_client; + private node_client_; /** * @inheritdoc */ @@ -4889,11 +4936,17 @@ declare namespace samchon.protocol { } } declare namespace samchon.protocol { + /** + * @hidden + */ namespace socket { type socket = any; type server = any; type http_server = any; } + /** + * @hidden + */ namespace websocket { type connection = any; type request = any; @@ -4902,14 +4955,42 @@ declare namespace samchon.protocol { type client = any; } } +declare namespace samchon.protocol.distributed { + class DSInvokeHistory extends InvokeHistory { + private system_; + private role_; + /** + * Construct from a DistributedSystem. + * + * @param system + */ + constructor(system: DistributedSystem); + /** + * Initilizer Constructor. + * + * @param system + * @param role + * @param invoke + */ + constructor(system: DistributedSystem, role: DistributedSystemRole, invoke: Invoke); + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + getSystem(): DistributedSystem; + getRole(): DistributedSystemRole; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} declare namespace samchon.protocol.external { /** - *

    An external system driver.

    + *

    A role of an external system.

    * - *

    The {@link ExternalSystem} class represents an external system, connected and interact with this system. - * {@link ExternalSystem} takes full charge of network communication with external system have connected. - * Replied {@link Invoke messages} from the external system is shifted to and processed in, children elements of this - * class, {@link ExternalSystemRole} objects.

    + *

    The {@link ExternalSystemRole} class represents a role, what to do in an {@link ExternalSystem}. + * Extends this class and writes some methods related to the role.

    * *

    @@ -4917,9 +4998,9 @@ declare namespace samchon.protocol.external { * style="max-width: 100%" /> *

    * - *

    Bridge & Proxy Pattern

    - *

    The {@link ExternalSystem} class can be a bridge for logical proxy. In framework within user, - * which {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + *

    Proxy Pattern

    + *

    The {@link ExternalSystemRole} class can be an logical proxy. In framework within user, which + * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not * important. Only interested in user's perspective is which can be done.

    * *

    By using the logical proxy, user dont't need to know which {@link ExternalSystemRole role} is belonged @@ -4936,197 +5017,81 @@ declare namespace samchon.protocol.external { * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the * external system. * - *

  • Those strategy is called Bridge Pattern and Proxy Pattern.
  • + *
  • Those strategy is called Proxy Pattern.
  • * * * @author Jeongho Nam */ - abstract class ExternalSystem extends EntityDequeCollection implements IProtocol { + abstract class ExternalSystemRole extends Entity implements IProtocol { /** - * A network communicator with external system. + * An {@link ExternalSystem external system} containing this {@link ExternalSystemRole role}. */ + private system; /** - * A network communicator with external system. - */ - protected communicator: ICommunicator; - /** - * The name represents external system have connected. + *

    A name, represents and identifies this {@link ExternalSystemRole role}.

    + * + *

    This {@link name} is an identifier represents this {@link ExternalSystemRole role}. This {@link name} is + * used in {@link ExternalSystemArray.getRole} and {@link ExternalSystem.get}, as a key elements. Thus, this + * {@link name} should be unique in an {@link ExternalSystemArray}. */ protected name: string; /** - * Default Constructor. - */ - constructor(); - /** - * Construct from an IClientDriver object. + * Constructor from a system. * - * @param driver + * @param system An external system containing this role. */ - constructor(driver: IClientDriver); + constructor(system: ExternalSystem); /** - * Default Destructor. - */ - destructor(): void; - /** - * Identifier of {@link ExternalSystem} is its {@link name}. + * Identifier of {@link ExternalSystemRole} is its {@link name}. */ key(): string; /** - * Get {@link name}. + * Get external system, this role is belonged to. + */ + getSystem(): ExternalSystem; + /** + * Get name, who represents and identifies this role. */ getName(): string; - close(): void; /** - * Send {@link Invoke} message to external system. + * Send an {@link Invoke} message to the external system via {@link system}. * - * @param invoke An {@link Invoke} message to send. + * @param invoke An {@link Invoke} message to send to the external system. */ sendData(invoke: Invoke): void; /** - * Handle an {@Invoke} message have received. + *

    Handle replied {@link Invoke message} from the {@link system external system} belonged to.

    * - * @param invoke An {@link Invoke} message have received. + *

    This {@link replyData replyData()} will call a member method named following {@link Invoke.listener}. + * in the invoke.

    + * + * @param invoke An {@link Invoke} message received from the {@link system external system}. */ replyData(invoke: Invoke): void; /** - * Tag name of the {@link ExternalSytem} in {@link XML}. - * - * @return system. - */ - TAG(): string; - /** - * Tag name of {@link ExternalSystemRole children elements} belonged to the {@link ExternalSytem} in {@link XML}. + * Tag name of the {@link ExternalSytemRole} in {@link XML}. * * @return role. */ - CHILD_TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - /** - * @hidden - */ - private communicator_; - /** - * @hidden - */ - private external_system_array_; - /** - * @hidden - */ - private erasing_; - /** - * @hidden - */ - private external_system_array; - /** - * @hidden - */ - private handle_close(); - } -} -declare namespace samchon.protocol.parallel { - /** - *

    An external parallel system driver.

    - * - * - * - * @author Jeongho Nam - */ - abstract class ParallelSystem extends external.ExternalSystem { - /** - * A manager containing this {@link ParallelSystem} object. - */ - private systemArray; - /** - * A list of {@link Invoke} messages on process. - * - * @see {@link performance} - */ - private progress_list; - /** - * A list of {@link Invoke} messages had processed. - * - * @see {@link performance} - */ - private history_list; - /** - *

    Performance index.

    - * - *

    A performance index that indicates how much fast the connected parallel system is.

    - * - *

    If this {@link ParallelSystem parallel system} hasn't any {@link Invoke} message - * {@link history_list had handled}, then the {@link performance performance index} will be 1, which means - * default and average value between all {@link ParallelSystem} instances (belonged to a same - * {@link ParallelSystemArray} object).

    - * - *

    You can specify this {@link performance} by yourself, but notice that, if the - * {@link performance performance index} is higher then other {@link ParallelSystem} objects, then this - * {@link ParallelSystem parallel system} will ordered to handle more processes than other {@link ParallelSystem} - * objects. Otherwise, the {@link performance performance index) is lower than others, of course, less processes - * will be delivered.

    - * - *

    This {@link performance index} is always re-calculated whenever {@link ParallelSystemArray} calls one of - * them below.

    - * - *
      - *
    • {@link ParallelSystemArray.sendSegmentData ParallelSystemArray.sendSegmentData()}
    • - *
    • {@link ParallelSystemArray.sendPieceData ParallelSystemArray.sendPieceData()}
    • - *
    - * - *

    If this class is a type of {@link DistributedSystem}, a derived class from the {@link ParallelSystem}, - * then {@link DistributedSystemRole.sendData DistributedSystem.sendData()} also cause the re-calculation.

    - * - * @see {@link progress_list}, {@link history_list} - */ - protected performance: number; - /** - * Construct from a {@link ParallelSystemArray}. - * - * @param systemArray A manager containing this {@link ParallelSystem} object. - * @param communicator A communicator who takes full charge of network communication with the external - * parallel system. - */ - constructor(systemArray: ParallelSystemArray, communicator?: ICommunicator); - /** - * Get manager of this object, {@link systemArray}. - * - * @return A manager containing this {@link ParallelSystem} object. - */ - getSystemArray(): ParallelSystemArray; - /** - * Get {@link performant performance index}. - * - * A performance index that indicates how much fast the connected parallel system is. - */ - getPerformance(): number; - /** - * Send an {@link Invoke} message with index of segmentation. - * - * @param invoke An invoke message requesting parallel process. - * @param first Initial piece's index in a section. - * @param last Final piece's index in a section. The ranged used is [first, last), which contains - * all the pieces' indices between first and last, including the piece pointed by index - * first, but not the piece pointed by the index last. - * - * @see {@link ParallelSystemArray.sendPieceData} - */ - private send_piece_data(invoke, first, last); - /** - * - * - * @param xml - * - * @see {@link ParallelSystemArray.notify_end} - */ - private report_invoke_history(xml); + TAG(): string; } } declare namespace samchon.protocol.distributed { - abstract class DistributedSystem extends parallel.ParallelSystem { + abstract class DistributedSystemRole extends external.ExternalSystemRole { + private system_array_; + private progress_list_; + private history_list_; + protected performance: number; + constructor(systemArray: DistributedSystemArray); + getSystemArray(): DistributedSystemArray; + getPerformance(): number; + sendData(invoke: protocol.Invoke): void; + _Report_history(history: DSInvokeHistory): void; } } +/** + * [[include: https://raw.githubusercontent.com/samchon/framework/master/handbook/TypeScript-Protocol-External_System.md]] + */ declare namespace samchon.protocol.external { /** *

    An array and manager of {@link ExternalSystem external systems}.

    @@ -5175,23 +5140,15 @@ declare namespace samchon.protocol.external { * * @author Jeongho Nam */ - abstract class ExternalSystemArray extends EntityArrayCollection implements IProtocol { + abstract class ExternalSystemArray extends EntityDequeCollection implements IProtocol { /** * Default Constructor. */ constructor(); - /** - * @hidden - */ - private handle_system_insert(event); /** * @hidden */ private handle_system_erase(event); - /** - * @hidden - */ - protected handle_system_close(system: ExternalSystem): void; /** * Test whether this system array has the role. * @@ -5244,13 +5201,25 @@ declare namespace samchon.protocol.parallel { */ abstract class ParallelSystemArray extends external.ExternalSystemArray { /** - * @see {@link ParallelSystem.progress_list}, {@link ParallelSystem.history_list} + * @hidden */ - private history_sequence; + private history_sequence_; /** * Default Constructor. */ constructor(); + /** + * @inheritdoc + */ + at(index: number): ParallelSystem; + /** + * @hidden + */ + _Fetch_history_sequence(): number; + /** + * @hidden + */ + _Set_history_sequence(val: number): void; /** * * @param invoke An invoke message requesting parallel process. @@ -5272,27 +5241,145 @@ declare namespace samchon.protocol.parallel { * @param history * * @return Whether the processes with same uid are all fininsed. - * - * @see {@link ParallelSystem.report_invoke_history}, {@link normalize_performance} */ - protected notify_end(history: PRInvokeHistory): boolean; + _Complete_history(history: InvokeHistory): boolean; /** - * @see {@link ParallelSystem.performance} + * @hidden */ private normalize_performance(); } } declare namespace samchon.protocol.distributed { abstract class DistributedSystemArray extends parallel.ParallelSystemArray { - protected roles: std.HashMap; + /** + * @hidden + */ + private role_map_; + /** + * Default Constructor. + */ + constructor(); + construct(xml: library.XML): void; + abstract createRole(xml: library.XML): DistributedSystemRole; + /** + * @inheritdoc + */ + at(index: number): DistributedSystem; + getRoleMap(): std.HashMap; + /** + * @inheritdoc + */ + hasRole(name: string): boolean; + /** + * @inheritdoc + */ + getRole(name: string): DistributedSystemRole; + insertRole(role: DistributedSystemRole): void; + eraseRole(name: string): void; + toXML(): library.XML; + } +} +declare namespace samchon.protocol.distributed { + abstract class DistributedClientArray extends DistributedSystemArray implements external.IExternalClientArray { + /** + * A subrogator of {@link IServer server}'s role instead of this {@link ExternalClientArray}. + */ + private server_base_; + /** + * Default Constructor. + */ + constructor(); + /** + *

    Factory method creating {@link IServerBase} object.

    + * + *

    This method {@link createServerBase createServerBase()} determines which protocol is used in this server, + * {@link ExternalClientArray}. If the protocol is determined, then {@link ExternalSystem external clients} who + * may connect to {@link ExternalClientArray this server} must follow the specified protocol.

    + * + *

    Creates and returns one of them:

    + *
      + *
    • {@link ServerBase}
    • + *
    • {@link WebServerBase}
    • + *
    • {@link SharedWorkerServerBase}
    • + *
    + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): IServerBase; + addClient(driver: IClientDriver): void; + createChild(xml: library.XML): DistributedSystem; + protected abstract createExternalClient(driver: IClientDriver): DistributedSystem; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.protocol.distributed { + abstract class DistributedSystemArrayMediator extends DistributedSystemArray { + private mediator_; + /** + * Default Constructor. + */ + constructor(); + protected abstract createMediator(): parallel.MediatorSystem; + protected startMediator(): void; + getMediator(): parallel.MediatorSystem; + _Complete_history(history: parallel.PRInvokeHistory): boolean; + } +} +declare namespace samchon.protocol.distributed { + abstract class DistributedClientArrayMediator extends DistributedSystemArrayMediator implements external.IExternalClientArray { + /** + * A subrogator of {@link IServer server}'s role instead of this {@link ExternalClientArray}. + */ + private server_base_; + /** + * Default Constructor. + */ + constructor(); + /** + *

    Factory method creating {@link IServerBase} object.

    + * + *

    This method {@link createServerBase createServerBase()} determines which protocol is used in this server, + * {@link ExternalClientArray}. If the protocol is determined, then {@link ExternalSystem external clients} who + * may connect to {@link ExternalClientArray this server} must follow the specified protocol.

    + * + *

    Creates and returns one of them:

    + *
      + *
    • {@link ServerBase}
    • + *
    • {@link WebServerBase}
    • + *
    • {@link SharedWorkerServerBase}
    • + *
    + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): IServerBase; + addClient(driver: IClientDriver): void; + createChild(xml: library.XML): DistributedSystem; + protected abstract createExternalClient(driver: IClientDriver): DistributedSystem; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; } } declare namespace samchon.protocol.external { /** - *

    A role of an external system.

    + *

    An external system driver.

    * - *

    The {@link ExternalSystemRole} class represents a role, what to do in an {@link ExternalSystem}. - * Extends this class and writes some methods related to the role.

    + *

    The {@link ExternalSystem} class represents an external system, connected and interact with this system. + * {@link ExternalSystem} takes full charge of network communication with external system have connected. + * Replied {@link Invoke messages} from the external system is shifted to and processed in, children elements of this + * class, {@link ExternalSystemRole} objects.

    * *

    @@ -5300,9 +5387,9 @@ declare namespace samchon.protocol.external { * style="max-width: 100%" /> *

    * - *

    Proxy Pattern

    - *

    The {@link ExternalSystemRole} class can be an logical proxy. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + *

    Bridge & Proxy Pattern

    + *

    The {@link ExternalSystem} class can be a bridge for logical proxy. In framework within user, + * which {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not * important. Only interested in user's perspective is which can be done.

    * *

    By using the logical proxy, user dont't need to know which {@link ExternalSystemRole role} is belonged @@ -5319,68 +5406,249 @@ declare namespace samchon.protocol.external { * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the * external system. * - *

  • Those strategy is called Proxy Pattern.
  • + *
  • Those strategy is called Bridge Pattern and Proxy Pattern.
  • * * * @author Jeongho Nam */ - abstract class ExternalSystemRole extends Entity implements IProtocol { + abstract class ExternalSystem extends EntityDequeCollection implements IProtocol { /** - * An {@link ExternalSystem external system} containing this {@link ExternalSystemRole role}. + * The name represents external system have connected. */ - private system; + protected name: string; /** - *

    A name, represents and identifies this {@link ExternalSystemRole role}.

    - * - *

    This {@link name} is an identifier represents this {@link ExternalSystemRole role}. This {@link name} is - * used in {@link ExternalSystemArray.getRole} and {@link ExternalSystem.get}, as a key elements. Thus, this - * {@link name} should be unique in an {@link ExternalSystemArray}. + * @hidden */ - private name; + private system_array_; /** - * Constructor from a system. - * - * @param system An external system containing this role. + * @hidden */ - constructor(system: ExternalSystem); + private communicator_; + constructor(systemArray: ExternalSystemArray); + constructor(systemArray: ExternalSystemArray, communicator: IClientDriver); /** - * Identifier of {@link ExternalSystemRole} is its {@link name}. + * Default Destructor. + */ + destructor(): void; + /** + * @hidden + */ + private handle_close(); + getSystemArray(): ExternalSystemArray; + /** + * Identifier of {@link ExternalSystem} is its {@link name}. */ key(): string; /** - * Get external system, this role is belonged to. - */ - getSystem(): ExternalSystem; - /** - * Get name, who represents and identifies this role. + * Get {@link name}. */ getName(): string; + protected communicator: protocol.ICommunicator; + close(): void; /** - * Send an {@link Invoke} message to the external system via {@link system}. + * Send {@link Invoke} message to external system. * - * @param invoke An {@link Invoke} message to send to the external system. + * @param invoke An {@link Invoke} message to send. */ sendData(invoke: Invoke): void; /** - *

    Handle replied {@link Invoke message} from the {@link system external system} belonged to.

    + * Handle an {@Invoke} message has received. * - *

    This {@link replyData replyData()} will call a member method named following {@link Invoke.listener}. - * in the invoke.

    - * - * @param invoke An {@link Invoke} message received from the {@link system external system}. + * @param invoke An {@link Invoke} message have received. */ replyData(invoke: Invoke): void; /** - * Tag name of the {@link ExternalSytemRole} in {@link XML}. + * Tag name of the {@link ExternalSytem} in {@link XML}. + * + * @return system. + */ + TAG(): string; + /** + * Tag name of {@link ExternalSystemRole children elements} belonged to the {@link ExternalSytem} in {@link XML}. * * @return role. */ - TAG(): string; + CHILD_TAG(): string; + } +} +declare namespace samchon.protocol.parallel { + /** + *

    An external parallel system driver.

    + * + * + * + * @author Jeongho Nam + */ + abstract class ParallelSystem extends external.ExternalSystem { + /** + * @hidden + */ + private progress_list_; + /** + * @hidden + */ + private history_list_; + /** + *

    Performance index.

    + * + *

    A performance index that indicates how much fast the connected parallel system is.

    + * + *

    If this {@link ParallelSystem parallel system} hasn't any {@link Invoke} message had handled, then the + * {@link performance performance index} will be 1, which means default and average value between all + * {@link ParallelSystem} instances (belonged to a same {@link ParallelSystemArray} object).

    + * + *

    You can specify this {@link performance} by yourself, but notice that, if the + * {@link performance performance index} is higher then other {@link ParallelSystem} objects, then this + * {@link ParallelSystem parallel system} will ordered to handle more processes than other + * {@link ParallelSystem} objects. Otherwise, the {@link performance performance index) is lower than others, + * of course, less processes will be delivered.

    + * + *

    This {@link performance index} is always re-calculated whenever {@link ParallelSystemArray} calls one of + * them below.

    + * + *
      + *
    • {@link ParallelSystemArray.sendSegmentData ParallelSystemArray.sendSegmentData()}
    • + *
    • {@link ParallelSystemArray.sendPieceData ParallelSystemArray.sendPieceData()}
    • + *
    + * + *

    If this class is a type of {@link DistributedSystem} derived class from the {@link ParallelSystem}, + * then {@link DistributedSystemRole.sendData DistributedSystemRole.sendData()} also cause the re-calculation. + *

    + */ + protected performance: number; + constructor(systemArray: ParallelSystemArray); + constructor(systemArray: ParallelSystemArray, communicator: IClientDriver); + destructor(): void; + /** + * Get manager of this object, {@link systemArray}. + * + * @return A manager containing this {@link ParallelSystem} object. + */ + getSystemArray(): ParallelSystemArray; + /** + * Get {@link performant performance index}. + * + * A performance index that indicates how much fast the connected parallel system is. + */ + getPerformance(): number; + _Get_progress_list(): std.HashMap>; + _Get_history_list(): std.HashMap; + _Set_performance(val: number): void; + /** + * @hidden + */ + _Send_piece_data(invoke: Invoke, first: number, last: number): void; + /** + * @hidden + */ + private _replyData(invoke); + /** + * + * + * @param xml + * + * @see {@link ParallelSystemArray.notify_complete} + */ + protected _Report_history(xml: library.XML): void; } } declare namespace samchon.protocol.distributed { - abstract class DistributedSystemRole extends external.ExternalSystemRole { - private systems; + abstract class DistributedSystem extends parallel.ParallelSystem { + destructor(): void; + createChild(xml: library.XML): external.ExternalSystemRole; + /** + * Get manager of this object. + * + * @return A manager containing this {@link DistributedSystem} objects. + */ + getSystemArray(): DistributedSystemArray; + /** + * @inheritdoc + */ + has(key: string): boolean; + /** + * @inheritdoc + */ + get(key: string): DistributedSystemRole; + replyData(invoke: protocol.Invoke): void; + protected _Report_history(xml: library.XML): void; + } +} +declare namespace samchon.protocol.distributed { + interface IDistributedServer extends DistributedSystem, external.IExternalServer { + /** + * @inheritdoc + */ + getSystemArray(): DistributedSystemArray; + /** + * @inheritdoc + */ + has(key: string): boolean; + /** + * @inheritdoc + */ + get(key: string): DistributedSystemRole; + } + abstract class DistributedServer extends DistributedSystem implements external.IExternalServer { + protected ip: string; + protected port: number; + constructor(systemArray: DistributedSystemArray); + protected abstract createServerConnector(): IServerConnector; + connect(): void; + getIP(): string; + getPort(): number; + } +} +declare namespace samchon.protocol.distributed { + abstract class DistributedServerArray extends DistributedSystemArray implements external.IExternalServerArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.protocol.distributed { + abstract class DistributedServerArrayMediator extends DistributedSystemArrayMediator implements external.IExternalServerArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.protocol.distributed { + abstract class DistributedServerClientArray extends DistributedClientArray implements external.IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + createChild(xml: library.XML): DistributedSystem; + protected abstract createExternalServer(xml: library.XML): IDistributedServer; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.protocol.distributed { + abstract class DistributedServerClientArrayMediator extends DistributedClientArrayMediator implements external.IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + createChild(xml: library.XML): DistributedSystem; + protected abstract createExternalServer(xml: library.XML): IDistributedServer; + /** + * @inheritdoc + */ + connect(): void; } } declare namespace samchon.protocol.external { @@ -5454,7 +5722,7 @@ declare namespace samchon.protocol.external { /** * A subrogator of {@link IServer server}'s role instead of this {@link ExternalClientArray}. */ - private server_base; + private server_base_; /** * Default Constructor. */ @@ -5482,7 +5750,7 @@ declare namespace samchon.protocol.external { * * @return null. */ - protected createChild(xml: library.XML): ExternalSystem; + createChild(xml: library.XML): ExternalSystem; /** * Factory method creating {@link ExternalSystem} object. * @@ -5528,18 +5796,7 @@ declare namespace samchon.protocol.external { * @author Jeongho Nam */ interface IExternalServer extends ExternalSystem { - /** - * Connect to the external system. - */ connect(): void; - /** - * Get ip address. - */ - getIP(): string; - /** - * Get port number. - */ - getPort(): number; } /** *

    An external server driver.

    @@ -5591,7 +5848,7 @@ declare namespace samchon.protocol.external { /** * Default Constructor. */ - constructor(); + constructor(systemArray: ExternalSystemArray); /** * Factory method creating server connector. */ @@ -5779,7 +6036,7 @@ declare namespace samchon.protocol.external { * * @return A new child Entity via {@link createExternalServer createExternalServer()}. */ - protected createChild(xml: library.XML): ExternalSystem; + createChild(xml: library.XML): ExternalSystem; /** * Factory method creating an {@link IExternalServer} object. * @@ -5795,33 +6052,34 @@ declare namespace samchon.protocol.external { } } declare namespace samchon.protocol.slave { - abstract class SlaveSystem extends external.ExternalSystem { + abstract class SlaveSystem implements protocol.IProtocol { + protected communicator_: ICommunicator; /** * Default Constructor. */ constructor(); + sendData(invoke: Invoke): void; + protected _replyData(invoke: Invoke): void; replyData(invoke: Invoke): void; } } -declare namespace samchon.protocol.external { +declare namespace samchon.protocol.parallel { abstract class MediatorSystem extends slave.SlaveSystem { - private system_array; - private progress_list; - constructor(systemArray: ExternalSystemArray); + private mediator_; + private progress_list_; + constructor(systemArray: ParallelSystemArrayMediator | distributed.DistributedSystemArrayMediator); abstract start(): void; - /** - * @hidden - */ - protected createChild(xml: library.XML): ExternalSystemRole; - private notify_end(uid); + getMediator(): ParallelSystemArrayMediator | distributed.DistributedSystemArrayMediator; + _Complete_history(uid: number): void; + protected _replyData(invoke: Invoke): void; replyData(invoke: protocol.Invoke): void; } } -declare namespace samchon.protocol.external { - class MediatorServer extends MediatorSystem implements IServer { - private server_base; +declare namespace samchon.protocol.parallel { + class MediatorServer extends MediatorSystem implements slave.ISlaveServer { + private server_base_; private port; - constructor(systemArray: ExternalSystemArray, port: number); + constructor(systemArray: ParallelSystemArrayMediator, port: number); protected createServerBase(): IServerBase; addClient(driver: IClientDriver): void; start(): void; @@ -5829,17 +6087,23 @@ declare namespace samchon.protocol.external { close(): void; } class MediatorWebServer extends MediatorServer { + /** + * @inheritdoc + */ protected createServerBase(): IServerBase; } class MediatorSharedWorkerServer extends MediatorServer { + /** + * @inheritdoc + */ protected createServerBase(): IServerBase; } } -declare namespace samchon.protocol.external { - class MediatorClient extends MediatorSystem implements IExternalServer { +declare namespace samchon.protocol.parallel { + class MediatorClient extends MediatorSystem implements slave.ISlaveClient { protected ip: string; protected port: number; - constructor(systemArray: ExternalSystemArray, ip: string, port: number); + constructor(systemArray: ParallelSystemArrayMediator, ip: string, port: number); protected createServerConnector(): IServerConnector; getIP(): string; getPort(): number; @@ -5881,6 +6145,8 @@ declare namespace samchon.protocol.parallel { constructor(invoke: Invoke); getFirst(): number; getLast(): number; + _Set_first(val: number): void; + _Set_last(val: number): void; /** * Compute number of allocated pieces. */ @@ -5892,7 +6158,7 @@ declare namespace samchon.protocol.parallel { /** * A subrogator of {@link IServer server}'s role instead of this {@link ExternalClientArray}. */ - private server_base; + private server_base_; /** * Default Constructor. */ @@ -5915,7 +6181,7 @@ declare namespace samchon.protocol.parallel { */ protected abstract createServerBase(): IServerBase; addClient(driver: IClientDriver): void; - protected createChild(xml: library.XML): ParallelSystem; + createChild(xml: library.XML): ParallelSystem; protected abstract createExternalClient(driver: IClientDriver): ParallelSystem; /** * @inheritdoc @@ -5929,16 +6195,15 @@ declare namespace samchon.protocol.parallel { } declare namespace samchon.protocol.parallel { abstract class ParallelSystemArrayMediator extends ParallelSystemArray { - protected mediator: external.MediatorSystem; + private mediator_; /** * Default Constructor. */ constructor(); - protected abstract createMediator(): external.MediatorSystem; + protected abstract createMediator(): MediatorSystem; protected start_mediator(): void; - sendData(invoke: protocol.Invoke): void; - sendPieceData(invoke: protocol.Invoke, first: number, last: number): void; - protected notify_end(history: PRInvokeHistory): boolean; + getMediator(): MediatorSystem; + _Complete_history(history: PRInvokeHistory): boolean; } } declare namespace samchon.protocol.parallel { @@ -5946,7 +6211,7 @@ declare namespace samchon.protocol.parallel { /** * A subrogator of {@link IServer server}'s role instead of this {@link ExternalClientArray}. */ - private server_base; + private server_base_; /** * Default Constructor. */ @@ -5969,7 +6234,7 @@ declare namespace samchon.protocol.parallel { */ protected abstract createServerBase(): IServerBase; addClient(driver: IClientDriver): void; - protected createChild(xml: library.XML): ParallelSystem; + createChild(xml: library.XML): ParallelSystem; protected abstract createExternalClient(driver: IClientDriver): ParallelSystem; /** * @inheritdoc @@ -5982,9 +6247,13 @@ declare namespace samchon.protocol.parallel { } } declare namespace samchon.protocol.parallel { - interface IParallelServer extends ParallelSystem, external.IExternalServer { + interface IParallelServer extends external.IExternalServer, ParallelSystem { + /** + * @inheritdoc + */ + getSystemArray(): ParallelSystemArray; } - abstract class ParallelServer extends ParallelSystem implements IParallelServer { + abstract class ParallelServer extends ParallelSystem implements external.IExternalServer { protected ip: string; protected port: number; constructor(systemArray: ParallelSystemArray); @@ -6003,6 +6272,9 @@ declare namespace samchon.protocol.parallel { declare namespace samchon.protocol.parallel { abstract class ParallelServerArrayMediator extends ParallelSystemArrayMediator implements external.IExternalServerArray { constructor(); + /** + * @inheritdoc + */ connect(): void; } } @@ -6012,7 +6284,7 @@ declare namespace samchon.protocol.parallel { * Default Constructor. */ constructor(); - protected createChild(xml: library.XML): ParallelSystem; + createChild(xml: library.XML): ParallelSystem; protected abstract createExternalServer(xml: library.XML): IParallelServer; connect(): void; } @@ -6023,7 +6295,7 @@ declare namespace samchon.protocol.parallel { * Default Constructor. */ constructor(); - protected createChild(xml: library.XML): ParallelSystem; + createChild(xml: library.XML): ParallelSystem; protected abstract createExternalServer(xml: library.XML): IParallelServer; /** * @inheritdoc @@ -6033,10 +6305,10 @@ declare namespace samchon.protocol.parallel { } declare namespace samchon.protocol.service { abstract class Client implements protocol.IProtocol { - private user; - private service; - private driver; - private no; + private user_; + private service_; + private communicator_; + private no_; /** * Construct from an User and WebClientDriver. */ @@ -6045,6 +6317,8 @@ declare namespace samchon.protocol.service { close(): void; getUser(): User; getService(): Service; + getNo(): number; + _Set_no(val: number): void; sendData(invoke: protocol.Invoke): void; replyData(invoke: protocol.Invoke): void; protected changeService(path: string): void; @@ -6052,8 +6326,8 @@ declare namespace samchon.protocol.service { } declare namespace samchon.protocol.service { abstract class Server extends protocol.WebServer implements IProtocol { - private session_map; - private account_map; + private session_map_; + private account_map_; /** * Default Constructor. */ @@ -6066,16 +6340,20 @@ declare namespace samchon.protocol.service { protected abstract createUser(): User; has(account: string): boolean; get(account: string): User; + /** + * @hidden + */ + _Get_account_map(): std.HashMap; sendData(invoke: protocol.Invoke): void; replyData(invoke: protocol.Invoke): void; addClient(driver: WebClientDriver): void; - private erase_user(user); + _Erase_user(user: User): void; } } declare namespace samchon.protocol.service { abstract class Service implements protocol.IProtocol { - private client; - private path; + private client_; + private path_; /** * Default Constructor. */ @@ -6095,39 +6373,75 @@ declare namespace samchon.protocol.service { } declare namespace samchon.protocol.service { abstract class User extends collection.HashMapCollection implements protocol.IProtocol { - private server; - private session_id; - private sequence; - private account_id; - private authority; + private server_; + private session_id_; + private sequence_; + private account_id_; + private authority_; /** * Construct from a Server. */ constructor(server: Server); protected abstract createClient(driver: WebClientDriver): Client; + /** + * @hidden + */ + _Create_child(driver: WebClientDriver): Client; + /** + * @hidden + */ private handle_erase_client(event); getServer(): Server; getAccountID(): string; getAuthority(): number; setAccount(id: string, authority: number): void; + /** + * @hidden + */ + _Get_session_id(): string; + /** + * @hidden + */ + _Fetch_sequence(): number; + /** + * @hidden + */ + _Set_session_id(val: string): void; sendData(invoke: protocol.Invoke): void; replyData(invoke: protocol.Invoke): void; } } declare namespace samchon.protocol.slave { - abstract class SlaveClient extends SlaveSystem { + interface ISlaveClient extends SlaveSystem { + connect(ip: string, port: number): void; + } + abstract class SlaveClient extends SlaveSystem implements ISlaveClient { + /** + * Default Constructor. + */ constructor(); + /** + * @inheritdoc + */ protected abstract createServerConnector(): IServerConnector; + /** + * @inheritdoc + */ connect(ip: string, port: number): void; } } declare namespace samchon.protocol.slave { - abstract class SlaveServer extends SlaveSystem implements IServer { - private server_base; + interface ISlaveServer extends SlaveSystem, IServer { + } + abstract class SlaveServer extends SlaveSystem implements ISlaveServer { + private server_base_; constructor(); protected abstract createServerBase(): IServerBase; - addClient(driver: IClientDriver): void; open(port: number): void; close(): void; + addClient(driver: IClientDriver): void; } } +declare namespace samchon.test { + function test_collection(): void; +} diff --git a/scrollreveal/scrollreveal-tests.ts b/scrollreveal/scrollreveal-tests.ts new file mode 100644 index 0000000000..f0b205763d --- /dev/null +++ b/scrollreveal/scrollreveal-tests.ts @@ -0,0 +1,74 @@ +/// + +//Tests from https://github.com/jlmakes/scrollreveal.js + +//1.2 +var sr = ScrollReveal(); +sr.reveal('.foo'); +sr.reveal('.bar'); + +//1.3 +sr = ScrollReveal().reveal('.foo, .bar'); + +//2.1 +sr = ScrollReveal({ reset: true }); +sr.reveal('.foo', { duration: 200 }); + +//3.1 +sr = ScrollReveal({ duration: 2000 }); +sr.reveal('.box', 50); + +sr = ScrollReveal(); +sr.reveal('.box', { duration: 2000 }, 50); + +//3.2 +var fooReveal = { + delay : 200, + distance : '90px', + easing : 'ease-in-out', + rotate : { z: 10 }, + scale : 1.1 +}; + +sr = ScrollReveal(); +sr.reveal('.foo', fooReveal); +sr.reveal('#chocolate', { delay: 500, scale: 0.9 }); + +//3.3 +sr.reveal(document.getElementById('foo')); +sr.reveal(document.querySelectorAll('.bar')); + +//3.4 +sr = ScrollReveal(); +var fooContainer = document.getElementById('fooContainer'); +sr.reveal('.foo', { container: fooContainer }); +sr.reveal('.bar', { container: '#barContainer' }); + +//3.5 + +fooContainer = document.getElementById('fooContainer'); + +sr = ScrollReveal(); +sr.reveal('.foo', { container: fooContainer }); +var xmlhttp = new XMLHttpRequest(); +xmlhttp.onreadystatechange = function() { + if (xmlhttp.readyState == XMLHttpRequest.DONE) { + if (xmlhttp.status == 200) { + + // Turn our response into HTML... + var content = document.createElement('div'); + content.innerHTML = xmlhttp.responseText; + + // Add each element to the DOM... + for (var i = 0; i < content.childNodes.length; i++) { + fooContainer.appendChild(content.childNodes[ i ]); + }; + + // Finally! + sr.sync(); + } + } +} + +xmlhttp.open('GET', 'ajax.html', true); +xmlhttp.send(); \ No newline at end of file diff --git a/scrollreveal/scrollreveal.d.ts b/scrollreveal/scrollreveal.d.ts new file mode 100644 index 0000000000..d1478c8243 --- /dev/null +++ b/scrollreveal/scrollreveal.d.ts @@ -0,0 +1,68 @@ +// Type definitions for ScrollReveal +// Project: https://github.com/jlmakes/scrollreveal.js +// Definitions by: David Pires +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace scrollReveal { + interface ScrollRevealRotateObject { + x?: number; + y?: number; + z?: number; + } + + interface ScrollRevealPositionObject { + top?: number; + right?: number; + bottom?: number; + left?: number; + } + + interface ScrollRevealObjectOptions { + origin ? : string; + distance ? : string; + duration ? : number; + delay ? : number; + rotate ? : ScrollRevealRotateObject; + opacity ? : number; + scale ? : number; + easing ? : string; + container ? : any; + mobile ? : boolean; + reset ? : boolean; + useDelay ? : string; + viewFactor ? : number; + viewOffset ? : ScrollRevealPositionObject; + beforeReveal ? (domEl: HTMLElement): void; + afterReveal ? (domEl: HTMLElement): void; + beforeReset ? (domEl: HTMLElement): void; + afterReset ? (domEl: HTMLElement): void; + beforeReveal ? (domEl: NodeListOf): void; + afterReveal ? (domEl: NodeListOf): void; + beforeReset ? (domEl: NodeListOf): void; + afterReset ? (domEl: NodeListOf): void; + } + + + interface ScrollRevealObject { + (): ScrollRevealObject; + (options: ScrollRevealObjectOptions): ScrollRevealObject; + reveal(selector: string): ScrollRevealObject; + reveal(selector: string, interval: number): ScrollRevealObject; + reveal(selector: string, options: ScrollRevealObjectOptions): ScrollRevealObject; + reveal(selector: string, options: ScrollRevealObjectOptions, interval: number): ScrollRevealObject; + + reveal(selector: HTMLElement): ScrollRevealObject; + reveal(selector: HTMLElement, interval: number): ScrollRevealObject; + reveal(selector: HTMLElement, options: ScrollRevealObjectOptions): ScrollRevealObject; + reveal(selector: HTMLElement, options: ScrollRevealObjectOptions, interval: number): ScrollRevealObject; + + reveal(selector: NodeListOf): ScrollRevealObject; + reveal(selector: NodeListOf, interval: number): ScrollRevealObject; + reveal(selector: NodeListOf, options: ScrollRevealObjectOptions): ScrollRevealObject; + reveal(selector: NodeListOf, options: ScrollRevealObjectOptions, interval: number): ScrollRevealObject; + + sync(): void; + } +} + +declare var ScrollReveal: scrollReveal.ScrollRevealObject; \ No newline at end of file diff --git a/selenium-webdriver/selenium-webdriver-2.53.1-tests.ts b/selenium-webdriver/selenium-webdriver-2.53.1-tests.ts new file mode 100644 index 0000000000..77c68bb58d --- /dev/null +++ b/selenium-webdriver/selenium-webdriver-2.53.1-tests.ts @@ -0,0 +1,1144 @@ +/// + +function TestChromeDriver() { + var driver: chrome.Driver = new chrome.Driver(); + driver = new chrome.Driver(webdriver.Capabilities.chrome()); + driver = new chrome.Driver(webdriver.Capabilities.chrome(), new remote.DriverService('executable', new chrome.Options()), new webdriver.promise.ControlFlow()); + + var baseDriver: webdriver.WebDriver = driver; +} + +function TestChromeOptions() { + var options: chrome.Options = new chrome.Options(); + options = chrome.Options.fromCapabilities(webdriver.Capabilities.chrome()); + + options = options.addArguments("a", "b", "c"); + options = options.addExtensions("a", "b", "c"); + options = options.excludeSwitches("a", "b", "c"); + options = options.detachDriver(true); + options = options.setChromeBinaryPath("path"); + options = options.setChromeLogFile("logfile"); + options = options.setLocalState("state"); + options = options.androidActivity("com.example.Activity"); + options = options.androidDeviceSerial("emulator-5554"); + options = options.androidChrome(); + options = options.androidPackage("com.android.chrome"); + options = options.androidProcess("com.android.chrome"); + options = options.androidUseRunningApp(true); + options = options.setLoggingPrefs(new webdriver.logging.Preferences()); + options = options.setPerfLoggingPrefs({enableNetwork: true, enablePage: true, enableTimeline: true, tracingCategories: "category", bufferUsageReportingInterval: 1000}); + options = options.setProxy({ proxyType: "proxyType" }); + options = options.setUserPreferences("preferences"); + var capabilities: webdriver.Capabilities = options.toCapabilities(); + capabilities = options.toCapabilities(webdriver.Capabilities.chrome()); +} + +function TestServiceBuilder() { + var builder: chrome.ServiceBuilder = new chrome.ServiceBuilder(); + builder = new chrome.ServiceBuilder("exe"); + + var anything: any = builder.build(); + builder = builder.usingPort(8080); + builder = builder.setAdbPort(5037); + builder = builder.loggingTo("path"); + builder = builder.enableVerboseLogging(); + builder = builder.setNumHttpThreads(5); + builder = builder.setUrlBasePath("path"); + builder = builder.setStdio("config"); + builder = builder.setStdio(["A", "B"]); + builder = builder.withEnvironment({ "A": "a", "B": "b" }); +} + +function TestChromeModule() { + var service: any = chrome.getDefaultService(); + chrome.setDefaultService(new remote.DriverService('executable', new chrome.Options())); +} + +function TestBinary() { + var binary: firefox.Binary = new firefox.Binary(); + binary = new firefox.Binary("exe"); + + binary.addArguments("A", "B", "C"); + var promise: webdriver.promise.Promise = binary.kill(); + binary.launch("profile").then(function (result: any) { }); +} + +function TestFirefoxDriver() { + var driver: firefox.Driver = new firefox.Driver(); + driver = new firefox.Driver(webdriver.Capabilities.firefox()); + driver = new firefox.Driver(webdriver.Capabilities.firefox(), new webdriver.promise.ControlFlow()); + + var baseDriver: webdriver.WebDriver = driver; +} + +function TestFirefoxOptions() { + var options: firefox.Options = new firefox.Options(); + + options = options.setBinary("binary"); + options = options.setBinary(new firefox.Binary()); + options = options.setLoggingPreferences(new webdriver.logging.Preferences()); + options = options.setProfile("profile"); + options = options.setProfile(new firefox.Profile()); + options = options.setProxy({ proxyType: "proxy" }); + var capabilities: webdriver.Capabilities = options.toCapabilities(); +} + +function TestFirefoxProfile() { + var profile: firefox.Profile = new firefox.Profile(); + profile = new firefox.Profile("dir"); + + var bool: boolean = profile.acceptUntrustedCerts(); + profile.addExtension("ext"); + bool = profile.assumeUntrustedCertIssuer(); + profile.encode().then(function (prof: string) { }); + var num: number = profile.getPort(); + var anything: any = profile.getPreference("key"); + bool = profile.nativeEventsEnabled(); + profile.setAcceptUntrustedCerts(true); + profile.setAssumeUntrustedCertIssuer(true); + profile.setNativeEventsEnabled(true); + profile.setPort(8080); + profile.setPreference("key", "value"); + profile.setPreference("key", 5); + profile.setPreference("key", true); + var stringPromise: webdriver.promise.Promise = profile.writeToDisk(); + stringPromise = profile.writeToDisk(true); +} + +function TestExecutors() { + var exec: webdriver.Executor = executors.createExecutor("url"); + var promise: webdriver.promise.Promise; + exec = executors.createExecutor(promise); +} + +function TestBuilder() { + var builder: webdriver.Builder = new webdriver.Builder(); + + var driver: webdriver.WebDriver = builder.build(); + builder = builder.forBrowser('name'); + builder = builder.forBrowser('name', 'version'); + builder = builder.forBrowser('name', 'version', 'platform'); + + var cap: webdriver.Capabilities = builder.getCapabilities(); + var str:string = builder.getServerUrl(); + + builder = builder.setAlertBehavior('behavior'); + builder = builder.setChromeOptions(new chrome.Options()); + builder = builder.setControlFlow(new webdriver.promise.ControlFlow()); + builder = builder.setEnableNativeEvents(true); + builder = builder.setFirefoxOptions(new firefox.Options()); + builder = builder.setLoggingPrefs(new webdriver.logging.Preferences()); + builder = builder.setLoggingPrefs({ "key": "value" }); + builder = builder.setProxy({ proxyType: 'type' }); + builder = builder.setScrollBehavior(1); + builder = builder.usingServer('http://someserver'); + builder = builder.withCapabilities(new webdriver.Capabilities()); + builder = builder.withCapabilities({ something: true }); +} + +function TestActionSequence() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var sequence: webdriver.ActionSequence = new webdriver.ActionSequence(driver); + var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); + var promise: webdriver.promise.Promise; + element = new webdriver.WebElement(driver, promise); + + // Click + sequence = sequence.click(); + sequence = sequence.click(webdriver.Button.LEFT); + sequence = sequence.click(element); + sequence = sequence.click(element, webdriver.Button.LEFT); + + // DoubleClick + sequence = sequence.doubleClick(); + sequence = sequence.doubleClick(webdriver.Button.LEFT); + sequence = sequence.doubleClick(element); + sequence = sequence.doubleClick(element, webdriver.Button.LEFT); + + // DragAndDrop + sequence = sequence.dragAndDrop(element, element); + sequence = sequence.dragAndDrop(element, {x: 1, y: 2}); + + // KeyDown + sequence = sequence.keyDown(webdriver.Key.ADD); + + // KeyUp + sequence = sequence.keyUp(webdriver.Key.ADD); + + // MouseDown + sequence = sequence.mouseDown(); + sequence = sequence.mouseDown(webdriver.Button.LEFT); + sequence = sequence.mouseDown(element); + sequence = sequence.mouseDown(element, webdriver.Button.LEFT); + + // MouseMove + sequence = sequence.mouseMove(element); + sequence = sequence.mouseMove({x: 1, y: 1}); + sequence = sequence.mouseMove(element, {x: 1, y: 2}); + + // MouseUp + sequence = sequence.mouseUp(); + sequence = sequence.mouseUp(webdriver.Button.LEFT); + sequence = sequence.mouseUp(element); + sequence = sequence.mouseUp(element, webdriver.Button.LEFT); + + // SendKeys + sequence = sequence.sendKeys("A", "B", "C"); + + sequence.perform().then(function () { }); +} + +function TestTouchSequence() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); + + var sequence: webdriver.TouchSequence = new webdriver.TouchSequence(driver); + + sequence = sequence.tap(element); + sequence = sequence.doubleTap(element); + sequence = sequence.longPress(element); + sequence = sequence.tapAndHold({ x: 100, y: 100 }); + sequence = sequence.move({ x: 100, y: 100 }); + sequence = sequence.release({ x: 100, y: 100 }); + sequence = sequence.scroll({ x: 100, y: 100 }); + sequence = sequence.scrollFromElement(element, { x: 100, y: 100 }); + sequence = sequence.flick({ xspeed: 100, yspeed: 100 }); + sequence = sequence.flickElement(element, { x: 100, y: 100 }, 100); + + sequence.perform().then(function () { }); +} + +function TestAlert() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var alert: webdriver.Alert = driver.switchTo().alert(); + + alert.accept().then(function () { }); + alert.dismiss().then(function () { }); + alert.getText().then(function (text: string) { }); + alert.sendKeys("ABC").then(function () { }); +} + +function TestBrowser() { + var browser: string; + + browser = webdriver.Browser.ANDROID; + browser = webdriver.Browser.CHROME; + browser = webdriver.Browser.FIREFOX; + browser = webdriver.Browser.HTMLUNIT; + browser = webdriver.Browser.INTERNET_EXPLORER; + browser = webdriver.Browser.IPAD; + browser = webdriver.Browser.IPHONE; + browser = webdriver.Browser.OPERA; + browser = webdriver.Browser.PHANTOM_JS; + browser = webdriver.Browser.SAFARI; +} + +function TestButton() { + var button: number; + + button = webdriver.Button.LEFT; + button = webdriver.Button.MIDDLE; + button = webdriver.Button.RIGHT; +} + +function TestCapabilities() { + var capabilities: webdriver.Capabilities = new webdriver.Capabilities(); + capabilities = new webdriver.Capabilities(webdriver.Capabilities.chrome()); + var objCapabilities: any = {}; + objCapabilities[webdriver.Capability.BROWSER_NAME] = webdriver.Browser.PHANTOM_JS; + capabilities = new webdriver.Capabilities(objCapabilities); + + var anything: any = capabilities.get(webdriver.Capability.SECURE_SSL); + var check: boolean = capabilities.has(webdriver.Capability.SECURE_SSL); + capabilities = capabilities.merge(capabilities); + capabilities = capabilities.merge(objCapabilities); + capabilities = capabilities.set(webdriver.Capability.VERSION, { abc: 'def' }); + capabilities = capabilities.set(webdriver.Capability.VERSION, null); + capabilities = capabilities.setLoggingPrefs(new webdriver.logging.Preferences()); + capabilities = capabilities.setLoggingPrefs({ "key": "value" }); + capabilities = capabilities.setProxy({ proxyType: 'Type' }); + capabilities = capabilities.setEnableNativeEvents(true); + capabilities = capabilities.setScrollBehavior(1); + capabilities = capabilities.setAlertBehavior('accept'); + + anything = capabilities.toJSON(); + + capabilities = webdriver.Capabilities.android(); + capabilities = webdriver.Capabilities.chrome(); + capabilities = webdriver.Capabilities.firefox(); + capabilities = webdriver.Capabilities.htmlunit(); + capabilities = webdriver.Capabilities.htmlunitwithjs(); + capabilities = webdriver.Capabilities.ie(); + capabilities = webdriver.Capabilities.ipad(); + capabilities = webdriver.Capabilities.iphone(); + capabilities = webdriver.Capabilities.opera(); + capabilities = webdriver.Capabilities.phantomjs(); + capabilities = webdriver.Capabilities.safari(); +} + +function TestCapability() { + var capability: string; + + capability = webdriver.Capability.ACCEPT_SSL_CERTS; + capability = webdriver.Capability.BROWSER_NAME; + capability = webdriver.Capability.ELEMENT_SCROLL_BEHAVIOR; + capability = webdriver.Capability.HANDLES_ALERTS; + capability = webdriver.Capability.LOGGING_PREFS; + capability = webdriver.Capability.NATIVE_EVENTS; + capability = webdriver.Capability.PLATFORM; + capability = webdriver.Capability.PROXY; + capability = webdriver.Capability.ROTATABLE; + capability = webdriver.Capability.SECURE_SSL; + capability = webdriver.Capability.SUPPORTS_APPLICATION_CACHE; + capability = webdriver.Capability.SUPPORTS_CSS_SELECTORS; + capability = webdriver.Capability.SUPPORTS_JAVASCRIPT; + capability = webdriver.Capability.SUPPORTS_LOCATION_CONTEXT; + capability = webdriver.Capability.TAKES_SCREENSHOT; + capability = webdriver.Capability.UNEXPECTED_ALERT_BEHAVIOR; + capability = webdriver.Capability.VERSION; +} + +function TestCommand() { + var command: webdriver.Command = new webdriver.Command(webdriver.CommandName.ADD_COOKIE); + + var name: string = command.getName(); + var param: any = command.getParameter("param"); + + var params: any = command.getParameters(); + + command = command.setParameter("param", 123); + command = command.setParameters({ param: 123 }); +} + +function TestDeferredExecutor() { + var promise: webdriver.promise.Promise; + var executor: webdriver.DeferredExecutor = new webdriver.DeferredExecutor(promise); +} + +function TestCommandName() { + var command: string; + + command = webdriver.CommandName.ACCEPT_ALERT; + command = webdriver.CommandName.ADD_COOKIE; + command = webdriver.CommandName.CLEAR_APP_CACHE; + command = webdriver.CommandName.CLEAR_ELEMENT; + command = webdriver.CommandName.CLEAR_LOCAL_STORAGE; + command = webdriver.CommandName.CLEAR_SESSION_STORAGE; + command = webdriver.CommandName.CLICK; + command = webdriver.CommandName.CLICK_ELEMENT; + command = webdriver.CommandName.CLOSE; + command = webdriver.CommandName.DELETE_ALL_COOKIES; + command = webdriver.CommandName.DELETE_COOKIE; + command = webdriver.CommandName.DESCRIBE_SESSION; + command = webdriver.CommandName.DISMISS_ALERT; + command = webdriver.CommandName.DOUBLE_CLICK; + command = webdriver.CommandName.ELEMENT_EQUALS; + command = webdriver.CommandName.EXECUTE_ASYNC_SCRIPT; + command = webdriver.CommandName.EXECUTE_SCRIPT; + command = webdriver.CommandName.EXECUTE_SQL; + command = webdriver.CommandName.FIND_CHILD_ELEMENT; + command = webdriver.CommandName.FIND_CHILD_ELEMENTS; + command = webdriver.CommandName.FIND_ELEMENT; + command = webdriver.CommandName.FIND_ELEMENTS; + command = webdriver.CommandName.GET; + command = webdriver.CommandName.GET_ACTIVE_ELEMENT; + command = webdriver.CommandName.GET_ALERT_TEXT; + command = webdriver.CommandName.GET_ALL_COOKIES; + command = webdriver.CommandName.GET_APP_CACHE; + command = webdriver.CommandName.GET_APP_CACHE_STATUS; + command = webdriver.CommandName.GET_AVAILABLE_LOG_TYPES; + command = webdriver.CommandName.GET_COOKIE; + command = webdriver.CommandName.GET_CURRENT_URL; + command = webdriver.CommandName.GET_CURRENT_WINDOW_HANDLE; + command = webdriver.CommandName.GET_ELEMENT_ATTRIBUTE; + command = webdriver.CommandName.GET_ELEMENT_LOCATION; + command = webdriver.CommandName.GET_ELEMENT_LOCATION_IN_VIEW; + command = webdriver.CommandName.GET_ELEMENT_SIZE; + command = webdriver.CommandName.GET_ELEMENT_TAG_NAME; + command = webdriver.CommandName.GET_ELEMENT_TEXT; + command = webdriver.CommandName.GET_ELEMENT_VALUE_OF_CSS_PROPERTY; + command = webdriver.CommandName.GET_LOCAL_STORAGE_ITEM; + command = webdriver.CommandName.GET_LOCAL_STORAGE_KEYS; + command = webdriver.CommandName.GET_LOCAL_STORAGE_SIZE; + command = webdriver.CommandName.GET_LOCATION; + command = webdriver.CommandName.GET_LOG; + command = webdriver.CommandName.GET_PAGE_SOURCE; + command = webdriver.CommandName.GET_SCREEN_ORIENTATION; + command = webdriver.CommandName.GET_SERVER_STATUS; + command = webdriver.CommandName.GET_SESSION_LOGS; + command = webdriver.CommandName.GET_SESSION_STORAGE_ITEM; + command = webdriver.CommandName.GET_SESSION_STORAGE_KEYS; + command = webdriver.CommandName.GET_SESSION_STORAGE_SIZE; + command = webdriver.CommandName.GET_SESSIONS; + command = webdriver.CommandName.GET_TITLE; + command = webdriver.CommandName.GET_WINDOW_HANDLES; + command = webdriver.CommandName.GET_WINDOW_POSITION; + command = webdriver.CommandName.GET_WINDOW_SIZE; + command = webdriver.CommandName.GO_BACK; + command = webdriver.CommandName.GO_FORWARD; + command = webdriver.CommandName.IMPLICITLY_WAIT; + command = webdriver.CommandName.IS_BROWSER_ONLINE; + command = webdriver.CommandName.IS_ELEMENT_DISPLAYED; + command = webdriver.CommandName.IS_ELEMENT_ENABLED; + command = webdriver.CommandName.IS_ELEMENT_SELECTED; + command = webdriver.CommandName.MAXIMIZE_WINDOW; + command = webdriver.CommandName.MOUSE_DOWN; + command = webdriver.CommandName.MOUSE_UP; + command = webdriver.CommandName.MOVE_TO; + command = webdriver.CommandName.NEW_SESSION; + command = webdriver.CommandName.QUIT; + command = webdriver.CommandName.REFRESH; + command = webdriver.CommandName.REMOVE_LOCAL_STORAGE_ITEM; + command = webdriver.CommandName.REMOVE_SESSION_STORAGE_ITEM; + command = webdriver.CommandName.SCREENSHOT; + command = webdriver.CommandName.SEND_KEYS_TO_ACTIVE_ELEMENT; + command = webdriver.CommandName.SEND_KEYS_TO_ELEMENT; + command = webdriver.CommandName.SET_ALERT_TEXT; + command = webdriver.CommandName.SET_BROWSER_ONLINE; + command = webdriver.CommandName.SET_LOCAL_STORAGE_ITEM; + command = webdriver.CommandName.SET_LOCATION; + command = webdriver.CommandName.SET_SCREEN_ORIENTATION; + command = webdriver.CommandName.SET_SCRIPT_TIMEOUT; + command = webdriver.CommandName.SET_SESSION_STORAGE_ITEM; + command = webdriver.CommandName.SET_TIMEOUT; + command = webdriver.CommandName.SET_WINDOW_POSITION; + command = webdriver.CommandName.SET_WINDOW_SIZE; + command = webdriver.CommandName.SUBMIT_ELEMENT; + command = webdriver.CommandName.SWITCH_TO_FRAME; + command = webdriver.CommandName.SWITCH_TO_WINDOW; + command = webdriver.CommandName.TOUCH_DOUBLE_TAP; + command = webdriver.CommandName.TOUCH_DOWN; + command = webdriver.CommandName.TOUCH_FLICK; + command = webdriver.CommandName.TOUCH_LONG_PRESS; + command = webdriver.CommandName.TOUCH_MOVE; + command = webdriver.CommandName.TOUCH_SCROLL; + command = webdriver.CommandName.TOUCH_SINGLE_TAP; + command = webdriver.CommandName.TOUCH_UP; +} + +function TestEventEmitter() { + var emitter: webdriver.EventEmitter = new webdriver.EventEmitter(); + + var callback = function (a: number, b: number, c: number) {}; + + emitter = emitter.addListener('ABC', callback); + emitter = emitter.addListener('ABC', callback, this); + + emitter.emit('ABC', 1, 2, 3); + + var listeners = emitter.listeners('ABC'); + if (listeners[0].oneshot) { + listeners[0].fn.apply(listeners[0].scope); + } + var length: number = listeners.length; + var listenerInfo = listeners[0]; + if (listenerInfo.oneshot) { + listenerInfo.fn.apply(listenerInfo.scope, [1, 2, 3]); + } + + emitter = emitter.on('ABC', callback); + emitter = emitter.on('ABC', callback, this); + + emitter = emitter.once('ABC', callback); + emitter = emitter.once('ABC', callback, this); + + emitter = emitter.removeListener('ABC', callback); + + emitter.removeAllListeners('ABC'); + emitter.removeAllListeners(); +} + +function TestKey() { + var key: webdriver.Key; + + key = webdriver.Key.ADD; + key = webdriver.Key.ALT; + key = webdriver.Key.ARROW_DOWN; + key = webdriver.Key.ARROW_LEFT; + key = webdriver.Key.ARROW_RIGHT; + key = webdriver.Key.ARROW_UP; + key = webdriver.Key.BACK_SPACE; + key = webdriver.Key.CANCEL; + key = webdriver.Key.CLEAR; + key = webdriver.Key.COMMAND; + key = webdriver.Key.CONTROL; + key = webdriver.Key.DECIMAL; + key = webdriver.Key.DELETE; + key = webdriver.Key.DIVIDE; + key = webdriver.Key.DOWN; + key = webdriver.Key.END; + key = webdriver.Key.ENTER; + key = webdriver.Key.EQUALS; + key = webdriver.Key.ESCAPE; + key = webdriver.Key.F1; + key = webdriver.Key.F2; + key = webdriver.Key.F3; + key = webdriver.Key.F4; + key = webdriver.Key.F5; + key = webdriver.Key.F6; + key = webdriver.Key.F7; + key = webdriver.Key.F8; + key = webdriver.Key.F9; + key = webdriver.Key.F10; + key = webdriver.Key.F11; + key = webdriver.Key.F12; + key = webdriver.Key.HELP; + key = webdriver.Key.HOME; + key = webdriver.Key.INSERT; + key = webdriver.Key.LEFT; + key = webdriver.Key.META; + key = webdriver.Key.MULTIPLY; + key = webdriver.Key.NULL; + key = webdriver.Key.NUMPAD0; + key = webdriver.Key.NUMPAD1; + key = webdriver.Key.NUMPAD2; + key = webdriver.Key.NUMPAD3; + key = webdriver.Key.NUMPAD4; + key = webdriver.Key.NUMPAD5; + key = webdriver.Key.NUMPAD6; + key = webdriver.Key.NUMPAD7; + key = webdriver.Key.NUMPAD8; + key = webdriver.Key.NUMPAD9; + key = webdriver.Key.PAGE_DOWN; + key = webdriver.Key.PAGE_UP; + key = webdriver.Key.PAUSE; + key = webdriver.Key.RETURN; + key = webdriver.Key.RIGHT; + key = webdriver.Key.SEMICOLON; + key = webdriver.Key.SEPARATOR; + key = webdriver.Key.SHIFT; + key = webdriver.Key.SPACE; + key = webdriver.Key.SUBTRACT; + key = webdriver.Key.TAB; + key = webdriver.Key.UP; +} + +function TestBy() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var locator: webdriver.By = new webdriver.By('class name', 'class'); + + var str: string = locator.toString(); + + locator = webdriver.By.className('class'); + locator = webdriver.By.css('css'); + locator = webdriver.By.id('id'); + locator = webdriver.By.linkText('link'); + locator = webdriver.By.name('name'); + locator = webdriver.By.partialLinkText('text'); + locator = webdriver.By.tagName('tag'); + locator = webdriver.By.xpath('xpath'); + + // Can import "By" without import declarations + var By = webdriver.By; + + var locatorHash: webdriver.ByHash; + locatorHash = { className: 'class' }; + locatorHash = { css: 'css' }; + locatorHash = { id: 'id' }; + locatorHash = { linkText: 'link' }; + locatorHash = { name: 'name' }; + locatorHash = { partialLinkText: 'text' }; + locatorHash = { tagName: 'tag' }; + locatorHash = { xpath: 'xpath' }; + + webdriver.By.js('script', 1, 2, 3)(driver).then(function (abc: number) { }); +} + +function TestSession() { + var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); + var capabilitiesObj: any = {}; + capabilitiesObj[webdriver.Capability.BROWSER_NAME] = webdriver.Browser.ANDROID; + capabilitiesObj[webdriver.Capability.PLATFORM] = 'ANDROID'; + session = new webdriver.Session('ABC', capabilitiesObj); + + var capabilities: webdriver.Capabilities = session.getCapabilities(); + var capability: any = session.getCapability(webdriver.Capability.BROWSER_NAME); + var id: string = session.getId(); + var data: string = session.toJSON(); +} + +function TestUnhandledAlertError() { + var someFunc = function (error: webdriver.UnhandledAlertError) { + var baseError: Error = error; + var str: string = error.getAlertText(); + str = error.toString(); + } +} + +function TestWebDriverFileDetector() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); + + fileDetector.handleFile(driver, 'path/to/file').then(function(path: string) {}); +} + +function TestWebDriverLogs() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var logs: webdriver.Logs = new webdriver.Logs(driver); + + logs.get(webdriver.logging.Type.BROWSER).then(function (entries: webdriver.logging.Entry[]) { });; + logs.getAvailableLogTypes().then(function (types: string[]) { }); +} + +function TestWebDriverNavigation() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var navigation: webdriver.Navigation = new webdriver.Navigation(driver); + + navigation.back().then(function () { }); + navigation.forward().then(function () { }); + navigation.refresh().then(function () { }); + navigation.to('http://google.com').then(function () { }); +} + +function TestWebDriverOptions() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var options: webdriver.Options = new webdriver.Options(driver); + var promise: webdriver.promise.Promise; + + // Add Cookie + promise = options.addCookie('name', 'value'); + promise = options.addCookie('name', 'value', 'path'); + promise = options.addCookie('name', 'value', 'path', 'domain'); + promise = options.addCookie('name', 'value', 'path', 'domain', true); + promise = options.addCookie('name', 'value', 'path', 'domain', true, 123); + promise = options.addCookie('name', 'value', 'path', 'domain', true, Date.now()); + + promise = options.deleteAllCookies(); + promise = options.deleteCookie('name'); + options.getCookie('name').then(function (cookies: webdriver.IWebDriverOptionsCookie) { }); + options.getCookies().then(function (cookies: webdriver.IWebDriverOptionsCookie[]) { }); + + var logs: webdriver.Logs = options.logs(); + var timeouts: webdriver.Timeouts = options.timeouts(); + var window: webdriver.Window = options.window(); +} + +function TestWebDriverTargetLocator() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var locator: webdriver.TargetLocator = new webdriver.TargetLocator(driver); + var promise: webdriver.promise.Promise; + + var element: webdriver.WebElement = locator.activeElement(); + var alert: webdriver.Alert = locator.alert(); + promise = locator.defaultContent(); + promise = locator.frame(1); + promise = locator.window('nameOrHandle'); +} + +function TestWebDriverTimeouts() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var timeouts: webdriver.Timeouts = new webdriver.Timeouts(driver); + var promise: webdriver.promise.Promise; + + promise = timeouts.implicitlyWait(123); + promise = timeouts.pageLoadTimeout(123); + promise = timeouts.setScriptTimeout(123); +} + +function TestWebDriverWindow() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var window: webdriver.Window = new webdriver.Window(driver); + var locationPromise: webdriver.promise.Promise; + var sizePromise: webdriver.promise.Promise; + var voidPromise: webdriver.promise.Promise; + + locationPromise = window.getPosition(); + sizePromise = window.getSize(); + voidPromise = window.maximize(); + voidPromise = window.setPosition(12, 34); + voidPromise = window.setSize(12, 34); +} + +function TestWebDriver() { + var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); + var sessionPromise: webdriver.promise.Promise; + var executor: webdriver.Executor = executors.createExecutor("http://someserver"); + var flow: webdriver.promise.ControlFlow = new webdriver.promise.ControlFlow(); + var driver: webdriver.WebDriver = new webdriver.WebDriver(session, executor); + driver = new webdriver.WebDriver(session, executor, flow); + driver = new webdriver.WebDriver(sessionPromise, executor); + driver = new webdriver.WebDriver(sessionPromise, executor, flow); + + var voidPromise: webdriver.promise.Promise; + var stringPromise: webdriver.promise.Promise; + var booleanPromise: webdriver.promise.Promise; + + var actions: webdriver.ActionSequence = driver.actions(); + var touchActions: webdriver.TouchSequence = driver.touchActions(); + + // call + stringPromise = driver.call(function(){ return 'value'; }); + stringPromise = driver.call(function(){ return stringPromise; }); + stringPromise = driver.call(function(){ var d: any = this; return 'value'; }, driver); + stringPromise = driver.call(function(a: number){ return 'value'; }, driver, 1); + + voidPromise = driver.close(); + flow = driver.controlFlow(); + + // executeAsyncScript + stringPromise = driver.executeAsyncScript('function(){}'); + stringPromise = driver.executeAsyncScript('function(){}', 1, 2, 3); + stringPromise = driver.executeAsyncScript(function(){}); + stringPromise = driver.executeAsyncScript(function(a: number){}, 1); + + // executeScript + stringPromise = driver.executeScript('function(){}'); + stringPromise = driver.executeScript('function(){}', 1, 2, 3); + stringPromise = driver.executeScript(function(){}); + stringPromise = driver.executeScript(function(a: number){}, 1); + + // findElement + var element: webdriver.WebElement; + element = driver.findElement(webdriver.By.id('ABC')); + element = driver.findElement(webdriver.By.js('function(){}')); + + // findElements + driver.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); + driver.findElements(webdriver.By.js('function(){}')).then(function (elements: webdriver.WebElement[]) { }); + + voidPromise = driver.get('http://www.google.com'); + driver.getAllWindowHandles().then(function (handles: string[]) { }); + driver.getCapabilities().then(function (caps: webdriver.Capabilities) { }); + stringPromise = driver.getCurrentUrl(); + stringPromise = driver.getPageSource() + driver.getSession().then(function (session: webdriver.Session) { });; + stringPromise = driver.getTitle(); + stringPromise = driver.getWindowHandle(); + + booleanPromise = driver.isElementPresent(webdriver.By.className('ABC')); + booleanPromise = driver.isElementPresent(webdriver.By.js('function(){}')); + + var options: webdriver.Options = driver.manage(); + var navigation: webdriver.Navigation = driver.navigate(); + var locator: webdriver.TargetLocator = driver.switchTo(); + + var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); + driver.setFileDetector(fileDetector); + + voidPromise = driver.quit(); + voidPromise = driver.schedule(new webdriver.Command(webdriver.CommandName.CLICK), 'ABC'); + voidPromise = driver.sleep(123); + stringPromise = driver.takeScreenshot(); + + var booleanCondition: webdriver.until.Condition; + booleanPromise = driver.wait(booleanPromise); + booleanPromise = driver.wait(booleanCondition); + booleanPromise = driver.wait(function(driver: webdriver.WebDriver) { return true; }); + booleanPromise = driver.wait(booleanPromise, 123); + booleanPromise = driver.wait(booleanPromise, 123, 'Message'); + + driver = webdriver.WebDriver.attachToSession(executor, 'ABC'); + driver = webdriver.WebDriver.createSession(executor, webdriver.Capabilities.android()); +} + +function TestSerializable() { + var serializable: webdriver.Serializable; + var serial: string|webdriver.promise.IThenable = serializable.serialize(); +} + +function TestWebElement() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var promise: webdriver.promise.Promise; + var element: webdriver.WebElement; + + element = new webdriver.WebElement(driver, 'elementId'); + element = new webdriver.WebElement(driver, promise); + + var voidPromise: webdriver.promise.Promise; + var stringPromise: webdriver.promise.Promise; + var booleanPromise: webdriver.promise.Promise; + + voidPromise = element.clear(); + voidPromise = element.click(); + + element = element.findElement(webdriver.By.id('ABC')); + element.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); + booleanPromise = element.isElementPresent(webdriver.By.className('ABC')); + + stringPromise = element.getAttribute('class'); + stringPromise = element.getCssValue('display'); + driver = element.getDriver(); + stringPromise = element.getInnerHtml(); + element.getLocation().then(function (location: webdriver.ILocation) { }); + stringPromise = element.getOuterHtml(); + element.getSize().then(function (size: webdriver.ISize) { }); + stringPromise = element.getTagName(); + stringPromise = element.getText(); + booleanPromise = element.isDisplayed(); + booleanPromise = element.isEnabled(); + booleanPromise = element.isSelected(); + voidPromise = element.sendKeys('A', 'B', 'C'); + voidPromise = element.sendKeys(stringPromise, stringPromise, stringPromise); + voidPromise = element.submit(); + element.getId().then(function (id: string) { }); + element.getRawId().then(function (id: string) { }); + element.serialize().then(function (id: webdriver.IWebElementId) { }); + + booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, 'elementId')); +} + +function TestWebElementPromise() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var elementPromise: webdriver.WebElementPromise = driver.findElement(webdriver.By.id('id')); + + elementPromise.cancel(); + elementPromise.cancel('reason'); + + var bool: boolean = elementPromise.isPending(); + + elementPromise.then(); + elementPromise.then(function (element: webdriver.WebElement) { }); + elementPromise.then(function (element: webdriver.WebElement) { }, function (error: any) { }); + elementPromise.then(function (element: webdriver.WebElement) { return "foo"; }, function (error: any) { }).then(function (result: string) { }); + + elementPromise.thenCatch(function (error: any) { }).then(function (value: any) { }); + + elementPromise.thenFinally(function () { }); +} + +function TestLogging() { + var preferences: webdriver.logging.Preferences = new webdriver.logging.Preferences(); + preferences.setLevel(webdriver.logging.Type.BROWSER, webdriver.logging.Level.ALL); + var prefs: any = preferences.toJSON(); + + var level: webdriver.logging.Level = webdriver.logging.getLevel('OFF'); + level = webdriver.logging.getLevel(1); + + level = webdriver.logging.Level.ALL; + level = webdriver.logging.Level.DEBUG; + level = webdriver.logging.Level.INFO; + level = webdriver.logging.Level.OFF; + level = webdriver.logging.Level.SEVERE; + level = webdriver.logging.Level.WARNING; + + var name: string = level.name(); + var value: number = level.value(); + + var type: webdriver.logging.Type; + type = webdriver.logging.Type.BROWSER; + type = webdriver.logging.Type.CLIENT; + type = webdriver.logging.Type.DRIVER; + type = webdriver.logging.Type.PERFORMANCE; + type = webdriver.logging.Type.SERVER; +} + +function TestLoggingEntry() { + var entry: webdriver.logging.Entry; + + entry = new webdriver.logging.Entry(webdriver.logging.Level.ALL, 'ABC'); + entry = new webdriver.logging.Entry('ALL', 'ABC'); + entry = new webdriver.logging.Entry(webdriver.logging.Level.ALL, 'ABC', 123); + entry = new webdriver.logging.Entry('ALL', 'ABC', 123); + entry = new webdriver.logging.Entry(webdriver.logging.Level.ALL, 'ABC', 123, webdriver.logging.Type.BROWSER); + entry = new webdriver.logging.Entry('ALL', 'ABC', 123, webdriver.logging.Type.BROWSER); + + var entryObj: any = entry.toJSON(); + + var message: string = entry.message; + var timestamp: number = entry.timestamp; + var type: string = entry.type; +} + +function TestPromiseModule() { + var cancellationError: webdriver.promise.CancellationError = new webdriver.promise.CancellationError(); + cancellationError = new webdriver.promise.CancellationError("message"); + var str: string = cancellationError.message; + str = cancellationError.name; + + var stringPromise: webdriver.promise.Promise; + var numberPromise: webdriver.promise.Promise; + var booleanPromise: webdriver.promise.Promise; + var voidPromise: webdriver.promise.Promise; + + webdriver.promise.all([stringPromise]).then(function (values: string[]) { }); + + webdriver.promise.asap('abc', function(value: any){ return true; }); + webdriver.promise.asap('abc', function(value: any){}, function(err: any) { return 'ABC'; }); + + stringPromise = webdriver.promise.checkedNodeCall(function(err: any, value: any) { return 'abc'; }); + + webdriver.promise.consume(function () { + return 5; + }).then(function (value: number) { }); + webdriver.promise.consume(function () { + return 5; + }, this).then(function (value: number) { }); + webdriver.promise.consume(function (a: number, b: number, c: number) { + return 5; + }, this, 1, 2, 3).then(function (value: number) { }); + + var numbersPromise: webdriver.promise.Promise = webdriver.promise.filter([1, 2, 3], function (element: number, type: any, index: number, arr: number[]) { + return true; + }); + numbersPromise = webdriver.promise.filter([1, 2, 3], function (element: number, type: any, index: number, arr: number[]) { + return true; + }, this); + numbersPromise = webdriver.promise.filter(numbersPromise, function (element: number, type: any, index: number, arr: number[]) { + return true; + }); + numbersPromise = webdriver.promise.filter(numbersPromise, function (element: number, type: any, index: number, arr: number[]) { + return true; + }, this); + + numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, type: any, index: number, arr: number[]) { + return true; + }); + numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, type: any, index: number, arr: number[]) { + return true; + }, this); + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { + return true; + }); + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { + return true; + }, this); + + var flow: webdriver.promise.ControlFlow = webdriver.promise.controlFlow(); + + stringPromise = webdriver.promise.createFlow(function(newFlow: webdriver.promise.ControlFlow) { return 'ABC' }); + + var deferred: webdriver.promise.Deferred; + deferred = webdriver.promise.defer(); + deferred = webdriver.promise.defer(); + + stringPromise = deferred.promise; + + deferred.fulfill('ABC'); + deferred.reject('error'); + + voidPromise = webdriver.promise.delayed(123); + + voidPromise = webdriver.promise.fulfilled(); + stringPromise = webdriver.promise.fulfilled('abc'); + + stringPromise = webdriver.promise.fullyResolved('abc'); + + var bool: boolean = webdriver.promise.isGenerator(function () { }); + var isPromise: boolean = webdriver.promise.isPromise('ABC'); + + stringPromise = webdriver.promise.rejected('{a: 123}'); + + webdriver.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); + + numberPromise = webdriver.promise.when('abc', function(value: any) { return 123; }, function(err: Error) { return 123; }); +} + +function TestUntilModule() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var conditionB: webdriver.until.Condition = new webdriver.until.Condition('message', function (driver: webdriver.WebDriver) { return true; }); + var conditionBBase: webdriver.until.Condition = conditionB; + var conditionWebElement: webdriver.until.Condition; + var conditionWebElements: webdriver.until.Condition; + + conditionB = webdriver.until.ableToSwitchToFrame(5); + var conditionAlert: webdriver.until.Condition = webdriver.until.alertIsPresent(); + var el: webdriver.WebElement = driver.findElement(webdriver.By.id('id')); + conditionB = webdriver.until.elementIsDisabled(el); + conditionB = webdriver.until.elementIsEnabled(el); + conditionB = webdriver.until.elementIsNotSelected(el); + conditionB = webdriver.until.elementIsNotVisible(el); + conditionB = webdriver.until.elementIsSelected(el); + conditionB = webdriver.until.elementIsVisible(el); + conditionB = webdriver.until.elementTextContains(el, 'text'); + conditionB = webdriver.until.elementTextIs(el, 'text'); + conditionB = webdriver.until.elementTextMatches(el, /text/); + conditionB = webdriver.until.stalenessOf(el); + conditionB = webdriver.until.titleContains('text'); + conditionB = webdriver.until.titleIs('text'); + conditionB = webdriver.until.titleMatches(/text/); + + conditionWebElement = webdriver.until.elementLocated(webdriver.By.id('id')); + conditionWebElements = webdriver.until.elementsLocated(webdriver.By.className('class')); +} + +function TestControlFlow() { + var flow: webdriver.promise.ControlFlow; + flow = new webdriver.promise.ControlFlow(); + + var emitter: webdriver.EventEmitter = flow; + + var eventType: string; + + eventType = webdriver.promise.ControlFlow.EventType.IDLE; + eventType = webdriver.promise.ControlFlow.EventType.RESET; + eventType = webdriver.promise.ControlFlow.EventType.SCHEDULE_TASK; + eventType = webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION; + + var stringPromise: webdriver.promise.Promise; + stringPromise = flow.execute(function() { return 'value'; }); + stringPromise = flow.execute(function() { return stringPromise; }); + stringPromise = flow.execute(function() { return stringPromise; }, 'Description'); + + var schedule: string; + schedule = flow.toString(); + schedule = flow.getSchedule(); + schedule = flow.getSchedule(true); + + flow.reset(); + + var voidPromise: webdriver.promise.Promise = flow.timeout(123); + voidPromise = flow.timeout(123, 'Description'); + + stringPromise = flow.wait(stringPromise); + + voidPromise = flow.wait(function() { return true; }); + voidPromise = flow.wait(function() { return true; }, 123); + voidPromise = flow.wait(function() { return stringPromise; }, 123, 'Timeout Message'); +} + +function TestDeferred() { + var deferred: webdriver.promise.Deferred; + + deferred = new webdriver.promise.Deferred(); + deferred = new webdriver.promise.Deferred(new webdriver.promise.ControlFlow()); + + var promise: webdriver.promise.Promise = deferred.promise; + + deferred.errback(new Error('Error')); + deferred.errback('Error'); + deferred.fulfill('abc'); + deferred.reject(new Error('Error')); + deferred.reject('Error'); + deferred.removeAll(); +} + +function TestPromiseClass() { + var controlFlow: webdriver.promise.ControlFlow; + var promise: webdriver.promise.Promise; + promise = new webdriver.promise.Promise(function( + onFulfilled: (value: string)=>void, + onRejected: ()=>void) { }); + promise = new webdriver.promise.Promise(function( + onFulfilled: (value: webdriver.promise.Promise)=>void, + onRejected: ()=>void) { }); + promise = new webdriver.promise.Promise(function( + onFulfilled: (value: string)=>void, + onRejected: ()=>void) { }, controlFlow); + + promise.cancel('Abort'); + + var isPending: boolean = promise.isPending(); + + promise = promise.then(); + promise = promise.then(function( a: string ) { return 'cde'; }); + promise = promise.then(function( a: string ) { return 'cde'; }, function( e: any) {}); + promise = promise.then(function( a: string ) { return 'cde'; }, function (e: any) { return 123; }); + + promise = promise.thenCatch(function (error: any) { }); + + promise.thenFinally(function () { }); +} + +function TestThenableClass() { + var thenable: webdriver.promise.Promise = new webdriver.promise.Promise(); + + thenable.cancel('Abort'); + + var isPending: boolean = thenable.isPending(); + + thenable = thenable.then(function (a: string) { return 'cde'; }); + thenable = thenable.then(function (a: string) { return 'cde'; }, function (e: any) { }); + thenable = thenable.then(function (a: string) { return 'cde'; }, function (e: any) { return 123; }); + + thenable = thenable.thenCatch(function (error: any) { }); + + thenable.thenFinally(function () { }); +} + +function TestErrorCode() { + var errorCode: number; + + errorCode = new webdriver.error.ElementNotSelectableError().code(); + errorCode = new webdriver.error.ElementNotVisibleError().code(); + errorCode = new webdriver.error.InvalidArgumentError().code(); + errorCode = new webdriver.error.InvalidCookieDomainError().code(); + errorCode = new webdriver.error.InvalidElementCoordinatesError().code(); + errorCode = new webdriver.error.InvalidElementStateError().code(); + errorCode = new webdriver.error.InvalidSelectorError().code(); + errorCode = new webdriver.error.NoSuchSessionError().code(); + errorCode = new webdriver.error.JavascriptError().code(); + errorCode = new webdriver.error.MoveTargetOutOfBoundsError().code(); + errorCode = new webdriver.error.NoSuchAlertError().code(); + errorCode = new webdriver.error.NoSuchElementError().code(); + errorCode = new webdriver.error.NoSuchFrameError().code(); + errorCode = new webdriver.error.NoSuchWindowError().code(); + errorCode = new webdriver.error.ScriptTimeoutError().code(); + errorCode = new webdriver.error.SessionNotCreatedError().code(); + errorCode = new webdriver.error.StaleElementReferenceError().code(); + errorCode = new webdriver.error.TimeoutError().code(); + errorCode = new webdriver.error.UnableToSetCookieError().code(); + errorCode = new webdriver.error.UnableToCaptureScreenError().code(); + errorCode = new webdriver.error.UnexpectedAlertOpenError().code(); + errorCode = new webdriver.error.UnknownCommandError().code(); + errorCode = new webdriver.error.UnknownMethodError().code(); + errorCode = new webdriver.error.UnsupportedOperationError().code(); +} + +function TestTestingModule() { + testing.before(function () { + }); + + testing.beforeEach(function () { + }); + + testing.describe("My test suite", function () { + testing.it("My test", function () { + }); + + testing.iit("My exclusive test.", function () { + }); + + }); + + testing.xdescribe("My disabled suite", function () { + testing.xit("My disabled test.", function () { + }); + }); + + testing.after(function () { + }); + + testing.afterEach(function () { + }); +} diff --git a/selenium-webdriver/selenium-webdriver-2.53.1.d.ts b/selenium-webdriver/selenium-webdriver-2.53.1.d.ts new file mode 100644 index 0000000000..a6e419755d --- /dev/null +++ b/selenium-webdriver/selenium-webdriver-2.53.1.d.ts @@ -0,0 +1,6459 @@ +// Type definitions for Selenium WebDriverJS 2.53.1 +// Project: https://github.com/SeleniumHQ/selenium/tree/master/javascript/node/selenium-webdriver +// Definitions by: Bill Armstrong , Yuki Kokubun , Craig Nishina +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace chrome { + /** + * Creates a new WebDriver client for Chrome. + * + * @extends {webdriver.WebDriver} + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(webdriver.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@link getDefaultService default service} by default. + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow to use, or + * {@code null} to use the currently active flow. + * @constructor + */ + constructor(opt_config?: Options|webdriver.Capabilities, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + } + + interface IOptionsValues { + args: string[]; + binary?: string; + detach: boolean; + extensions: string[]; + localState?: any; + logFile?: string; + prefs?: any; + } + + interface IPerfLoggingPrefs { + enableNetwork: boolean; + enablePage: boolean; + enableTimeline: boolean; + tracingCategories: string; + bufferUsageReportingInterval: number; + } + + /** + * Class for managing ChromeDriver specific options. + */ + class Options { + /** + * @constructor + */ + constructor(); + + /** + * Extracts the ChromeDriver specific options from the given capabilities + * object. + * @param {!webdriver.Capabilities} capabilities The capabilities object. + * @return {!Options} The ChromeDriver options. + */ + static fromCapabilities(capabilities: webdriver.Capabilities): Options; + + + /** + * Add additional command line arguments to use when launching the Chrome + * browser. Each argument may be specified with or without the "--" prefix + * (e.g. "--foo" and "foo"). Arguments with an associated value should be + * delimited by an "=": "foo=bar". + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: string[]): Options; + + + /** + * List of Chrome command line switches to exclude that ChromeDriver by default + * passes when starting Chrome. Do not prefix switches with "--". + * + * @param {...(string|!Array)} var_args The switches to exclude. + * @return {!Options} A self reference. + */ + excludeSwitches(...var_args: string[]): Options; + + + /** + * Add additional extensions to install when launching Chrome. Each extension + * should be specified as the path to the packed CRX file, or a Buffer for an + * extension. + * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The + * extensions to add. + * @return {!Options} A self reference. + */ + addExtensions(...var_args: any[]): Options; + + + /** + * Sets the path to the Chrome binary to use. On Mac OS X, this path should + * reference the actual Chrome executable, not just the application binary + * (e.g. "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"). + * + * The binary path be absolute or relative to the chromedriver server + * executable, but it must exist on the machine that will launch Chrome. + * + * @param {string} path The path to the Chrome binary to use. + * @return {!Options} A self reference. + */ + setChromeBinaryPath(path: string): Options; + + + /** + * Sets whether to leave the started Chrome browser running if the controlling + * ChromeDriver service is killed before {@link webdriver.WebDriver#quit()} is + * called. + * @param {boolean} detach Whether to leave the browser running if the + * chromedriver service is killed before the session. + * @return {!Options} A self reference. + */ + detachDriver(detach: boolean): Options; + + + /** + * Sets the user preferences for Chrome's user profile. See the "Preferences" + * file in Chrome's user data directory for examples. + * @param {!Object} prefs Dictionary of user preferences to use. + * @return {!Options} A self reference. + */ + setUserPreferences(prefs: any): Options; + + + /** + * Sets the logging preferences for the new session. + * @param {!webdriver.logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the performance logging preferences. Options include: + * + * - `enableNetwork`: Whether or not to collect events from Network domain. + * - `enablePage`: Whether or not to collect events from Page domain. + * - `enableTimeline`: Whether or not to collect events from Timeline domain. + * Note: when tracing is enabled, Timeline domain is implicitly disabled, + * unless `enableTimeline` is explicitly set to true. + * - `tracingCategories`: A comma-separated string of Chrome tracing categories + * for which trace events should be collected. An unspecified or empty + * string disables tracing. + * - `bufferUsageReportingInterval`: The requested number of milliseconds + * between DevTools trace buffer usage events. For example, if 1000, then + * once per second, DevTools will report how full the trace buffer is. If a + * report indicates the buffer usage is 100%, a warning will be issued. + * + * @param {{enableNetwork: boolean, + * enablePage: boolean, + * enableTimeline: boolean, + * tracingCategories: string, + * bufferUsageReportingInterval: number}} prefs The performance + * logging preferences. + * @return {!Options} A self reference. + */ + setPerfLoggingPrefs(prefs: IPerfLoggingPrefs): Options; + + + /** + * Sets preferences for the "Local State" file in Chrome's user data + * directory. + * @param {!Object} state Dictionary of local state preferences. + * @return {!Options} A self reference. + */ + setLocalState(state: any): Options; + + + /** + * Sets the name of the activity hosting a Chrome-based Android WebView. This + * option must be set to connect to an [Android WebView]( + * https://sites.google.com/a/chromium.org/chromedriver/getting-started/getting-started---android) + * + * @param {string} name The activity name. + * @return {!Options} A self reference. + */ + androidActivity(name: string): Options; + + + /** + * Sets the device serial number to connect to via ADB. If not specified, the + * ChromeDriver will select an unused device at random. An error will be + * returned if all devices already have active sessions. + * + * @param {string} serial The device serial number to connect to. + * @return {!Options} A self reference. + */ + androidDeviceSerial(serial: string): Options; + + + /** + * Configures the ChromeDriver to launch Chrome on Android via adb. This + * function is shorthand for + * {@link #androidPackage options.androidPackage('com.android.chrome')}. + * @return {!Options} A self reference. + */ + androidChrome(): Options; + + + /** + * Sets the package name of the Chrome or WebView app. + * + * @param {?string} pkg The package to connect to, or `null` to disable Android + * and switch back to using desktop Chrome. + * @return {!Options} A self reference. + */ + androidPackage(pkg: string): Options; + + + /** + * Sets the process name of the Activity hosting the WebView (as given by `ps`). + * If not specified, the process name is assumed to be the same as + * {@link #androidPackage}. + * + * @param {string} processName The main activity name. + * @return {!Options} A self reference. + */ + androidProcess(processName: string): Options; + + + /** + * Sets whether to connect to an already-running instead of the specified + * {@linkplain #androidProcess app} instead of launching the app with a clean + * data directory. + * + * @param {boolean} useRunning Whether to connect to a running instance. + * @return {!Options} A self reference. + */ + androidUseRunningApp(useRunning: boolean): Options; + + + /** + * Sets the path to Chrome's log file. This path should exist on the machine + * that will launch Chrome. + * @param {string} path Path to the log file to use. + * @return {!Options} A self reference. + */ + setChromeLogFile(path: string): Options; + + + /** + * Sets the directory to store Chrome minidumps in. This option is only + * supported when ChromeDriver is running on Linux. + * @param {string} path The directory path. + * @return {!Options} A self reference. + */ + setChromeMinidumpPath(path: string): Options; + + + /** + * Configures Chrome to emulate a mobile device. For more information, refer + * to the ChromeDriver project page on [mobile emulation][em]. Configuration + * options include: + * + * - `deviceName`: The name of a pre-configured [emulated device][devem] + * - `width`: screen width, in pixels + * - `height`: screen height, in pixels + * - `pixelRatio`: screen pixel ratio + * + * __Example 1: Using a Pre-configured Device__ + * + * let options = new chrome.Options().setMobileEmulation( + * {deviceName: 'Google Nexus 5'}); + * + * let driver = new chrome.Driver(options); + * + * __Example 2: Using Custom Screen Configuration__ + * + * let options = new chrome.Options().setMobileEmulation({ + * width: 360, + * height: 640, + * pixelRatio: 3.0 + * }); + * + * let driver = new chrome.Driver(options); + * + * + * [em]: https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation + * [devem]: https://developer.chrome.com/devtools/docs/device-mode + * + * @param {?({deviceName: string}| + * {width: number, height: number, pixelRatio: number})} config The + * mobile emulation configuration, or `null` to disable emulation. + * @return {!Options} A self reference. + */ + setMobileEmulation(config: any): Options; + + /** + * Sets the proxy settings for the new session. + * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + + /** + * Converts this options instance to a {@link webdriver.Capabilities} object. + * @param {webdriver.Capabilities=} opt_capabilities The capabilities to merge + * these options into, if any. + * @return {!webdriver.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; + } + + /** + * Creates {@link remote.DriverService} instances that manage a ChromeDriver + * server. + */ + class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the chromedriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the chromedriver + * cannot be found on the PATH. + * @constructor + */ + constructor(opt_exe?: string); + + /** + * Sets the port to start the ChromeDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; + + + /** + * Sets which port adb is listening to. _The ChromeDriver will connect to adb + * if an {@linkplain Options#androidPackage Android session} is requested, but + * adb **must** be started beforehand._ + * + * @param {number} port Which port adb is running on. + * @return {!ServiceBuilder} A self reference. + */ + setAdbPort(port: number): ServiceBuilder; + + + /** + * Sets the path of the log file the driver should log to. If a log file is + * not specified, the driver will log to stderr. + * @param {string} path Path of the log file to use. + * @return {!ServiceBuilder} A self reference. + */ + loggingTo(path: string): ServiceBuilder; + + + /** + * Enables verbose logging. + * @return {!ServiceBuilder} A self reference. + */ + enableVerboseLogging(): ServiceBuilder; + + + /** + * Sets the number of threads the driver should use to manage HTTP requests. + * By default, the driver will use 4 threads. + * @param {number} n The number of threads to use. + * @return {!ServiceBuilder} A self reference. + */ + setNumHttpThreads(n: number): ServiceBuilder; + + + /** + * Sets the base path for WebDriver REST commands (e.g. "/wd/hub"). + * By default, the driver will accept commands relative to "/". + * @param {string} path The base path to use. + * @return {!ServiceBuilder} A self reference. + */ + setUrlBasePath(path: string): ServiceBuilder; + + + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array.)} config The + * configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string|Array): ServiceBuilder; + + + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: { [key: string]: string }): ServiceBuilder; + + + /** + * Creates a new DriverService using this instance's current configuration. + * @return {remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; + } + + /** + * Returns the default ChromeDriver service. If such a service has not been + * configured, one will be constructed using the default configuration for + * a ChromeDriver executable found on the system PATH. + * @return {!remote.DriverService} The default ChromeDriver service. + */ + function getDefaultService(): remote.DriverService; + + /** + * Sets the default service to use for new ChromeDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ + function setDefaultService(service: remote.DriverService): void; +} + +declare namespace edge { + + class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@linkplain #getDefaultService default service} by default. + * @param {promise.ControlFlow=} opt_flow The control flow to use, or + * {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities|Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; + } + + /** + * Class for managing MicrosoftEdgeDriver specific options. + */ + class Options { + + /** + * Extracts the MicrosoftEdgeDriver specific options from the given + * capabilities object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The MicrosoftEdgeDriver options. + */ + static fromCapabilities(cap: webdriver.Capabilities): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Sets the page load strategy for Edge. + * Supported values are "normal", "eager", and "none"; + * + * @param {string} pageLoadStrategy The page load strategy to use. + * @return {!Options} A self reference. + */ + setPageLoadStrategy(pageLoadStrategy: string): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; + } + + /** + * Creates {@link remote.DriverService} instances that manage a + * MicrosoftEdgeDriver server in a child process. + */ + class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the MicrosoftEdgeDriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the + * MicrosoftEdgeDriver cannot be found on the PATH. + */ + constructor(opt_exe?: string); + + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array.)} + * config The configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string|Array): ServiceBuilder; + + /** + * Sets the port to start the MicrosoftEdgeDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; + + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: Object): ServiceBuilder; + + /** + * Creates a new DriverService using this instance's current configuration. + * @return {!remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; + } + + /** + * Returns the default MicrosoftEdgeDriver service. If such a service has + * not been configured, one will be constructed using the default configuration + * for an MicrosoftEdgeDriver executable found on the system PATH. + * @return {!remote.DriverService} The default MicrosoftEdgeDriver service. + */ + function getDefaultService(): remote.DriverService; + + /** + * Sets the default service to use for new MicrosoftEdgeDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ + function setDefaultService(service: remote.DriverService): void; +} + +declare namespace executors { + /** + * Creates a command executor that uses WebDriver's JSON wire protocol. + * @param {(string|!promise.Promise)} url The server's URL, + * or a promise that will resolve to that URL. + * @param {?string=} opt_proxy (optional) The URL of the HTTP proxy for the + * client to use. + * @returns {!./lib/command.Executor} The new command executor. + */ + function createExecutor(url: string|webdriver.promise.Promise, opt_agent?: string, opt_proxy?: string): webdriver.Executor; +} + +declare namespace firefox { + /** + * Manages a Firefox subprocess configured for use with WebDriver. + */ + class Binary { + /** + * @param {string=} opt_exe Path to the Firefox binary to use. If not + * specified, will attempt to locate Firefox on the current system. + * @constructor + */ + constructor(opt_exe?: string); + + /** + * Add arguments to the command line used to start Firefox. + * @param {...(string|!Array.)} var_args Either the arguments to add as + * varargs, or the arguments as an array. + */ + addArguments(...var_args: string[]): void; + + + /** + * Launches Firefox and eturns a promise that will be fulfilled when the process + * terminates. + * @param {string} profile Path to the profile directory to use. + * @return {!promise.Promise.} A promise for the process result. + * @throws {Error} If this instance has already been started. + */ + launch(profile: string): webdriver.promise.Promise; + + + /** + * Kills the managed Firefox process. + * @return {!promise.Promise} A promise for when the process has terminated. + */ + kill(): webdriver.promise.Promise; + } + + /** + * Models a Firefox proifle directory for use with the FirefoxDriver. The + * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} + * is called. + */ + class Profile { + /** + * @param {string=} opt_dir Path to an existing Firefox profile directory to + * use a template for this profile. If not specified, a blank profile will + * be used. + * @constructor + */ + constructor(opt_dir?: string); + + /** + * Registers an extension to be included with this profile. + * @param {string} extension Path to the extension to include, as either an + * unpacked extension directory or the path to a xpi file. + */ + addExtension(extension: string): void; + + + /** + * Sets a desired preference for this profile. + * @param {string} key The preference key. + * @param {(string|number|boolean)} value The preference value. + * @throws {Error} If attempting to set a frozen preference. + */ + setPreference(key: string, value: string): void; + setPreference(key: string, value: number): void; + setPreference(key: string, value: boolean): void; + + + /** + * Returns the currently configured value of a profile preference. This does + * not include any defaults defined in the profile's template directory user.js + * file (if a template were specified on construction). + * @param {string} key The desired preference. + * @return {(string|number|boolean|undefined)} The current value of the + * requested preference. + */ + getPreference(key: string): any; + + + /** + * @return {number} The port this profile is currently configured to use, or + * 0 if the port will be selected at random when the profile is written + * to disk. + */ + getPort(): number; + + + /** + * Sets the port to use for the WebDriver extension loaded by this profile. + * @param {number} port The desired port, or 0 to use any free port. + */ + setPort(port: number): void; + + + /** + * @return {boolean} Whether the FirefoxDriver is configured to automatically + * accept untrusted SSL certificates. + */ + acceptUntrustedCerts(): boolean; + + + /** + * Sets whether the FirefoxDriver should automatically accept untrusted SSL + * certificates. + * @param {boolean} value . + */ + setAcceptUntrustedCerts(value: boolean): void; + + + /** + * Sets whether to assume untrusted certificates come from untrusted issuers. + * @param {boolean} value . + */ + setAssumeUntrustedCertIssuer(value: boolean): void; + + + /** + * @return {boolean} Whether to assume untrusted certs come from untrusted + * issuers. + */ + assumeUntrustedCertIssuer(): boolean; + + + /** + * Sets whether to use native events with this profile. + * @param {boolean} enabled . + */ + setNativeEventsEnabled(enabled: boolean): void; + + + /** + * Returns whether native events are enabled in this profile. + * @return {boolean} . + */ + nativeEventsEnabled(): boolean; + + + /** + * Writes this profile to disk. + * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver + * extension from the generated profile. Used to reduce the size of an + * {@link #encode() encoded profile} since the server will always install + * the extension itself. + * @return {!promise.Promise.} A promise for the path to the new + * profile directory. + */ + writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; + + + /** + * Encodes this profile as a zipped, base64 encoded directory. + * @return {!promise.Promise.} A promise for the encoded profile. + */ + encode(): webdriver.promise.Promise; + } + + /** + * Configuration options for the FirefoxDriver. + */ + class Options { + /** + * Sets the profile to use. The profile may be specified as a + * {@link Profile} object or as the path to an existing Firefox profile to use + * as a template. + * + * @param {(string|!Profile)} profile The profile to use. + * @return {!Options} A self reference. + */ + setProfile(profile: string|any): Options; + + /** + * Sets the binary to use. The binary may be specified as the path to a Firefox + * executable, or as a {@link Binary} object. + * + * @param {(string|!Binary)} binary The binary to use. + * @return {!Options} A self reference. + */ + setBinary(binary: string|any): Options; + + /** + * Sets the logging preferences for the new session. + * @param {logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the proxy to use. + * + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Sets whether to use Mozilla's Marionette to drive the browser. + * + * @see https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver + */ + useMarionette(marionette: any): Options; + + /** + * Converts these options to a {@link capabilities.Capabilities} instance. + * + * @return {!capabilities.Capabilities} A new capabilities object. + */ + toCapabilities(): webdriver.Capabilities; + } + + /** + * @return {string} . + * @throws {Error} + */ + function findWires(): string; + + /** + * @param {(string|!Binary)} binary . + * @return {!remote.DriverService} . + */ + function createWiresService(binary: string|any): remote.DriverService; + + /** + * @param {(Profile|string)} profile The profile to prepare. + * @param {number} port The port the FirefoxDriver should listen on. + * @return {!Promise} a promise for the path to the profile directory. + */ + function prepareProfile(profile: string|any, port: number): any; + + /** + * A WebDriver client for Firefox. + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(Options|capabilities.Capabilities|Object)=} opt_config The + * configuration options for this driver, specified as either an + * {@link Options} or {@link capabilities.Capabilities}, or as a raw hash + * object. + * @param {promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + */ + constructor(opt_config?: Options|webdriver.Capabilities|Object, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; + } +} + +declare namespace http { + /** + * Converts a headers map to a HTTP header block string. + * @param {!Map} headers The map to convert. + * @return {string} The headers as a string. + */ + function headersToString(headers: any): string; + + /** + * Represents a HTTP request message. This class is a "partial" request and only + * defines the path on the server to send a request to. It is each client's + * responsibility to build the full URL for the final request. + * @final + */ + class HttpRequest { + /** + * @param {string} method The HTTP method to use for the request. + * @param {string} path The path on the server to send the request to. + * @param {Object=} opt_data This request's non-serialized JSON payload data. + */ + constructor(method: string, path: string, opt_data?: Object); + + /** @override */ + toString(): string; + } + + /** + * Represents a HTTP response message. + * @final + */ + class HttpResponse { + /** + * @param {number} status The response code. + * @param {!Object} headers The response headers. All header names + * will be converted to lowercase strings for consistent lookups. + * @param {string} body The response body. + */ + constructor(status: number, headers: Object, body: string); + + /** @override */ + toString(): string; + } + + + function post(path: string): any; + function del(path: string): any; + function get(path: string): any; + function resource(method: string, path: string): any; + + /** + * A basic HTTP client used to send messages to a remote end. + */ + class HttpClient { + /** + * @param {string} serverUrl URL for the WebDriver server to send commands to. + * @param {http.Agent=} opt_agent The agent to use for each request. + * Defaults to `http.globalAgent`. + * @param {?string=} opt_proxy The proxy to use for the connection to the + * server. Default is to use no proxy. + */ + constructor(serverUrl: string, opt_agent?: any, opt_proxy?: string); + + /** + * Sends a request to the server. The client will automatically follow any + * redirects returned by the server, fulfilling the returned promise with the + * final response. + * + * @param {!HttpRequest} httpRequest The request to send. + * @return {!promise.Promise} A promise that will be fulfilled + * with the server's response. + */ + send(httpRequest: HttpRequest): webdriver.promise.Promise; + } + + /** + * Sends a single HTTP request. + * @param {!Object} options The request options. + * @param {function(!HttpResponse)} onOk The function to call if the + * request succeeds. + * @param {function(!Error)} onError The function to call if the request fails. + * @param {?string=} opt_data The data to send with the request. + * @param {?string=} opt_proxy The proxy server to use for the request. + */ + function sendRequest(options: Object, onOk: any, onError: any, opt_data?: string, opt_proxy?: string): any; + + /** + * A command executor that communicates with the server using HTTP + JSON. + * + * By default, each instance of this class will use the legacy wire protocol + * from [Selenium project][json]. The executor will automatically switch to the + * [W3C wire protocol][w3c] if the remote end returns a compliant response to + * a new session command. + * + * [json]: https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol + * [w3c]: https://w3c.github.io/webdriver/webdriver-spec.html + * + * @implements {cmd.Executor} + */ + class Executor { + /** + * @param {!HttpClient} client The client to use for sending requests to the + * server. + */ + constructor(client: HttpClient); + + /** + * Defines a new command for use with this executor. When a command is sent, + * the {@code path} will be preprocessed using the command's parameters; any + * path segments prefixed with ":" will be replaced by the parameter of the + * same name. For example, given "/person/:name" and the parameters + * "{name: 'Bob'}", the final command path will be "/person/Bob". + * + * @param {string} name The command name. + * @param {string} method The HTTP method to use when sending this command. + * @param {string} path The path to send the command to, relative to + * the WebDriver server's command root and of the form + * "/path/:variable/segment". + */ + defineCommand(name: string, method: string, path: string): void; + + /** @override */ + execute(command: any): any; + } + + /** + * @param {string} str . + * @return {?} . + */ + function tryParse(str: string): any; + + /** + * Callback used to parse {@link HttpResponse} objects from a + * {@link HttpClient}. + * @param {!HttpResponse} httpResponse The HTTP response to parse. + * @param {boolean} w3c Whether the response should be processed using the + * W3C wire protocol. + * @return {{value: ?}} The parsed response. + * @throws {WebDriverError} If the HTTP response is an error. + */ + function parseHttpResponse(httpResponse: HttpResponse, w3c: boolean): any; + + /** + * Builds a fully qualified path using the given set of command parameters. Each + * path segment prefixed with ':' will be replaced by the value of the + * corresponding parameter. All parameters spliced into the path will be + * removed from the parameter map. + * @param {string} path The original resource path. + * @param {!Object<*>} parameters The parameters object to splice into the path. + * @return {string} The modified path. + */ + function buildPath(path: string, parameters: Object): string; +} + +declare namespace ie { + + /** + * A WebDriver client for Microsoft's Internet Explorer. + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {promise.ControlFlow=} opt_flow The control flow to use, + * or {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities|Options, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; + } + + /** + * Class for managing IEDriver specific options. + */ + class Options { + constructor(); + + /** + * Extracts the IEDriver specific options from the given capabilities + * object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The IEDriver options. + */ + static fromCapabilities(caps: webdriver.Capabilities): Options; + + /** + * Whether to disable the protected mode settings check when the session is + * created. Disbling this setting may lead to significant instability as the + * browser may become unresponsive/hang. Only "best effort" support is provided + * when using this capability. + * + * For more information, refer to the IEDriver's + * [required system configuration](http://goo.gl/eH0Yi3). + * + * @param {boolean} ignoreSettings Whether to ignore protected mode settings. + * @return {!Options} A self reference. + */ + introduceFlakinessByIgnoringProtectedModeSettings(ignoreSettings: boolean): Options; + + /** + * Indicates whether to skip the check that the browser's zoom level is set to + * 100%. + * + * @param {boolean} ignore Whether to ignore the browser's zoom level settings. + * @return {!Options} A self reference. + */ + ignoreZoomSetting(ignore: boolean): Options; + + /** + * Sets the initial URL loaded when IE starts. This is intended to be used with + * {@link #ignoreProtectedModeSettings} to allow the user to initialize IE in + * the proper Protected Mode zone. Setting this option may cause browser + * instability or flaky and unresponsive code. Only "best effort" support is + * provided when using this option. + * + * @param {string} url The initial browser URL. + * @return {!Options} A self reference. + */ + initialBrowserUrl(url: string): Options; + + /** + * Configures whether to enable persistent mouse hovering (true by default). + * Persistent hovering is achieved by continuously firing mouse over events at + * the last location the mouse cursor has been moved to. + * + * @param {boolean} enable Whether to enable persistent hovering. + * @return {!Options} A self reference. + */ + enablePersistentHover(enable: boolean): Options; + + /** + * Configures whether the driver should attempt to remove obsolete + * {@linkplain webdriver.WebElement WebElements} from its internal cache on + * page navigation (true by default). Disabling this option will cause the + * driver to run with a larger memory footprint. + * + * @param {boolean} enable Whether to enable element reference cleanup. + * @return {!Options} A self reference. + */ + enableElementCacheCleanup(enable: boolean): Options; + + /** + * Configures whether to require the IE window to have input focus before + * performing any user interactions (i.e. mouse or keyboard events). This + * option is disabled by default, but delivers much more accurate interaction + * events when enabled. + * + * @param {boolean} require Whether to require window focus. + * @return {!Options} A self reference. + */ + requireWindowFocus(require: boolean): Options; + + /** + * Configures the timeout, in milliseconds, that the driver will attempt to + * located and attach to a newly opened instance of Internet Explorer. The + * default is zero, which indicates waiting indefinitely. + * + * @param {number} timeout How long to wait for IE. + * @return {!Options} A self reference. + */ + browserAttachTimeout(timeout: number): Options; + + /** + * Configures whether to launch Internet Explorer using the CreateProcess API. + * If this option is not specified, IE is launched using IELaunchURL, if + * available. For IE 8 and above, this option requires the TabProcGrowth + * registry value to be set to 0. + * + * @param {boolean} force Whether to use the CreateProcess API. + * @return {!Options} A self reference. + */ + forceCreateProcessApi(force: boolean): Options; + + /** + * Specifies command-line switches to use when launching Internet Explorer. + * This is only valid when used with {@link #forceCreateProcessApi}. + * + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: Array): Options; + + /** + * Configures whether proxies should be configured on a per-process basis. If + * not set, setting a {@linkplain #setProxy proxy} will configure the system + * proxy. The default behavior is to use the system proxy. + * + * @param {boolean} enable Whether to enable per-process proxy settings. + * @return {!Options} A self reference. + */ + usePerProcessProxy(enable: boolean): Options; + + /** + * Configures whether to clear the cache, cookies, history, and saved form data + * before starting the browser. _Using this capability will clear session data + * for all running instances of Internet Explorer, including those started + * manually._ + * + * @param {boolean} cleanSession Whether to clear all session data on startup. + * @return {!Options} A self reference. + */ + ensureCleanSession(cleanSession: boolean): Options; + + /** + * Sets the path to the log file the driver should log to. + * @param {string} file The log file path. + * @return {!Options} A self reference. + */ + setLogFile(file: string): Options; + + /** + * Sets the IEDriverServer's logging {@linkplain Level level}. + * @param {Level} level The logging level. + * @return {!Options} A self reference. + */ + setLogLevel(level: webdriver.logging.Level): Options; + + /** + * Sets the IP address of the driver's host adapter. + * @param {string} host The IP address to use. + * @return {!Options} A self reference. + */ + setHost(host: string): Options; + + /** + * Sets the path of the temporary data directory to use. + * @param {string} path The log file path. + * @return {!Options} A self reference. + */ + setExtractPath(path: string): Options; + + /** + * Sets whether the driver should start in silent mode. + * @param {boolean} silent Whether to run in silent mode. + * @return {!Options} A self reference. + */ + silent(silent: boolean): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; + } + +} + +declare namespace opera { + /** + * Creates {@link remote.DriverService} instances that manages an + * [OperaDriver](https://github.com/operasoftware/operachromiumdriver) + * server in a child process. + */ + class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the operadriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the operadriver + * cannot be found on the PATH. + */ + constructor(opt_exe?: string); + + /** + * Sets the port to start the OperaDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; + + /** + * Sets the path of the log file the driver should log to. If a log file is + * not specified, the driver will log to stderr. + * @param {string} path Path of the log file to use. + * @return {!ServiceBuilder} A self reference. + */ + loggingTo(path: string): ServiceBuilder; + + /** + * Enables verbose logging. + * @return {!ServiceBuilder} A self reference. + */ + enableVerboseLogging(): ServiceBuilder; + + /** + * Silence sthe drivers output. + * @return {!ServiceBuilder} A self reference. + */ + silent(): ServiceBuilder; + + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array)} + * config The configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string|Array): ServiceBuilder; + + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: Object): ServiceBuilder; + + /** + * Creates a new DriverService using this instance's current configuration. + * @return {!remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; + } + + /** + * Sets the default service to use for new OperaDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ + function setDefaultService(service: remote.DriverService): any; + + /** + * Returns the default OperaDriver service. If such a service has not been + * configured, one will be constructed using the default configuration for + * a OperaDriver executable found on the system PATH. + * @return {!remote.DriverService} The default OperaDriver service. + */ + function getDefaultService(): remote.DriverService; + + /** + * Class for managing {@linkplain Driver OperaDriver} specific options. + */ + class Options { + /** + * Extracts the OperaDriver specific options from the given capabilities + * object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The OperaDriver options. + */ + static fromCapabilities(caps: webdriver.Capabilities): Options; + + /** + * Add additional command line arguments to use when launching the Opera + * browser. Each argument may be specified with or without the "--" prefix + * (e.g. "--foo" and "foo"). Arguments with an associated value should be + * delimited by an "=": "foo=bar". + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: Array): Options; + + /** + * Add additional extensions to install when launching Opera. Each extension + * should be specified as the path to the packed CRX file, or a Buffer for an + * extension. + * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The + * extensions to add. + * @return {!Options} A self reference. + */ + addExtensions(...var_args: Array): Options; + + /** + * Sets the path to the Opera binary to use. On Mac OS X, this path should + * reference the actual Opera executable, not just the application binary. The + * binary path be absolute or relative to the operadriver server executable, but + * it must exist on the machine that will launch Opera. + * + * @param {string} path The path to the Opera binary to use. + * @return {!Options} A self reference. + */ + setOperaBinaryPath(path: string): Options; + + /** + * Sets the logging preferences for the new session. + * @param {!./lib/logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; + } + + class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@link getDefaultService default service} by default. + * @param {promise.ControlFlow=} opt_flow The control flow to use, + * or {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities|Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; + } +} + +declare namespace remote { + /** + * A record object that defines the configuration options for a DriverService + * instance. + * + * @record + */ + interface ServiceOptions {} + + /** + * Manages the life and death of a native executable WebDriver server. + * + * It is expected that the driver server implements the + * https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol. + * Furthermore, the managed server should support multiple concurrent sessions, + * so that this class may be reused for multiple clients. + */ + class DriverService { + /** + * @param {string} executable Path to the executable to run. + * @param {!ServiceOptions} options Configuration options for the service. + */ + constructor(executable: string, options: ServiceOptions); + + /** + * @return {!promise.Promise} A promise that resolves to + * the server's address. + * @throws {Error} If the server has not been started. + */ + address(): webdriver.promise.Promise; + + /** + * Returns whether the underlying process is still running. This does not take + * into account whether the process is in the process of shutting down. + * @return {boolean} Whether the underlying service process is running. + */ + isRunning(): boolean; + + /** + * Starts the server if it is not already running. + * @param {number=} opt_timeoutMs How long to wait, in milliseconds, for the + * server to start accepting requests. Defaults to 30 seconds. + * @return {!promise.Promise} A promise that will resolve + * to the server's base URL when it has started accepting requests. If the + * timeout expires before the server has started, the promise will be + * rejected. + */ + start(opt_timeoutMs?: number): webdriver.promise.Promise; + + /** + * Stops the service if it is not currently running. This function will kill + * the server immediately. To synchronize with the active control flow, use + * {@link #stop()}. + * @return {!promise.Promise} A promise that will be resolved when + * the server has been stopped. + */ + kill(): webdriver.promise.Promise; + + /** + * Schedules a task in the current control flow to stop the server if it is + * currently running. + * @return {!promise.Promise} A promise that will be resolved when + * the server has been stopped. + */ + stop(): webdriver.promise.Promise; + } +} + +declare namespace safari { + class Server {} + + /** + * @return {!Promise} A promise that will resolve with the path + * to Safari on the current system. + */ + function findSafariExecutable(): any; + + /** + * @param {string} serverUrl The URL to connect to. + * @return {!Promise} A promise for the path to a file that Safari can + * open on start-up to trigger a new connection to the WebSocket server. + */ + function createConnectFile(serverUrl: string): any; + + /** + * Deletes all session data files if so desired. + * @param {!Object} desiredCapabilities . + * @return {!Array} A list of promises for the deleted files. + */ + function cleanSession(desiredCapabilities: webdriver.Capabilities): any[]; + + /** @return {string} . */ + function getRandomString(): string; + + /** + * @implements {command.Executor} + */ + class CommandExecutor { + } + + /** + * Configuration options specific to the {@link Driver SafariDriver}. + */ + class Options { + /** + * Extracts the SafariDriver specific options from the given capabilities + * object. + * @param {!Capabilities} capabilities The capabilities object. + * @return {!Options} The ChromeDriver options. + */ + static fromCapabilities(capabilities: webdriver.Capabilities): Options; + + /** + * Sets whether to force Safari to start with a clean session. Enabling this + * option will cause all global browser data to be deleted. + * @param {boolean} clean Whether to make sure the session has no cookies, + * cache entries, local storage, or databases. + * @return {!Options} A self reference. + */ + setCleanSession(clean: boolean): Options; + + /** + * Sets the logging preferences for the new session. + * @param {!./lib/logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Converts this options instance to a {@link Capabilities} object. + * @param {Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; + } + + /** + * A WebDriver client for Safari. This class should never be instantiated + * directly; instead, use the {@linkplain ./builder.Builder Builder}: + * + * var driver = new Builder() + * .forBrowser('safari') + * .build(); + * + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(Options|Capabilities)=} opt_config The configuration + * options for the new session. + * @param {promise.ControlFlow=} opt_flow The control flow to create + * the driver under. + */ + constructor(opt_config?: Options|webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); + + } +} + +declare namespace webdriver { + + namespace error { + class IError extends Error { + constructor(opt_error?: string); + + code(): number; + } + + /** + * The base WebDriver error type. This error type is only used directly when a + * more appropriate category is not defined for the offending error. + */ + class WebDriverError extends IError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An attempt was made to select an element that cannot be selected. + */ + class ElementNotSelectableError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An element command could not be completed because the element is not visible + * on the page. + */ + class ElementNotVisibleError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The arguments passed to a command are either invalid or malformed. + */ + class InvalidArgumentError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An illegal attempt was made to set a cookie under a different domain than + * the current page. + */ + class InvalidCookieDomainError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The coordinates provided to an interactions operation are invalid. + */ + class InvalidElementCoordinatesError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An element command could not be completed because the element is in an + * invalid state, e.g. attempting to click an element that is no longer attached + * to the document. + */ + class InvalidElementStateError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * Argument was an invalid selector. + */ + class InvalidSelectorError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * Occurs when a command is directed to a session that does not exist. + */ + class NoSuchSessionError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An error occurred while executing JavaScript supplied by the user. + */ + class JavascriptError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The target for mouse interaction is not in the browser’s viewport and cannot + * be brought into that viewport. + */ + class MoveTargetOutOfBoundsError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An attempt was made to operate on a modal dialog when one was not open. + */ + class NoSuchAlertError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An element could not be located on the page using the given search + * parameters. + */ + class NoSuchElementError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A request to switch to a frame could not be satisfied because the frame + * could not be found. + */ + class NoSuchFrameError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A request to switch to a window could not be satisfied because the window + * could not be found. + */ + class NoSuchWindowError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A script did not complete before its timeout expired. + */ + class ScriptTimeoutError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A new session could not be created. + */ + class SessionNotCreatedError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An element command failed because the referenced element is no longer + * attached to the DOM. + */ + class StaleElementReferenceError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An operation did not completErrorCodee before its timeout expired. + */ + class TimeoutError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A request to set a cookie’s value could not be satisfied. + */ + class UnableToSetCookieError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A screen capture operation was not possible. + */ + class UnableToCaptureScreenError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A modal dialog was open, blocking this operation. + */ + class UnexpectedAlertOpenError extends WebDriverError { + /** + * @param {string=} opt_error the error message, if any. + * @param {string=} opt_text the text of the open dialog, if available. + */ + constructor(opt_error?: string, opt_text?: string); + + /** + * @return {(string|undefined)} The text displayed with the unhandled alert, + * if available. + */ + getAlertText(): string; + } + + /** + * A command could not be executed because the remote end is not aware of it. + */ + class UnknownCommandError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The requested command matched a known URL but did not match an method for + * that URL. + */ + class UnknownMethodError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * Reports an unsupport operation. + */ + class UnsupportedOperationError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + } + + namespace logging { + + /** + * A hash describing log preferences. + * @typedef {Object.} + */ + class Preferences { + setLevel(type: string|Type, level: Level|string|number): void; + toJSON(): { [key: string]: string }; + } + + /** + * Common log types. + * @enum {string} + */ + enum Type { + /** Logs originating from the browser. */ + BROWSER, + /** Logs from a WebDriver client. */ + CLIENT, + /** Logs from a WebDriver implementation. */ + DRIVER, + /** Logs related to performance. */ + PERFORMANCE, + /** Logs from the remote server. */ + SERVER + } + + /** + * Defines a message level that may be used to control logging output. + * + * @final + */ + class Level { + name_: string; + value_: number; + /** + * @param {string} name the level's name. + * @param {number} level the level's numeric value. + */ + constructor(name: string, level: number); + + /** @override */ + toString(): string; + + /** This logger's name. */ + name(): string; + + /** The numeric log level. */ + value(): number; + + /** + * Indicates no log messages should be recorded. + * @const + */ + static OFF: Level; + /** + * Log messages with a level of `1000` or higher. + * @const + */ + static SEVERE: Level; + /** + * Log messages with a level of `900` or higher. + * @const + */ + static WARNING: Level; + /** + * Log messages with a level of `800` or higher. + * @const + */ + static INFO: Level; + /** + * Log messages with a level of `700` or higher. + * @const + */ + static DEBUG: Level; + /** + * Log messages with a level of `500` or higher. + * @const + */ + static FINE: Level; + /** + * Log messages with a level of `400` or higher. + * @const + */ + static FINER: Level; + /** + * Log messages with a level of `300` or higher. + * @const + */ + static FINEST: Level; + /** + * Indicates all log messages should be recorded. + * @const + */ + static ALL: Level; + } + + /** + * Converts a level name or value to a {@link webdriver.logging.Level} value. + * If the name/value is not recognized, {@link webdriver.logging.Level.ALL} + * will be returned. + * @param {(number|string)} nameOrValue The log level name, or value, to + * convert . + * @return {!webdriver.logging.Level} The converted level. + */ + function getLevel(nameOrValue: string|number): Level; + + interface IEntryJSON { + level: string; + message: string; + timestamp: number; + type: string; + } + + /** + * A single log entry. + */ + class Entry { + /** + * @param {(!webdriver.logging.Level|string)} level The entry level. + * @param {string} message The log message. + * @param {number=} opt_timestamp The time this entry was generated, in + * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the + * current time will be used. + * @param {string=} opt_type The log type, if known. + * @constructor + */ + constructor(level: Level|string|number, message: string, opt_timestamp?:number, opt_type?:string|Type); + + /** @type {!webdriver.logging.Level} */ + level: Level; + + /** @type {string} */ + message: string; + + /** @type {number} */ + timestamp: number; + + /** @type {string} */ + type: string; + + /** + * @return {{level: string, message: string, timestamp: number, + * type: string}} The JSON representation of this entry. + */ + toJSON(): IEntryJSON; + } + + /** + * An object used to log debugging messages. Loggers use a hierarchical, + * dot-separated naming scheme. For instance, "foo" is considered the parent of + * the "foo.bar" and an ancestor of "foo.bar.baz". + * + * Each logger may be assigned a {@linkplain #setLevel log level}, which + * controls which level of messages will be reported to the + * {@linkplain #addHandler handlers} attached to this instance. If a log level + * is not explicitly set on a logger, it will inherit its parent. + * + * This class should never be directly instantiated. Instead, users should + * obtain logger references using the {@linkplain ./logging.getLogger() + * getLogger()} function. + * + * @final + */ + class Logger { + /** + * @param {string} name the name of this logger. + * @param {Level=} opt_level the initial level for this logger. + */ + constructor(name: string, opt_level?: Level); + + /** @private {string} */ + name_: string; + /** @private {Level} */ + level_: Level; + /** @private {Logger} */ + parent_: Logger; + /** @private {Set} */ + handlers_: any; + + /** @return {string} the name of this logger. */ + getName(): string; + + /** + * @param {Level} level the new level for this logger, or `null` if the logger + * should inherit its level from its parent logger. + */ + setLevel(level: Level): void; + + /** @return {Level} the log level for this logger. */ + getLevel(): Level; + + /** + * @return {!Level} the effective level for this logger. + */ + getEffectiveLevel(): Level; + + /** + * @param {!Level} level the level to check. + * @return {boolean} whether messages recorded at the given level are loggable + * by this instance. + */ + isLoggable(level: Level): boolean; + + /** + * Adds a handler to this logger. The handler will be invoked for each message + * logged with this instance, or any of its descendants. + * + * @param {function(!Entry)} handler the handler to add. + */ + addHandler(handler: any): void; + + /** + * Removes a handler from this logger. + * + * @param {function(!Entry)} handler the handler to remove. + * @return {boolean} whether a handler was successfully removed. + */ + removeHandler(handler: any): void; + + /** + * Logs a message at the given level. The message may be defined as a string + * or as a function that will return the message. If a function is provided, + * it will only be invoked if this logger's + * {@linkplain #getEffectiveLevel() effective log level} includes the given + * `level`. + * + * @param {!Level} level the level at which to log the message. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + log(level: Level, loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.SEVERE} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + severe(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.WARNING} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + warning(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.INFO} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + info(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.DEBUG} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + debug(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.FINE} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + fine(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.FINER} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + finer(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.FINEST} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + finest(loggable: string|Function): void; + } + + /** + * Maintains a collection of loggers. + * + * @final + */ + class LogManager { + /** + * Retrieves a named logger, creating it in the process. This function will + * implicitly create the requested logger, and any of its parents, if they + * do not yet exist. + * + * @param {string} name the logger's name. + * @return {!Logger} the requested logger. + */ + getLogger(name: string): Logger; + + /** + * Creates a new logger. + * + * @param {string} name the logger's name. + * @param {!Logger} parent the logger's parent. + * @return {!Logger} the new logger. + * @private + */ + createLogger_(name: string, parent: Logger): Logger; + } + } + + namespace promise { + //region Functions + + /** + * Given an array of promises, will return a promise that will be fulfilled + * with the fulfillment values of the input array's values. If any of the + * input array's promises are rejected, the returned promise will be rejected + * with the same reason. + * + * @param {!Array<(T|!ManagedPromise)>} arr An array of + * promises to wait on. + * @return {!ManagedPromise>} A promise that is + * fulfilled with an array containing the fulfilled values of the + * input array, or rejected with the same reason as the first + * rejected value. + * @template T + */ + function all(arr: Array>): Promise; + + /** + * Invokes the appropriate callback function as soon as a promised + * {@code value} is resolved. This function is similar to + * {@link webdriver.promise.when}, except it does not return a new promise. + * @param {*} value The value to observe. + * @param {Function} callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + */ + function asap(value: any, callback: Function, opt_errback?: Function): void; + + /** + * @return {!webdriver.promise.ControlFlow} The currently active control flow. + */ + function controlFlow(): ControlFlow; + + /** + * Creates a new control flow. The provided callback will be invoked as the + * first task within the new flow, with the flow as its sole argument. Returns + * a promise that resolves to the callback result. + * @param {function(!ControlFlow)} callback The entry point + * to the newly created flow. + * @return {!ManagedPromise} A promise that resolves to the callback + * result. + */ + function createFlow(callback: (flow: ControlFlow) => R): Promise; + + /** + * Determines whether a {@code value} should be treated as a promise. + * Any object whose "then" property is a function will be considered a promise. + * + * @param {*} value The value to test. + * @return {boolean} Whether the value is a promise. + */ + function isPromise(value: any): boolean; + + /** + * Tests is a function is a generator. + * @param {!Function} fn The function to test. + * @return {boolean} Whether the function is a generator. + */ + function isGenerator(fn: Function): boolean; + + /** + * Creates a promise that will be resolved at a set time in the future. + * @param {number} ms The amount of time, in milliseconds, to wait before + * resolving the promise. + * @return {!ManagedPromise} The promise. + */ + function delayed(ms: number): Promise; + + /** + * Calls a function for each element in an array, and if the function returns + * true adds the element to a new array. + * + * If the return value of the filter function is a promise, this function + * will wait for it to be fulfilled before determining whether to insert the + * element into the new array. + * + * If the filter function throws or returns a rejected promise, the promise + * returned by this function will be rejected with the same reason. Only the + * first failure will be reported; all subsequent errors will be silently + * ignored. + * + * @param {!(Array|ManagedPromise>)} arr The + * array to iterator over, or a promise that will resolve to said array. + * @param {function(this: SELF, TYPE, number, !Array): ( + * boolean|ManagedPromise)} fn The function + * to call for each element in the array. + * @param {SELF=} opt_self The object to be used as the value of 'this' within + * {@code fn}. + * @template TYPE, SELF + */ + function filter(arr: Array|Promise>, fn: (element: T, type: any, index: number, array: T[]) => any, opt_self?: any): Promise; + + /** + * Creates a new deferred object. + * @return {!webdriver.promise.Deferred} The new deferred object. + */ + function defer(): Deferred; + + /** + * Creates a promise that has been resolved with the given value. + * @param {T=} opt_value The resolved value. + * @return {!ManagedPromise} The resolved promise. + * @template T + */ + function fulfilled(opt_value?: T): Promise; + + /** + * Calls a function for each element in an array and inserts the result into a + * new array, which is used as the fulfillment value of the promise returned + * by this function. + * + * If the return value of the mapping function is a promise, this function + * will wait for it to be fulfilled before inserting it into the new array. + * + * If the mapping function throws or returns a rejected promise, the + * promise returned by this function will be rejected with the same reason. + * Only the first failure will be reported; all subsequent errors will be + * silently ignored. + * + * @param {!(Array|ManagedPromise>)} arr The + * array to iterator over, or a promise that will resolve to said array. + * @param {function(this: SELF, TYPE, number, !Array): ?} fn The + * function to call for each element in the array. This function should + * expect three arguments (the element, the index, and the array itself. + * @param {SELF=} opt_self The object to be used as the value of 'this' within + * {@code fn}. + * @template TYPE, SELF + */ + function map(arr: Array|Promise>, fn: (self: any, type: any, index: number, array: any[]) => any, opt_self?: any): Promise + + /** + * Creates a promise that has been rejected with the given reason. + * @param {*=} opt_reason The rejection reason; may be any value, but is + * usually an Error or a string. + * @return {!ManagedPromise} The rejected promise. + * @template T + */ + function rejected(opt_reason?: any): Promise; + + /** + * Wraps a function that expects a node-style callback as its final + * argument. This callback expects two arguments: an error value (which will be + * null if the call succeeded), and the success value as the second argument. + * The callback will the resolve or reject the returned promise, based on its + * arguments. + * @param {!Function} fn The function to wrap. + * @param {...?} var_args The arguments to apply to the function, excluding the + * final callback. + * @return {!ManagedPromise} A promise that will be resolved with the + * result of the provided function's callback. + */ + function checkedNodeCall(fn: Function, ...var_args: any[]): Promise; + + /** + * Consumes a {@code GeneratorFunction}. Each time the generator yields a + * promise, this function will wait for it to be fulfilled before feeding the + * fulfilled value back into {@code next}. Likewise, if a yielded promise is + * rejected, the rejection error will be passed to {@code throw}. + * + * __Example 1:__ the Fibonacci Sequence. + * + * promise.consume(function* fibonacci() { + * var n1 = 1, n2 = 1; + * for (var i = 0; i < 4; ++i) { + * var tmp = yield n1 + n2; + * n1 = n2; + * n2 = tmp; + * } + * return n1 + n2; + * }).then(function(result) { + * console.log(result); // 13 + * }); + * + * __Example 2:__ a generator that throws. + * + * promise.consume(function* () { + * yield promise.delayed(250).then(function() { + * throw Error('boom'); + * }); + * }).catch(function(e) { + * console.log(e.toString()); // Error: boom + * }); + * + * @param {!Function} generatorFn The generator function to execute. + * @param {Object=} opt_self The object to use as "this" when invoking the + * initial generator. + * @param {...*} var_args Any arguments to pass to the initial generator. + * @return {!ManagedPromise} A promise that will resolve to the + * generator's final result. + * @throws {TypeError} If the given function is not a generator. + */ + function consume(generatorFn: Function, opt_self?: any, ...var_args: any[]): Promise; + + /** + * Registers an observer on a promised {@code value}, returning a new promise + * that will be resolved when the value is. If {@code value} is not a promise, + * then the return promise will be immediately resolved. + * @param {*} value The value to observe. + * @param {Function=} opt_callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + * @return {!ManagedPromise} A new promise. + */ + function when(value: T|Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + + /** + * Returns a promise that will be resolved with the input value in a + * fully-resolved state. If the value is an array, each element will be fully + * resolved. Likewise, if the value is an object, all keys will be fully + * resolved. In both cases, all nested arrays and objects will also be + * fully resolved. All fields are resolved in place; the returned promise will + * resolve on {@code value} and not a copy. + * + * Warning: This function makes no checks against objects that contain + * cyclical references: + * + * var value = {}; + * value['self'] = value; + * promise.fullyResolved(value); // Stack overflow. + * + * @param {*} value The value to fully resolve. + * @return {!ManagedPromise} A promise for a fully resolved version + * of the input value. + */ + function fullyResolved(value: any): Promise; + + /** + * Changes the default flow to use when no others are active. + * @param {!ControlFlow} flow The new default flow. + * @throws {Error} If the default flow is not currently active. + */ + function setDefaultFlow(flow: ControlFlow): void; + + //endregion + + /** + * Error used when the computation of a promise is cancelled. + */ + class CancellationError extends Error { + /** + * @param {string=} opt_msg The cancellation message. + */ + constructor(opt_msg?: string); + } + + interface IThenable { + /** + * Cancels the computation of this promise's value, rejecting the promise in + * the process. This method is a no-op if the promise has already been + * resolved. + * + * @param {(string|Error)=} opt_reason The reason this promise is being + * cancelled. This value will be wrapped in a {@link CancellationError}. + */ + cancel(opt_reason?: string|Error): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. + * + * @param {?(function(T): (R|IThenable))=} opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param {?(function(*): (R|IThenable))=} opt_errback + * The function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + then(opt_callback?: (value: T) => R|IThenable, opt_errback?: (error: any) => R|IThenable): Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): Promise; + } + + /** + * Thenable is a promise-like object with a {@code then} method which may be + * used to schedule callbacks on a promised value. + * + * @interface + * @template T + */ + class Thenable implements IThenable { + /** + * Cancels the computation of this promise's value, rejecting the promise in + * the process. This method is a no-op if the promise has already been + * resolved. + * + * @param {(string|Error)=} opt_reason The reason this promise is being + * cancelled. This value will be wrapped in a {@link CancellationError}. + */ + cancel(opt_reason?: string|Error): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. + * + * @param {?(function(T): (R|IThenable))=} opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param {?(function(*): (R|IThenable))=} opt_errback + * The function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + then(opt_callback?: (value: T) => R|IThenable, opt_errback?: (error: any) => R|IThenable): Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): Promise; + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } finally { + * cleanUp(); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().finally(cleanUp); + * + * __Note:__ similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + * + * try { + * throw Error('one'); + * } finally { + * throw Error('two'); // Hides Error: one + * } + * + * promise.rejected(Error('one')) + * .finally(function() { + * throw Error('two'); // Hides Error: one + * }); + * + * @param {function(): (R|IThenable)} callback The function to call when + * this promise is resolved. + * @return {!ManagedPromise} A promise that will be fulfilled + * with the callback result. + * @template R + */ + finally(callback: Function): Promise; + + /** + * Adds a property to a class prototype to allow runtime checks of whether + * instances of that class implement the Thenable interface. This function + * will also ensure the prototype's {@code then} function is exported from + * compiled code. + * @param {function(new: Thenable, ...?)} ctor The + * constructor whose prototype to modify. + */ + static addImplementation(ctor: Function): void; + + /** + * Checks if an object has been tagged for implementing the Thenable + * interface as defined by {@link Thenable.addImplementation}. + * @param {*} object The object to test. + * @return {boolean} Whether the object is an implementation of the Thenable + * interface. + */ + static isImplementation(object: any): boolean; + } + + interface IFulfilledCallback { + (value: T|IThenable|Thenable|void): void; + } + + interface IRejectedCallback { + (reason: any): void; + } + + /** + * Represents the eventual value of a completed operation. Each promise may be + * in one of three states: pending, fulfilled, or rejected. Each promise starts + * in the pending state and may make a single transition to either a + * fulfilled or rejected state, at which point the promise is considered + * resolved. + * + * @implements {promise.Thenable} + * @template T + * @see http://promises-aplus.github.io/promises-spec/ + */ + class Promise implements IThenable { + /** + * @param {function( + * function((T|IThenable|Thenable)=), + * function(*=))} resolver + * Function that is invoked immediately to begin computation of this + * promise's value. The function should accept a pair of callback + * functions, one for fulfilling the promise and another for rejecting it. + * @param {ControlFlow=} opt_flow The control flow + * this instance was created under. Defaults to the currently active flow. + */ + constructor(resolver: (onFulfilled: IFulfilledCallback, onRejected: IRejectedCallback)=>void, opt_flow?: ControlFlow); + constructor(); // For angular-protractor/angular-protractor-tests.ts + + //region Methods + + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. + * @param {*} reason The reason this promise is being cancelled. If not an + * {@code Error}, one will be created using the value's string + * representation. + */ + cancel(opt_reason?: string|Error): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. This function most + * overridden by subtypes. + * + * @param opt_callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param opt_errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @return A new promise which will be resolved + * with the result of the invoked callback. + */ + then(opt_callback?: Function, opt_errback?: Function): Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *
    
    +             *   // Synchronous API:
    +             *   try {
    +             *     doSynchronousWork();
    +             *   } catch (ex) {
    +             *     console.error(ex);
    +             *   }
    +             *
    +             *   // Asynchronous promise API:
    +             *   doAsynchronousWork().thenCatch(function(ex) {
    +             *     console.error(ex);
    +             *   });
    +             * 
    + * + * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!webdriver.promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *
    
    +             *   // Synchronous API:
    +             *   try {
    +             *     doSynchronousWork();
    +             *   } finally {
    +             *     cleanUp();
    +             *   }
    +             *
    +             *   // Asynchronous promise API:
    +             *   doAsynchronousWork().thenFinally(cleanUp);
    +             * 
    + * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *
    
    +             *   try {
    +             *     throw Error('one');
    +             *   } finally {
    +             *     throw Error('two');  // Hides Error: one
    +             *   }
    +             *
    +             *   webdriver.promise.rejected(Error('one'))
    +             *       .thenFinally(function() {
    +             *         throw Error('two');  // Hides Error: one
    +             *       });
    +             * 
    + * + * + * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: Function): Promise; + + //endregion + } + + /** + * Represents a value that will be resolved at some point in the future. This + * class represents the protected "producer" half of a Promise - each Deferred + * has a {@code promise} property that may be returned to consumers for + * registering callbacks, reserving the ability to resolve the deferred to the + * producer. + * + *

    If this Deferred is rejected and there are no listeners registered before + * the next turn of the event loop, the rejection will be passed to the + * {@link webdriver.promise.ControlFlow} as an unhandled failure. + * + *

    If this Deferred is cancelled, the cancellation reason will be forward to + * the Deferred's canceller function (if provided). The canceller may return a + * truth-y value to override the reason provided for rejection. + * + * @extends {webdriver.promise.Promise} + */ + class Deferred extends Promise { + //region Constructors + + /** + * + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow + * this instance was created under. This should only be provided during + * unit tests. + * @constructor + */ + constructor(opt_flow?: ControlFlow); + + //endregion + + static State_: { + BLOCKED: number; + PENDING: number; + REJECTED: number; + RESOLVED: number; + }; + + //region Properties + + /** + * The consumer promise for this instance. Provides protected access to the + * callback registering functions. + * @type {!webdriver.promise.Promise} + */ + promise: Promise; + + //endregion + + //region Methods + + /** + * Rejects this promise. If the error is itself a promise, this instance will + * be chained to it and be rejected with the error's resolved value. + * @param {*=} opt_error The rejection reason, typically either a + * {@code Error} or a {@code string}. + */ + reject(opt_error?: any): void; + errback(opt_error?: any): void; + + /** + * Resolves this promise with the given value. If the value is itself a + * promise and not a reference to this deferred, this instance will wait for + * it before resolving. + * @param {*=} opt_value The resolved value. + */ + fulfill(opt_value?: T): void; + + /** + * Removes all of the listeners previously registered on this deferred. + * @throws {Error} If this deferred has already been resolved. + */ + removeAll(): void; + + //endregion + } + + interface IControlFlowTimer { + clearInterval: (ms: number) => void; + clearTimeout: (ms: number) => void; + setInterval: (fn: Function, ms: number) => number; + setTimeout: (fn: Function, ms: number) => number; + } + + /** + * Handles the execution of scheduled tasks, each of which may be an + * asynchronous operation. The control flow will ensure tasks are executed in + * the ordered scheduled, starting each task only once those before it have + * completed. + * + * Each task scheduled within this flow may return a + * {@link webdriver.promise.Promise} to indicate it is an asynchronous + * operation. The ControlFlow will wait for such promises to be resolved before + * marking the task as completed. + * + * Tasks and each callback registered on a {@link webdriver.promise.Promise} + * will be run in their own ControlFlow frame. Any tasks scheduled within a + * frame will take priority over previously scheduled tasks. Furthermore, if any + * of the tasks in the frame fail, the remainder of the tasks in that frame will + * be discarded and the failure will be propagated to the user through the + * callback/task's promised result. + * + * Each time a ControlFlow empties its task queue, it will fire an + * {@link webdriver.promise.ControlFlow.EventType.IDLE IDLE} event. Conversely, + * whenever the flow terminates due to an unhandled error, it will remove all + * remaining tasks in its queue and fire an + * {@link webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION + * UNCAUGHT_EXCEPTION} event. If there are no listeners registered with the + * flow, the error will be rethrown to the global error handler. + * + * @extends {EventEmitter} + * @final + */ + class ControlFlow extends EventEmitter { + /** + * @constructor + */ + constructor(); + + /** + * Events that may be emitted by an {@link webdriver.promise.ControlFlow}. + * @enum {string} + */ + static EventType: { + /** Emitted when all tasks have been successfully executed. */ + IDLE: string; + + /** Emitted when a ControlFlow has been reset. */ + RESET: string; + + /** Emitted whenever a new task has been scheduled. */ + SCHEDULE_TASK: string; + + /** + * Emitted whenever a control flow aborts due to an unhandled promise + * rejection. This event will be emitted along with the offending rejection + * reason. Upon emitting this event, the control flow will empty its task + * queue and revert to its initial state. + */ + UNCAUGHT_EXCEPTION: string; + }; + + /** + * Returns a string representation of this control flow, which is its current + * {@link #getSchedule() schedule}, sans task stack traces. + * @return {string} The string representation of this contorl flow. + * @override + */ + toString(): string; + + /** + * Resets this instance, clearing its queue and removing all event listeners. + */ + reset(): void; + + /** + * Generates an annotated string describing the internal state of this control + * flow, including the currently executing as well as pending tasks. If + * {@code opt_includeStackTraces === true}, the string will include the + * stack trace from when each task was scheduled. + * @param {string=} opt_includeStackTraces Whether to include the stack traces + * from when each task was scheduled. Defaults to false. + * @return {string} String representation of this flow's internal state. + */ + getSchedule(opt_includeStackTraces?: boolean): string; + + /** + * Schedules a task for execution. If there is nothing currently in the + * queue, the task will be executed in the next turn of the event loop. If + * the task function is a generator, the task will be executed using + * {@link webdriver.promise.consume}. + * + * @param {function(): (T|promise.Promise)} fn The function to + * call to start the task. If the function returns a + * {@link webdriver.promise.Promise}, this instance will wait for it to be + * resolved before starting the next task. + * @param {string=} opt_description A description of the task. + * @return {!promise.Promise} A promise that will be resolved + * with the result of the action. + * @template T + */ + execute(fn: ()=>(T|Promise), opt_description?: string): Promise; + + /** + * Inserts a {@code setTimeout} into the command queue. This is equivalent to + * a thread sleep in a synchronous programming language. + * + * @param {number} ms The timeout delay, in milliseconds. + * @param {string=} opt_description A description to accompany the timeout. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the result of the action. + */ + timeout(ms: number, opt_description?: string): Promise; + + /** + * Schedules a task that shall wait for a condition to hold. Each condition + * function may return any value, but it will always be evaluated as a boolean. + * + * Condition functions may schedule sub-tasks with this instance, however, + * their execution time will be factored into whether a wait has timed out. + * + * In the event a condition returns a Promise, the polling loop will wait for + * it to be resolved before evaluating whether the condition has been satisfied. + * The resolution time for a promise is factored into whether a wait has timed + * out. + * + * If the condition function throws, or returns a rejected promise, the + * wait task will fail. + * + * If the condition is defined as a promise, the flow will wait for it to + * settle. If the timeout expires before the promise settles, the promise + * returned by this function will be rejected. + * + * If this function is invoked with `timeout === 0`, or the timeout is omitted, + * the flow will wait indefinitely for the condition to be satisfied. + * + * @param {(!promise.Promise|function())} condition The condition to poll, + * or a promise to wait on. + * @param {number=} opt_timeout How long to wait, in milliseconds, for the + * condition to hold before timing out. If omitted, the flow will wait + * indefinitely. + * @param {string=} opt_message An optional error message to include if the + * wait times out; defaults to the empty string. + * @return {!promise.Promise} A promise that will be fulfilled + * when the condition has been satisified. The promise shall be rejected if + * the wait times out waiting for the condition. + * @throws {TypeError} If condition is not a function or promise or if timeout + * is not a number >= 0. + * @template T + */ + wait(condition: Promise|Function, opt_timeout?: number, opt_message?: string): Promise; + } + } + + namespace until { + /** + * Defines a condition to + */ + class Condition { + /** + * @param {string} message A descriptive error message. Should complete the + * sentence "Waiting [...]" + * @param {function(!webdriver.WebDriver): OUT} fn The condition function to + * evaluate on each iteration of the wait loop. + * @constructor + */ + constructor(message: string, fn: (webdriver: WebDriver) => any); + + /** @return {string} A description of this condition. */ + description(): string; + + /** @type {function(!webdriver.WebDriver): OUT} */ + fn(webdriver: WebDriver): any; + } + + /** + * Creates a condition that will wait until the input driver is able to switch + * to the designated frame. The target frame may be specified as + * + * 1. a numeric index into + * [window.frames](https://developer.mozilla.org/en-US/docs/Web/API/Window.frames) + * for the currently selected frame. + * 2. a {@link ./webdriver.WebElement}, which must reference a FRAME or IFRAME + * element on the current page. + * 3. a locator which may be used to first locate a FRAME or IFRAME on the + * current page before attempting to switch to it. + * + * Upon successful resolution of this condition, the driver will be left + * focused on the new frame. + * + * @param {!(number|./webdriver.WebElement|By| + * function(!./webdriver.WebDriver): !./webdriver.WebElement)} frame + * The frame identifier. + * @return {!Condition} A new condition. + */ + function ableToSwitchToFrame(frame: number|WebElement|By|((webdriver: WebDriver)=>WebElement)): Condition; + + /** + * Creates a condition that waits for an alert to be opened. Upon success, the + * returned promise will be fulfilled with the handle for the opened alert. + * + * @return {!Condition} The new condition. + */ + function alertIsPresent(): Condition; + + /** + * Creates a condition that will wait for the given element to be disabled. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isEnabled + */ + function elementIsDisabled(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be enabled. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isEnabled + */ + function elementIsEnabled(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be deselected. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isSelected + */ + function elementIsNotSelected(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be in the DOM, + * yet not visible to the user. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isDisplayed + */ + function elementIsNotVisible(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be selected. + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isSelected + */ + function elementIsSelected(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to become visible. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isDisplayed + */ + function elementIsVisible(element: WebElement): Condition; + + /** + * Creates a condition that will loop until an element is + * {@link ./webdriver.WebDriver#findElement found} with the given locator. + * + * @param {!(By|Function)} locator The locator to use. + * @return {!until.Condition.} The new condition. + */ + function elementLocated(locator: By|Function): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link webdriver.WebDriver#getText visible text} to contain the given + * substring. + * + * @param {!webdriver.WebElement} element The element to test. + * @param {string} substr The substring to search for. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#getText + */ + function elementTextContains(element: WebElement, substr: string): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link webdriver.WebDriver#getText visible text} to match the given + * {@code text} exactly. + * + * @param {!webdriver.WebElement} element The element to test. + * @param {string} text The expected text. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#getText + */ + function elementTextIs(element: WebElement, text: string): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link webdriver.WebDriver#getText visible text} to match a regular + * expression. + * + * @param {!webdriver.WebElement} element The element to test. + * @param {!RegExp} regex The regular expression to test against. + * @return {!until.Condition} The new condition. + * @see webdriver.WebDriver#getText + */ + function elementTextMatches(element: WebElement, regex: RegExp): Condition; + + /** + * Creates a condition that will loop until at least one element is + * {@link webdriver.WebDriver#findElement found} with the given locator. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator + * to use. + * @return {!until.Condition.>} The new + * condition. + */ + function elementsLocated(locator: By|Function): Condition; + + /** + * Creates a condition that will wait for the given element to become stale. An + * element is considered stale once it is removed from the DOM, or a new page + * has loaded. + * + * @param {!webdriver.WebElement} element The element that should become stale. + * @return {!until.Condition} The new condition. + */ + function stalenessOf(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the current page's title to contain + * the given substring. + * + * @param {string} substr The substring that should be present in the page + * title. + * @return {!until.Condition.} The new condition. + */ + function titleContains(substr: string): Condition; + + /** + * Creates a condition that will wait for the current page's title to match the + * given value. + * + * @param {string} title The expected page title. + * @return {!until.Condition} The new condition. + */ + function titleIs(title: string): Condition; + + /** + * Creates a condition that will wait for the current page's title to match the + * given regular expression. + * + * @param {!RegExp} regex The regular expression to test against. + * @return {!until.Condition.} The new condition. + */ + function titleMatches(regex: RegExp): Condition; + } + + interface ILocation { + x: number; + y: number; + } + + interface ISize { + width: number; + height: number; + } + + /** + * Representations of pressable keys that aren't text. These are stored in + * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to + * http://www.google.com.au/search?&q=unicode+pua&btnG=Search + * + * @enum {string} + */ + enum Button { + LEFT, + MIDDLE, + RIGHT, + } + + /** + * Representations of pressable keys that aren't text. These are stored in + * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to + * http://www.google.com.au/search?&q=unicode+pua&btnG=Search + * + * @enum {string} + */ + enum Key { + NULL, + CANCEL, // ^break + HELP, + BACK_SPACE, + TAB, + CLEAR, + RETURN, + ENTER, + SHIFT, + CONTROL, + ALT, + PAUSE, + ESCAPE, + SPACE, + PAGE_UP, + PAGE_DOWN, + END, + HOME, + ARROW_LEFT, + LEFT, + ARROW_UP, + UP, + ARROW_RIGHT, + RIGHT, + ARROW_DOWN, + DOWN, + INSERT, + DELETE, + SEMICOLON, + EQUALS, + + NUMPAD0, // number pad keys + NUMPAD1, + NUMPAD2, + NUMPAD3, + NUMPAD4, + NUMPAD5, + NUMPAD6, + NUMPAD7, + NUMPAD8, + NUMPAD9, + MULTIPLY, + ADD, + SEPARATOR, + SUBTRACT, + DECIMAL, + DIVIDE, + + F1, // function keys + F2, + F3, + F4, + F5, + F6, + F7, + F8, + F9, + F10, + F11, + F12, + + COMMAND, // Apple command key + META // alias for Windows key + + } + + /** + * Class for defining sequences of complex user interactions. Each sequence + * will not be executed until {@link #perform} is called. + * + * Example: + * + * new ActionSequence(driver). + * keyDown(Key.SHIFT). + * click(element1). + * click(element2). + * dragAndDrop(element3, element4). + * keyUp(Key.SHIFT). + * perform(); + * + */ + class ActionSequence { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The driver instance to use. + * @constructor + */ + constructor(driver: WebDriver); + + //endregion + + //region Methods + + /** + * Executes this action sequence. + * @return {!webdriver.promise.Promise} A promise that will be resolved once + * this sequence has completed. + */ + perform(): webdriver.promise.Promise; + + /** + * Moves the mouse. The location to move to may be specified in terms of the + * mouse's current location, an offset relative to the top-left corner of an + * element, or an element (in which case the middle of the element is used). + * + * @param {(!./webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, as either another WebElement or an offset in + * pixels. + * @param {{x: number, y: number}=} opt_offset If the target {@code location} + * is defined as a {@link ./webdriver.WebElement}, this parameter defines + * an offset within that element. The offset should be specified in pixels + * relative to the top-left corner of the element's bounding box. If + * omitted, the element's center will be used as the target offset. + * @return {!ActionSequence} A self reference. + */ + mouseMove(location: WebElement|ILocation, opt_offset?: ILocation): ActionSequence; + + /** + * Presses a mouse button. The mouse button will not be released until + * {@link #mouseUp} is called, regardless of whether that call is made in this + * sequence or another. The behavior for out-of-order events (e.g. mouseDown, + * click) is undefined. + * + * If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + * + * sequence.mouseMove(element).mouseDown() + * + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link input.Button.LEFT} if neither an element nor + * button is specified. + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!ActionSequence} A self reference. + */ + mouseDown(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; + + /** + * Releases a mouse button. Behavior is undefined for calling this function + * without a previous call to {@link #mouseDown}. + * + * If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + * + * sequence.mouseMove(element).mouseUp() + * + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link input.Button.LEFT} if neither an element nor + * button is specified. + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!ActionSequence} A self reference. + */ + mouseUp(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; + + /** + * Convenience function for performing a "drag and drop" manuever. The target + * element may be moved to the location of another element, or by an offset (in + * pixels). + * + * @param {!./webdriver.WebElement} element The element to drag. + * @param {(!./webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, either as another WebElement or an offset in + * pixels. + * @return {!ActionSequence} A self reference. + */ + dragAndDrop(element: WebElement, location: WebElement|ILocation): ActionSequence; + + /** + * Clicks a mouse button. + * + * If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + * + * sequence.mouseMove(element).click() + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link input.Button.LEFT} if neither an element nor + * button is specified. + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!ActionSequence} A self reference. + */ + click(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; + + /** + * Double-clicks a mouse button. + * + * If an element is provided, the mouse will first be moved to the center of + * that element. This is equivalent to: + * + * sequence.mouseMove(element).doubleClick() + * + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link input.Button.LEFT} if neither an element nor + * button is specified. + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!ActionSequence} A self reference. + */ + doubleClick(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; + + /** + * Performs a modifier key press. The modifier key is not released + * until {@link #keyUp} or {@link #sendKeys} is called. The key press will be + * targetted at the currently focused element. + * @param {!webdriver.Key} key The modifier key to push. Must be one of + * {ALT, CONTROL, SHIFT, COMMAND, META}. + * @return {!webdriver.ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + keyDown(key: Key): ActionSequence; + + /** + * Performs a modifier key release. The release is targetted at the currently + * focused element. + * @param {!webdriver.Key} key The modifier key to release. Must be one of + * {ALT, CONTROL, SHIFT, COMMAND, META}. + * @return {!webdriver.ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + keyUp(key: Key): ActionSequence; + + /** + * Simulates typing multiple keys. Each modifier key encountered in the + * sequence will not be released until it is encountered again. All key events + * will be targetted at the currently focused element. + * @param {...(string|!webdriver.Key|!Array.<(string|!webdriver.Key)>)} var_args + * The keys to type. + * @return {!webdriver.ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + sendKeys(...var_args: Array): ActionSequence; + + //endregion + } + + + /** + * Class for defining sequences of user touch interactions. Each sequence + * will not be executed until {@link #perform} is called. + * + * Example: + * + * new webdriver.TouchSequence(driver). + * tapAndHold({x: 0, y: 0}). + * move({x: 3, y: 4}). + * release({x: 10, y: 10}). + * perform(); + */ + class TouchSequence { + /* + * @param {!webdriver.WebDriver} driver The driver instance to use. + * @constructor + */ + constructor(driver: WebDriver); + + + /** + * Executes this action sequence. + * @return {!webdriver.promise.Promise} A promise that will be resolved once + * this sequence has completed. + */ + perform(): webdriver.promise.Promise; + + + /** + * Taps an element. + * + * @param {!webdriver.WebElement} elem The element to tap. + * @return {!webdriver.TouchSequence} A self reference. + */ + tap(elem: WebElement): TouchSequence; + + + /** + * Double taps an element. + * + * @param {!webdriver.WebElement} elem The element to double tap. + * @return {!webdriver.TouchSequence} A self reference. + */ + doubleTap(elem: WebElement): TouchSequence; + + + /** + * Long press on an element. + * + * @param {!webdriver.WebElement} elem The element to long press. + * @return {!webdriver.TouchSequence} A self reference. + */ + longPress(elem: WebElement): TouchSequence; + + + /** + * Touch down at the given location. + * + * @param {{ x: number, y: number }} location The location to touch down at. + * @return {!webdriver.TouchSequence} A self reference. + */ + tapAndHold(location: ILocation): TouchSequence; + + + /** + * Move a held {@linkplain #tapAndHold touch} to the specified location. + * + * @param {{x: number, y: number}} location The location to move to. + * @return {!webdriver.TouchSequence} A self reference. + */ + move(location: ILocation): TouchSequence; + + + /** + * Release a held {@linkplain #tapAndHold touch} at the specified location. + * + * @param {{x: number, y: number}} location The location to release at. + * @return {!webdriver.TouchSequence} A self reference. + */ + release(location: ILocation): TouchSequence; + + + /** + * Scrolls the touch screen by the given offset. + * + * @param {{x: number, y: number}} offset The offset to scroll to. + * @return {!webdriver.TouchSequence} A self reference. + */ + scroll(offset: IOffset): TouchSequence; + + /** + * Scrolls the touch screen, starting on `elem` and moving by the specified + * offset. + * + * @param {!webdriver.WebElement} elem The element where scroll starts. + * @param {{x: number, y: number}} offset The offset to scroll to. + * @return {!webdriver.TouchSequence} A self reference. + */ + scrollFromElement(elem: WebElement, offset: IOffset): TouchSequence; + + /** + * Flick, starting anywhere on the screen, at speed xspeed and yspeed. + * + * @param {{xspeed: number, yspeed: number}} speed The speed to flick in each + direction, in pixels per second. + * @return {!webdriver.TouchSequence} A self reference. + */ + flick(speed: ISpeed): TouchSequence; + + /** + * Flick starting at elem and moving by x and y at specified speed. + * + * @param {!webdriver.WebElement} elem The element where flick starts. + * @param {{x: number, y: number}} offset The offset to flick to. + * @param {number} speed The speed to flick at in pixels per second. + * @return {!webdriver.TouchSequence} A self reference. + */ + flickElement(elem: WebElement, offset: IOffset, speed: number): TouchSequence; + } + + interface IOffset { + x: number; + y: number; + } + + interface ISpeed { + xspeed: number; + yspeed: number; + } + + /** + * Represents a modal dialog such as {@code alert}, {@code confirm}, or + * {@code prompt}. Provides functions to retrieve the message displayed with + * the alert, accept or dismiss the alert, and set the response text (in the + * case of {@code prompt}). + */ + class Alert { + /** + * @param {!WebDriver} driver The driver controlling the browser this alert + * is attached to. + * @param {string} text The message text displayed with this alert. + */ + constructor(driver: WebDriver, text: string); + + //region Methods + + /** + * Retrieves the message text displayed with this alert. For instance, if the + * alert were opened with alert("hello"), then this would return "hello". + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * text displayed with this alert. + */ + getText(): webdriver.promise.Promise; + + /** + * Sets the username and password in an alert prompting for credentials (such + * as a Basic HTTP Auth prompt). This method will implicitly + * {@linkplain #accept() submit} the dialog. + * + * @param {string} username The username to send. + * @param {string} password The password to send. + * @return {!promise.Promise} A promise that will be resolved when this + * command has completed. + */ + authenticateAs(username: string, password: string): webdriver.promise.Promise; + + /** + * Accepts this alert. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * this command has completed. + */ + accept(): webdriver.promise.Promise; + + /** + * Dismisses this alert. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * this command has completed. + */ + dismiss(): webdriver.promise.Promise; + + /** + * Sets the response text on this alert. This command will return an error if + * the underlying alert does not support response text (e.g. window.alert and + * window.confirm). + * @param {string} text The text to set. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * this command has completed. + */ + sendKeys(text: string): webdriver.promise.Promise; + + //endregion + + } + + /** + * AlertPromise is a promise that will be fulfilled with an Alert. This promise + * serves as a forward proxy on an Alert, allowing calls to be scheduled + * directly on this instance before the underlying Alert has been fulfilled. In + * other words, the following two statements are equivalent: + * + * driver.switchTo().alert().dismiss(); + * driver.switchTo().alert().then(function(alert) { + * return alert.dismiss(); + * }); + * + * @implements {promise.Thenable.} + * @final + */ + class AlertPromise extends Alert { + /** + * @param {!WebDriver} driver The driver controlling the browser this + * alert is attached to. + * @param {!promise.Thenable} alert A thenable + * that will be fulfilled with the promised alert. + */ + constructor(driver: WebDriver, alert: webdriver.promise.Promise); + } + + /** @deprecated Use {@link error.UnexpectedAlertOpenError} instead. */ + class UnhandledAlertError extends webdriver.error.UnexpectedAlertOpenError { + } + + /** + * Recognized browser names. + * @enum {string} + */ + interface IBrowser { + ANDROID: string; + CHROME: string; + EDGE: string; + FIREFOX: string; + IE: string; + INTERNET_EXPLORER: string; + IPAD: string; + IPHONE: string; + OPERA: string; + PHANTOM_JS: string; + SAFARI: string; + HTMLUNIT: string; + } + + var Browser: IBrowser; + + interface ProxyConfig { + proxyType: string; + proxyAutoconfigUrl?: string; + ftpProxy?: string; + httpProxy?: string; + sslProxy?: string; + noProxy?: string; + } + + /** + * Creates new {@link webdriver.WebDriver WebDriver} instances. The environment + * variables listed below may be used to override a builder's configuration, + * allowing quick runtime changes. + * + * - {@code SELENIUM_BROWSER}: defines the target browser in the form + * {@code browser[:version][:platform]}. + * + * - {@code SELENIUM_REMOTE_URL}: defines the remote URL for all builder + * instances. This environment variable should be set to a fully qualified + * URL for a WebDriver server (e.g. http://localhost:4444/wd/hub). This + * option always takes precedence over {@code SELENIUM_SERVER_JAR}. + * + * - {@code SELENIUM_SERVER_JAR}: defines the path to the + * + * standalone Selenium server jar to use. The server will be started the + * first time a WebDriver instance and be killed when the process exits. + * + * Suppose you had mytest.js that created WebDriver with + * + * var driver = new webdriver.Builder() + * .forBrowser('chrome') + * .build(); + * + * This test could be made to use Firefox on the local machine by running with + * `SELENIUM_BROWSER=firefox node mytest.js`. Rather than change the code to + * target Google Chrome on a remote machine, you can simply set the + * `SELENIUM_BROWSER` and `SELENIUM_REMOTE_URL` environment variables: + * + * SELENIUM_BROWSER=chrome:36:LINUX \ + * SELENIUM_REMOTE_URL=http://www.example.com:4444/wd/hub \ + * node mytest.js + * + * You could also use a local copy of the standalone Selenium server: + * + * SELENIUM_BROWSER=chrome:36:LINUX \ + * SELENIUM_SERVER_JAR=/path/to/selenium-server-standalone.jar \ + * node mytest.js + */ + class Builder { + + //region Constructors + + /** + * @constructor + */ + constructor(); + + //endregion + + //region Methods + + /** + * Configures this builder to ignore any environment variable overrides and to + * only use the configuration specified through this instance's API. + * + * @return {!Builder} A self reference. + */ + disableEnvironmentOverrides(): Builder; + + /** + * Creates a new WebDriver client based on this builder's current + * configuration. + * + * While this method will immediately return a new WebDriver instance, any + * commands issued against it will be deferred until the associated browser + * has been fully initialized. Users may call {@link #buildAsync()} to obtain + * a promise that will not be fulfilled until the browser has been created + * (the difference is purely in style). + * + * @return {!webdriver.WebDriver} A new WebDriver instance. + * @throws {Error} If the current configuration is invalid. + * @see #buildAsync() + */ + build(): WebDriver; + + /** + * Creates a new WebDriver client based on this builder's current + * configuration. This method returns a promise that will not be fulfilled + * until the new browser session has been fully initialized. + * + * __Note:__ this method is purely a convenience wrapper around + * {@link #build()}. + * + * @return {!promise.Promise} A promise that will be + * fulfilled with the newly created WebDriver instance once the browser + * has been fully initialized. + * @see #build() + */ + buildAsync(): webdriver.promise.Promise; + + /** + * Configures the target browser for clients created by this instance. + * Any calls to {@link #withCapabilities} after this function will + * overwrite these settings. + * + *

    You may also define the target browser using the {@code SELENIUM_BROWSER} + * environment variable. If set, this environment variable should be of the + * form {@code browser[:[version][:platform]]}. + * + * @param {(string|webdriver.Browser)} name The name of the target browser; + * common defaults are available on the {@link webdriver.Browser} enum. + * @param {string=} opt_version A desired version; may be omitted if any + * version should be used. + * @param {string=} opt_platform The desired platform; may be omitted if any + * version may be used. + * @return {!Builder} A self reference. + */ + forBrowser(name: string, opt_version?: string, opt_platform?: string): Builder; + + /** + * Returns the base set of capabilities this instance is currently configured + * to use. + * @return {!webdriver.Capabilities} The current capabilities for this builder. + */ + getCapabilities(): Capabilities; + + /** + * @return {string} The URL of the WebDriver server this instance is configured + * to use. + */ + getServerUrl(): string; + + /** + * @return {?string} The URL of the proxy server to use for the WebDriver's + * HTTP connections, or `null` if not set. + */ + getWebDriverProxy(): string; + + /** + * Sets the default action to take with an unexpected alert before returning + * an error. + * @param {string} beahvior The desired behavior; should be "accept", "dismiss", + * or "ignore". Defaults to "dismiss". + * @return {!Builder} A self reference. + */ + setAlertBehavior(behavior: string): Builder; + + /** + * Sets Chrome-specific options for drivers created by this builder. Any + * logging or proxy settings defined on the given options will take precedence + * over those set through {@link #setLoggingPrefs} and {@link #setProxy}, + * respectively. + * + * @param {!chrome.Options} options The ChromeDriver options to use. + * @return {!Builder} A self reference. + */ + setChromeOptions(options: chrome.Options): Builder; + + /** + * Sets the control flow that created drivers should execute actions in. If + * the flow is never set, or is set to {@code null}, it will use the active + * flow at the time {@link #build()} is called. + * @param {webdriver.promise.ControlFlow} flow The control flow to use, or + * {@code null} to + * @return {!Builder} A self reference. + */ + setControlFlow(flow: webdriver.promise.ControlFlow): Builder; + + /** + * Set {@linkplain edge.Options options} specific to Microsoft's Edge browser + * for drivers created by this builder. Any proxy settings defined on the + * given options will take precedence over those set through + * {@link #setProxy}. + * + * @param {!edge.Options} options The MicrosoftEdgeDriver options to use. + * @return {!Builder} A self reference. + */ + setEdgeOptions(options: edge.Options): Builder; + + /** + * Sets whether native events should be used. + * @param {boolean} enabled Whether to enable native events. + * @return {!Builder} A self reference. + */ + setEnableNativeEvents(enabled: boolean): Builder; + + /** + * Sets Firefox-specific options for drivers created by this builder. Any + * logging or proxy settings defined on the given options will take precedence + * over those set through {@link #setLoggingPrefs} and {@link #setProxy}, + * respectively. + * + * @param {!firefox.Options} options The FirefoxDriver options to use. + * @return {!Builder} A self reference. + */ + setFirefoxOptions(options: firefox.Options): Builder; + + /** + * Set Internet Explorer specific {@linkplain ie.Options options} for drivers + * created by this builder. Any proxy settings defined on the given options + * will take precedence over those set through {@link #setProxy}. + * + * @param {!ie.Options} options The IEDriver options to use. + * @return {!Builder} A self reference. + */ + setIeOptions(options: ie.Options): Builder; + + /** + * Sets the logging preferences for the created session. Preferences may be + * changed by repeated calls, or by calling {@link #withCapabilities}. + * @param {!(webdriver.logging.Preferences|Object.)} prefs The + * desired logging preferences. + * @return {!Builder} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences|Object): Builder; + + /** + * Sets Opera specific {@linkplain opera.Options options} for drivers created + * by this builder. Any logging or proxy settings defined on the given options + * will take precedence over those set through {@link #setLoggingPrefs} and + * {@link #setProxy}, respectively. + * + * @param {!opera.Options} options The OperaDriver options to use. + * @return {!Builder} A self reference. + */ + setOperaOptions(options: opera.Options): Builder; + + /** + * Sets the proxy configuration to use for WebDriver clients created by this + * builder. Any calls to {@link #withCapabilities} after this function will + * overwrite these settings. + * @param {!capabilities.ProxyConfig} config The configuration to use. + * @return {!Builder} A self reference. + */ + setProxy(config: webdriver.ProxyConfig): Builder; + + /** + * Sets Safari specific {@linkplain safari.Options options} for drivers + * created by this builder. Any logging settings defined on the given options + * will take precedence over those set through {@link #setLoggingPrefs}. + * + * @param {!safari.Options} options The Safari options to use. + * @return {!Builder} A self reference. + */ + setSafari(options: safari.Options): Builder; + + /** + * Sets how elements should be scrolled into view for interaction. + * @param {number} behavior The desired scroll behavior: either 0 to align with + * the top of the viewport or 1 to align with the bottom. + * @return {!Builder} A self reference. + */ + setScrollBehavior(behavior: number): Builder; + + /** + * Sets the URL of a remote WebDriver server to use. Once a remote URL has been + * specified, the builder direct all new clients to that server. If this method + * is never called, the Builder will attempt to create all clients locally. + * + *

    As an alternative to this method, you may also set the + * {@code SELENIUM_REMOTE_URL} environment variable. + * + * @param {string} url The URL of a remote server to use. + * @return {!Builder} A self reference. + */ + usingServer(url: string): Builder; + + /** + * Sets the URL of the proxy to use for the WebDriver's HTTP connections. + * If this method is never called, the Builder will create a connection + * without a proxy. + * + * @param {string} proxy The URL of a proxy to use. + * @return {!Builder} A self reference. + */ + usingWebDriverProxy(proxy: string): Builder; + + /** + * Sets the desired capabilities when requesting a new session. This will + * overwrite any previously set capabilities. + * @param {!(Object|webdriver.Capabilities)} capabilities The desired + * capabilities for a new session. + * @return {!Builder} A self reference. + */ + withCapabilities(capabilities: Object|Capabilities): Builder; + + //endregion + } + + /** + * Describes a mechanism for locating an element on the page. + * @final + */ + class By { + + /** + * @param {string} using the name of the location strategy to use. + * @param {string} value the value to search for. + */ + constructor(using: string, value: string); + + /** + * Locates elements that have a specific class name. + * + * @param {string} name The class name to search for. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes + * @see http://www.w3.org/TR/CSS2/selector.html#class-html + */ + static className(name: string): By; + + /** + * Locates elements using a CSS selector. + * + * @param {string} selector The CSS selector to use. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/CSS2/selector.html + */ + static css(selector: string): By; + + /** + * Locates eleemnts by the ID attribute. This locator uses the CSS selector + * `*[id="$ID"]`, _not_ `document.getElementById`. + * + * @param {string} id The ID to search for. + * @return {!By} The new locator. + */ + static id(id: string): By; + + /** + * Locates link elements whose + * {@linkplain webdriver.WebElement#getText visible text} matches the given + * string. + * + * @param {string} text The link text to search for. + * @return {!By} The new locator. + */ + static linkText(text: string): By; + + /** + * Locates an elements by evaluating a + * {@linkplain webdriver.WebDriver#executeScript JavaScript expression}. + * The result of this expression must be an element or list of elements. + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {function(!./webdriver.WebDriver): !./promise.Promise} + * A new JavaScript-based locator function. + */ + static js(script: string|Function, ...var_args: Array): (webdriver: webdriver.WebDriver) => webdriver.promise.Promise; + + /** + * Locates elements whose `name` attribute has the given value. + * + * @param {string} name The name attribute to search for. + * @return {!By} The new locator. + */ + static name(name: string): By; + + /** + * Locates link elements whose + * {@linkplain webdriver.WebElement#getText visible text} contains the given + * substring. + * + * @param {string} text The substring to check for in a link's visible text. + * @return {!By} The new locator. + */ + static partialLinkText(text: string): By; + + /** + * Locates elements with a given tag name. + * + * @param {string} name The tag name to search for. + * @return {!By} The new locator. + * @deprecated Use {@link By.css() By.css(tagName)} instead. + */ + static tagName(name: string): By; + + /** + * Locates elements matching a XPath selector. Care should be taken when + * using an XPath selector with a {@link webdriver.WebElement} as WebDriver + * will respect the context in the specified in the selector. For example, + * given the selector `//div`, WebDriver will search from the document root + * regardless of whether the locator was used with a WebElement. + * + * @param {string} xpath The XPath selector to use. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/xpath/ + */ + static xpath(xpath: string): By; + + /** @override */ + toString(): string; + } + + /** + * Short-hand expressions for the primary element locator strategies. + * For example the following two statements are equivalent: + * + * var e1 = driver.findElement(webdriver.By.id('foo')); + * var e2 = driver.findElement({id: 'foo'}); + * + * Care should be taken when using JavaScript minifiers (such as the + * Closure compiler), as locator hashes will always be parsed using + * the un-obfuscated properties listed. + * + * @typedef {( + * {className: string}| + * {css: string}| + * {id: string}| + * {js: string}| + * {linkText: string}| + * {name: string}| + * {partialLinkText: string}| + * {tagName: string}| + * {xpath: string})} + */ + type ByHash = {className: string}| + {css: string}| + {id: string}| + {js: string}| + {linkText: string}| + {name: string}| + {partialLinkText: string}| + {tagName: string}| + {xpath: string}; + + /** + * Common webdriver capability keys. + * @enum {string} + */ + interface ICapability { + + /** + * Indicates whether a driver should accept all SSL certs by default. This + * capability only applies when requesting a new session. To query whether + * a driver can handle insecure SSL certs, see + * {@link webdriver.Capability.SECURE_SSL}. + */ + ACCEPT_SSL_CERTS: string; + + + /** + * The browser name. Common browser names are defined in the + * {@link webdriver.Browser} enum. + */ + BROWSER_NAME: string; + + /** + * Defines how elements should be scrolled into the viewport for interaction. + * This capability will be set to zero (0) if elements are aligned with the + * top of the viewport, or one (1) if aligned with the bottom. The default + * behavior is to align with the top of the viewport. + */ + ELEMENT_SCROLL_BEHAVIOR: string; + + /** + * Whether the driver is capable of handling modal alerts (e.g. alert, + * confirm, prompt). To define how a driver should handle alerts, + * use {@link webdriver.Capability.UNEXPECTED_ALERT_BEHAVIOR}. + */ + HANDLES_ALERTS: string; + + /** + * Key for the logging driver logging preferences. + */ + LOGGING_PREFS: string; + + /** + * Whether this session generates native events when simulating user input. + */ + NATIVE_EVENTS: string; + + /** + * Describes the platform the browser is running on. Will be one of + * ANDROID, IOS, LINUX, MAC, UNIX, or WINDOWS. When requesting a + * session, ANY may be used to indicate no platform preference (this is + * semantically equivalent to omitting the platform capability). + */ + PLATFORM: string; + + /** + * Describes the proxy configuration to use for a new WebDriver session. + */ + PROXY: string; + + /** Whether the driver supports changing the brower's orientation. */ + ROTATABLE: string; + + /** + * Whether a driver is only capable of handling secure SSL certs. To request + * that a driver accept insecure SSL certs by default, use + * {@link webdriver.Capability.ACCEPT_SSL_CERTS}. + */ + SECURE_SSL: string; + + /** Whether the driver supports manipulating the app cache. */ + SUPPORTS_APPLICATION_CACHE: string; + + /** Whether the driver supports locating elements with CSS selectors. */ + SUPPORTS_CSS_SELECTORS: string; + + /** Whether the browser supports JavaScript. */ + SUPPORTS_JAVASCRIPT: string; + + /** Whether the driver supports controlling the browser's location info. */ + SUPPORTS_LOCATION_CONTEXT: string; + + /** Whether the driver supports taking screenshots. */ + TAKES_SCREENSHOT: string; + + /** + * Defines how the driver should handle unexpected alerts. The value should + * be one of "accept", "dismiss", or "ignore. + */ + UNEXPECTED_ALERT_BEHAVIOR: string; + + /** Defines the browser version. */ + VERSION: string; + } + + var Capability: ICapability; + + class Capabilities { + //region Constructors + + /** + * @param {(webdriver.Capabilities|Object)=} opt_other Another set of + * capabilities to merge into this instance. + * @constructor + */ + constructor(opt_other?: Capabilities|Object); + + //endregion + + //region Methods + + /** @return {!Object} The JSON representation of this instance. */ + toJSON(): any; + + /** + * Merges another set of capabilities into this instance. Any duplicates in + * the provided set will override those already set on this instance. + * @param {!(webdriver.Capabilities|Object)} other The capabilities to + * merge into this instance. + * @return {!webdriver.Capabilities} A self reference. + */ + merge(other: Capabilities|Object): Capabilities; + + /** + * @param {string} key The capability to set. + * @param {*} value The capability value. Capability values must be JSON + * serializable. Pass {@code null} to unset the capability. + * @return {!webdriver.Capabilities} A self reference. + */ + set(key: string, value: any): Capabilities; + + /** + * Sets the logging preferences. Preferences may be specified as a + * {@link webdriver.logging.Preferences} instance, or a as a map of log-type to + * log-level. + * @param {!(webdriver.logging.Preferences|Object.)} prefs The + * logging preferences. + * @return {!webdriver.Capabilities} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences|Object): Capabilities; + + /** + * Sets the proxy configuration for this instance. + * @param {webdriver.ProxyConfig} proxy The desired proxy configuration. + * @return {!webdriver.Capabilities} A self reference. + */ + setProxy(proxy: ProxyConfig): Capabilities; + + + /** + * Sets whether native events should be used. + * @param {boolean} enabled Whether to enable native events. + * @return {!webdriver.Capabilities} A self reference. + */ + setEnableNativeEvents(enabled: boolean): Capabilities; + + + /** + * Sets how elements should be scrolled into view for interaction. + * @param {number} behavior The desired scroll behavior: either 0 to align with + * the top of the viewport or 1 to align with the bottom. + * @return {!webdriver.Capabilities} A self reference. + */ + setScrollBehavior(behavior: number): Capabilities; + + /** + * Sets the default action to take with an unexpected alert before returning + * an error. + * @param {string} behavior The desired behavior; should be "accept", "dismiss", + * or "ignore". Defaults to "dismiss". + * @return {!webdriver.Capabilities} A self reference. + */ + setAlertBehavior(behavior: string): Capabilities; + + /** + * @param {string} key The capability to return. + * @return {*} The capability with the given key, or {@code null} if it has + * not been set. + */ + get(key: string): any; + + /** + * @param {string} key The capability to check. + * @return {boolean} Whether the specified capability is set. + */ + has(key: string): boolean; + + //endregion + + //region Static Methods + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Android. + */ + static android(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Chrome. + */ + static chrome(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for Microsoft Edge. + */ + static edge(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Firefox. + */ + static firefox(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for + * Internet Explorer. + */ + static ie(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for iPad. + */ + static ipad(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for iPhone. + */ + static iphone(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Opera. + */ + static opera(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for + * PhantomJS. + */ + static phantomjs(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Safari. + */ + static safari(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for HTMLUnit. + */ + static htmlunit(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for HTMLUnit + * with enabled Javascript. + */ + static htmlunitwithjs(): Capabilities; + + //endregion + } + + /** + * An enumeration of valid command string. + */ + interface ICommandName { + GET_SERVER_STATUS: string; + + NEW_SESSION: string; + GET_SESSIONS: string; + DESCRIBE_SESSION: string; + + CLOSE: string; + QUIT: string; + + GET_CURRENT_URL: string; + GET: string; + GO_BACK: string; + GO_FORWARD: string; + REFRESH: string; + + ADD_COOKIE: string; + GET_COOKIE: string; + GET_ALL_COOKIES: string; + DELETE_COOKIE: string; + DELETE_ALL_COOKIES: string; + + GET_ACTIVE_ELEMENT: string; + FIND_ELEMENT: string; + FIND_ELEMENTS: string; + FIND_CHILD_ELEMENT: string; + FIND_CHILD_ELEMENTS: string; + + CLEAR_ELEMENT: string; + CLICK_ELEMENT: string; + SEND_KEYS_TO_ELEMENT: string; + SUBMIT_ELEMENT: string; + + GET_CURRENT_WINDOW_HANDLE: string; + GET_WINDOW_HANDLES: string; + GET_WINDOW_POSITION: string; + SET_WINDOW_POSITION: string; + GET_WINDOW_SIZE: string; + SET_WINDOW_SIZE: string; + MAXIMIZE_WINDOW: string; + + SWITCH_TO_WINDOW: string; + SWITCH_TO_FRAME: string; + GET_PAGE_SOURCE: string; + GET_TITLE: string; + + EXECUTE_SCRIPT: string; + EXECUTE_ASYNC_SCRIPT: string; + + GET_ELEMENT_TEXT: string; + GET_ELEMENT_TAG_NAME: string; + IS_ELEMENT_SELECTED: string; + IS_ELEMENT_ENABLED: string; + IS_ELEMENT_DISPLAYED: string; + GET_ELEMENT_LOCATION: string; + GET_ELEMENT_LOCATION_IN_VIEW: string; + GET_ELEMENT_SIZE: string; + GET_ELEMENT_ATTRIBUTE: string; + GET_ELEMENT_VALUE_OF_CSS_PROPERTY: string; + ELEMENT_EQUALS: string; + + SCREENSHOT: string; + IMPLICITLY_WAIT: string; + SET_SCRIPT_TIMEOUT: string; + SET_TIMEOUT: string; + + ACCEPT_ALERT: string; + DISMISS_ALERT: string; + GET_ALERT_TEXT: string; + SET_ALERT_TEXT: string; + + EXECUTE_SQL: string; + GET_LOCATION: string; + SET_LOCATION: string; + GET_APP_CACHE: string; + GET_APP_CACHE_STATUS: string; + CLEAR_APP_CACHE: string; + IS_BROWSER_ONLINE: string; + SET_BROWSER_ONLINE: string; + + GET_LOCAL_STORAGE_ITEM: string; + GET_LOCAL_STORAGE_KEYS: string; + SET_LOCAL_STORAGE_ITEM: string; + REMOVE_LOCAL_STORAGE_ITEM: string; + CLEAR_LOCAL_STORAGE: string; + GET_LOCAL_STORAGE_SIZE: string; + + GET_SESSION_STORAGE_ITEM: string; + GET_SESSION_STORAGE_KEYS: string; + SET_SESSION_STORAGE_ITEM: string; + REMOVE_SESSION_STORAGE_ITEM: string; + CLEAR_SESSION_STORAGE: string; + GET_SESSION_STORAGE_SIZE: string; + + SET_SCREEN_ORIENTATION: string; + GET_SCREEN_ORIENTATION: string; + + // These belong to the Advanced user interactions - an element is + // optional for these commands. + CLICK: string; + DOUBLE_CLICK: string; + MOUSE_DOWN: string; + MOUSE_UP: string; + MOVE_TO: string; + SEND_KEYS_TO_ACTIVE_ELEMENT: string; + + // These belong to the Advanced Touch API + TOUCH_SINGLE_TAP: string; + TOUCH_DOWN: string; + TOUCH_UP: string; + TOUCH_MOVE: string; + TOUCH_SCROLL: string; + TOUCH_DOUBLE_TAP: string; + TOUCH_LONG_PRESS: string; + TOUCH_FLICK: string; + + GET_AVAILABLE_LOG_TYPES: string; + GET_LOG: string; + GET_SESSION_LOGS: string; + + UPLOAD_FILE: string; + } + + var CommandName: ICommandName; + + /** + * Describes a command to be executed by the WebDriverJS framework. + * @param {!webdriver.CommandName} name The name of this command. + * @constructor + */ + class Command { + //region Constructors + + /** + * @param {!webdriver.CommandName} name The name of this command. + * @constructor + */ + constructor(name: string); + + //endregion + + //region Methods + + /** + * @return {!webdriver.CommandName} This command's name. + */ + getName(): string; + + /** + * Sets a parameter to send with this command. + * @param {string} name The parameter name. + * @param {*} value The parameter value. + * @return {!webdriver.Command} A self reference. + */ + setParameter(name: string, value: any): Command; + + /** + * Sets the parameters for this command. + * @param {!Object.<*>} parameters The command parameters. + * @return {!webdriver.Command} A self reference. + */ + setParameters(parameters: any): Command; + + /** + * Returns a named command parameter. + * @param {string} key The parameter key to look up. + * @return {*} The parameter value, or undefined if it has not been set. + */ + getParameter(key: string): any; + + /** + * @return {!Object.<*>} The parameters to send with this command. + */ + getParameters(): any; + + //endregion + } + + /** + * Handles the execution of WebDriver {@link Command commands}. + * @interface + */ + class Executor { + /** + * Executes the given {@code command}. If there is an error executing the + * command, the provided callback will be invoked with the offending error. + * Otherwise, the callback will be invoked with a null Error and non-null + * response object. + * + * @param {!Command} command The command to execute. + * @return {!promise.Promise} A promise that will be fulfilled with + * the command result. + */ + execute(command: Command): webdriver.promise.Promise + } + + /** + * Wraps a promised {@link Executor}, ensuring no commands are executed until + * the wrapped executor has been fully resolved. + * @implements {Executor} + */ + class DeferredExecutor { + /** + * @param {!promise.Promise} delegate The promised delegate, which + * may be provided by any promise-like thenable object. + */ + constructor(delegate: webdriver.promise.Promise); + } + + /** + * Describes an event listener registered on an {@linkplain EventEmitter}. + */ + class Listener { + /** + * @param {!Function} fn The acutal listener function. + * @param {(Object|undefined)} scope The object in whose scope to invoke the + * listener. + * @param {boolean} oneshot Whether this listener should only be used once. + */ + constructor(fn: Function, scope: Object, oneshot: boolean); + } + + /** + * Object that can emit events for others to listen for. This is used instead + * of Closure's event system because it is much more light weight. The API is + * based on Node's EventEmitters. + */ + class EventEmitter { + //region Constructors + + /** + * @constructor + */ + constructor(); + + //endregion + + //region Methods + + /** + * Fires an event and calls all listeners. + * @param {string} type The type of event to emit. + * @param {...*} var_args Any arguments to pass to each listener. + */ + emit(type: string, ...var_args: any[]): void; + + /** + * Returns a mutable list of listeners for a specific type of event. + * @param {string} type The type of event to retrieve the listeners for. + * @return {!Set} The registered listeners for the given event + * type. + */ + listeners(type: string): any; + + /** + * Registers a listener. + * @param {string} type The type of event to listen for. + * @param {!Function} fn The function to invoke when the event is fired. + * @param {Object=} opt_self The object in whose scope to invoke the listener. + * @param {boolean=} opt_oneshot Whether the listener should b (e removed after + * the first event is fired. + * @return {!EventEmitter} A self reference. + * @private + */ + addListener(type: string, fn: Function, opt_scope?:any, opt_oneshot?: boolean): EventEmitter; + + + /** + * Registers a one-time listener which will be called only the first time an + * event is emitted, after which it will be removed. + * @param {string} type The type of event to listen for. + * @param {!Function} fn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!webdriver.EventEmitter} A self reference. + */ + once(type: string, fn: any, opt_scope?: any): EventEmitter; + + /** + * An alias for {@code #addListener()}. + * @param {string} type The type of event to listen for. + * @param {!Function} fn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!webdriver.EventEmitter} A self reference. + */ + on(type: string, fn: Function, opt_scope?:any): EventEmitter; + + /** + * Removes a previously registered event listener. + * @param {string} type The type of event to unregister. + * @param {!Function} listenerFn The handler function to remove. + * @return {!webdriver.EventEmitter} A self reference. + */ + removeListener(type: string, listenerFn: Function): EventEmitter; + + /** + * Removes all listeners for a specific type of event. If no event is + * specified, all listeners across all types will be removed. + * @param {string=} opt_type The type of event to remove listeners from. + * @return {!webdriver.EventEmitter} A self reference. + */ + removeAllListeners(opt_type?: string): EventEmitter; + + //endregion + } + + + /** + * Interface for navigating back and forth in the browser history. + */ + class Navigation { + //region Constructors + + /** + * Interface for navigating back and forth in the browser history. + * + * This class should never be instantiated directly. Insead, obtain an instance + * with + * + * webdriver.navigate() + * + * @see WebDriver#navigate() + */ + constructor(driver: WebDriver); + + //endregion + + //region Methods + + /** + * Schedules a command to navigate to a new URL. + * @param {string} url The URL to navigate to. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the URL has been loaded. + */ + to(url: string): webdriver.promise.Promise; + + /** + * Schedules a command to move backwards in the browser history. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the navigation event has completed. + */ + back(): webdriver.promise.Promise; + + /** + * Schedules a command to move forwards in the browser history. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the navigation event has completed. + */ + forward(): webdriver.promise.Promise; + + /** + * Schedules a command to refresh the current page. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the navigation event has completed. + */ + refresh(): webdriver.promise.Promise; + + //endregion + } + + interface IWebDriverOptionsCookie { + name: string; + value: string; + path?: string; + domain?: string; + secure?: boolean; + expiry?: number; + } + + /** + * Provides methods for managing browser and driver state. + */ + class Options { + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: webdriver.WebDriver); + + //endregion + + //region Methods + + /** + * Schedules a command to add a cookie. + * @param {string} name The cookie name. + * @param {string} value The cookie value. + * @param {string=} opt_path The cookie path. + * @param {string=} opt_domain The cookie domain. + * @param {boolean=} opt_isSecure Whether the cookie is secure. + * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified + * as a number, should be in milliseconds since midnight, + * January 1, 1970 UTC. + * @return {!promise.Promise} A promise that will be resolved + * when the cookie has been added to the page. + */ + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number|Date): webdriver.promise.Promise; + + /** + * Schedules a command to delete all cookies visible to the current page. + * @return {!webdriver.promise.Promise} A promise that will be resolved when all + * cookies have been deleted. + */ + deleteAllCookies(): webdriver.promise.Promise; + + /** + * Schedules a command to delete the cookie with the given name. This command is + * a no-op if there is no cookie with the given name visible to the current + * page. + * @param {string} name The name of the cookie to delete. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * cookie has been deleted. + */ + deleteCookie(name: string): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve all cookies visible to the current page. + * Each cookie will be returned as a JSON object as described by the WebDriver + * wire protocol. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * cookies visible to the current page. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object + */ + getCookies(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the cookie with the given name. Returns null + * if there is no such cookie. The cookie will be returned as a JSON object as + * described by the WebDriver wire protocol. + * @param {string} name The name of the cookie to retrieve. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * named cookie, or {@code null} if there is no such cookie. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object + */ + getCookie(name: string): webdriver.promise.Promise; + + /** + * @return {!webdriver.WebDriver.Logs} The interface for managing driver + * logs. + */ + logs(): webdriver.Logs; + + /** + * @return {!webdriver.WebDriver.Timeouts} The interface for managing driver + * timeouts. + */ + timeouts(): webdriver.Timeouts; + + /** + * @return {!webdriver.WebDriver.Window} The interface for managing the + * current window. + */ + window(): webdriver.Window; + + //endregion + } + + /** + * An interface for managing timeout behavior for WebDriver instances. + */ + class Timeouts { + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: webdriver.WebDriver); + + //endregion + + //region Methods + + /** + * Specifies the amount of time the driver should wait when searching for an + * element if it is not immediately present. + *

    + * When searching for a single element, the driver should poll the page + * until the element has been found, or this timeout expires before failing + * with a {@code bot.ErrorCode.NO_SUCH_ELEMENT} error. When searching + * for multiple elements, the driver should poll the page until at least one + * element has been found or this timeout has expired. + *

    + * Setting the wait timeout to 0 (its default value), disables implicit + * waiting. + *

    + * Increasing the implicit wait timeout should be used judiciously as it + * will have an adverse effect on test run time, especially when used with + * slower location strategies like XPath. + * + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * implicit wait timeout has been set. + */ + implicitlyWait(ms: number): webdriver.promise.Promise; + + /** + * Sets the amount of time to wait, in milliseconds, for an asynchronous script + * to finish execution before returning an error. If the timeout is less than or + * equal to 0, the script will be allowed to run indefinitely. + * + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * script timeout has been set. + */ + setScriptTimeout(ms: number): webdriver.promise.Promise; + + /** + * Sets the amount of time to wait for a page load to complete before returning + * an error. If the timeout is negative, page loads may be indefinite. + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the timeout has been set. + */ + pageLoadTimeout(ms: number): webdriver.promise.Promise; + + //endregion + } + + /** + * An interface for managing the current window. + */ + class Window { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: webdriver.WebDriver); + + //endregion + + //region Methods + + /** + * Retrieves the window's current position, relative to the top left corner of + * the screen. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * window's position in the form of a {x:number, y:number} object literal. + */ + getPosition(): webdriver.promise.Promise; + + /** + * Repositions the current window. + * @param {number} x The desired horizontal position, relative to the left side + * of the screen. + * @param {number} y The desired vertical position, relative to the top of the + * of the screen. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * command has completed. + */ + setPosition(x: number, y: number): webdriver.promise.Promise; + + /** + * Retrieves the window's current size. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * window's size in the form of a {width:number, height:number} object + * literal. + */ + getSize(): webdriver.promise.Promise; + + /** + * Resizes the current window. + * @param {number} width The desired window width. + * @param {number} height The desired window height. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * command has completed. + */ + setSize(width: number, height: number): webdriver.promise.Promise; + + /** + * Maximizes the current window. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * command has completed. + */ + maximize(): webdriver.promise.Promise; + + //endregion + } + + /** + * Interface for managing WebDriver log records. + */ + class Logs { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: webdriver.WebDriver); + + //endregion + + //region + + /** + * Fetches available log entries for the given type. + * + *

    Note that log buffers are reset after each call, meaning that + * available log entries correspond to those entries not yet returned for a + * given log type. In practice, this means that this call will return the + * available log entries since the last call, or from the start of the + * session. + * + * @param {!webdriver.logging.Type} type The desired log type. + * @return {!webdriver.promise.Promise.>} A + * promise that will resolve to a list of log entries for the specified + * type. + */ + get(type: webdriver.logging.Type): webdriver.promise.Promise; + + /** + * Retrieves the log types available to this driver. + * @return {!webdriver.promise.Promise.>} A + * promise that will resolve to a list of available log types. + */ + getAvailableLogTypes(): webdriver.promise.Promise; + + //endregion + } + + /** + * An interface for changing the focus of the driver to another frame or window. + */ + class TargetLocator { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: webdriver.WebDriver); + + //endregion + + //region Methods + + /** + * Schedules a command retrieve the {@code document.activeElement} element on + * the current document, or {@code document.body} if activeElement is not + * available. + * @return {!webdriver.WebElement} The active element. + */ + activeElement(): WebElementPromise; + + /** + * Schedules a command to switch focus of all future commands to the first frame + * on the page. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * driver has changed focus to the default content. + */ + defaultContent(): webdriver.promise.Promise; + + /** + * Schedules a command to switch the focus of all future commands to another + * frame on the page. The target frame may be specified as one of the + * following: + * + * - A number that specifies a (zero-based) index into [window.frames]( + * https://developer.mozilla.org/en-US/docs/Web/API/Window.frames). + * - A {@link WebElement} reference, which correspond to a `frame` or `iframe` + * DOM element. + * - The `null` value, to select the topmost frame on the page. Passing `null` + * is the same as calling {@link #defaultContent defaultContent()}. + * + * If the specified frame can not be found, the returned promise will be + * rejected with a {@linkplain error.NoSuchFrameError}. + * + * @param {(number|WebElement|null)} id The frame locator. + * @return {!promise.Promise} A promise that will be resolved + * when the driver has changed focus to the specified frame. + */ + frame(nameOrIndex: number|WebElement): webdriver.promise.Promise; + + /** + * Schedules a command to switch the focus of all future commands to another + * window. Windows may be specified by their {@code window.name} attribute or + * by its handle (as returned by {@link WebDriver#getWindowHandles}). + * + * If the specified window cannot be found, the returned promise will be + * rejected with a {@linkplain error.NoSuchWindowError}. + * + * @param {string} nameOrHandle The name or window handle of the window to + * switch focus to. + * @return {!promise.Promise} A promise that will be resolved + * when the driver has changed focus to the specified window. + */ + window(nameOrHandle: string): webdriver.promise.Promise; + + /** + * Schedules a command to change focus to the active modal dialog, such as + * those opened by `window.alert()`, `window.confirm()`, and + * `window.prompt()`. The returned promise will be rejected with a + * {@linkplain error.NoSuchAlertError} if there are no open alerts. + * + * @return {!AlertPromise} The open alert. + */ + alert(): AlertPromise; + + //endregion + } + + /** + * Used with {@link webdriver.WebElement#sendKeys WebElement#sendKeys} on file + * input elements ({@code }) to detect when the entered key + * sequence defines the path to a file. + * + * By default, {@linkplain webdriver.WebElement WebElement's} will enter all + * key sequences exactly as entered. You may set a + * {@linkplain webdriver.WebDriver#setFileDetector file detector} on the parent + * WebDriver instance to define custom behavior for handling file elements. Of + * particular note is the {@link selenium-webdriver/remote.FileDetector}, which + * should be used when running against a remote + * [Selenium Server](http://docs.seleniumhq.org/download/). + */ + class FileDetector { + /** @constructor */ + constructor(); + + /** + * Handles the file specified by the given path, preparing it for use with + * the current browser. If the path does not refer to a valid file, it will + * be returned unchanged, otherwisee a path suitable for use with the current + * browser will be returned. + * + * This default implementation is a no-op. Subtypes may override this + * function for custom tailored file handling. + * + * @param {!webdriver.WebDriver} driver The driver for the current browser. + * @param {string} path The path to process. + * @return {!webdriver.promise.Promise} A promise for the processed + * file path. + * @package + */ + handleFile(driver: webdriver.WebDriver, path: string): webdriver.promise.Promise; + } + + /** + * Creates a new WebDriver client, which provides control over a browser. + * + * Every WebDriver command returns a {@code webdriver.promise.Promise} that + * represents the result of that command. Callbacks may be registered on this + * object to manipulate the command result or catch an expected error. Any + * commands scheduled with a callback are considered sub-commands and will + * execute before the next command in the current frame. For example: + * + * var message = []; + * driver.call(message.push, message, 'a').then(function() { + * driver.call(message.push, message, 'b'); + * }); + * driver.call(message.push, message, 'c'); + * driver.call(function() { + * alert('message is abc? ' + (message.join('') == 'abc')); + * }); + * + */ + class WebDriver { + //region Constructors + + /** + * @param {!(Session|promise.Promise)} session Either a + * known session or a promise that will be resolved to a session. + * @param {!command.Executor} executor The executor to use when sending + * commands to the browser. + * @param {promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + */ + constructor(session: Session|webdriver.promise.Promise, executor: Executor, opt_flow?: webdriver.promise.ControlFlow); + + //endregion + + //region StaticMethods + + /** + * Creates a new WebDriver client for an existing session. + * @param {!command.Executor} executor Command executor to use when querying + * for session details. + * @param {string} sessionId ID of the session to attach to. + * @param {promise.ControlFlow=} opt_flow The control flow all + * driver commands should execute under. Defaults to the + * {@link promise.controlFlow() currently active} control flow. + * @return {!WebDriver} A new client for the specified session. + */ + static attachToSession(executor: Executor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + + /** + * Creates a new WebDriver session. + * @param {!command.Executor} executor The executor to create the new session + * with. + * @param {!./capabilities.Capabilities} desiredCapabilities The desired + * capabilities for the new session. + * @param {promise.ControlFlow=} opt_flow The control flow all driver + * commands should execute under, including the initial session creation. + * Defaults to the {@link promise.controlFlow() currently active} + * control flow. + * @return {!WebDriver} The driver for the newly created session. + */ + static createSession(executor: Executor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + + //endregion + + //region Methods + + /** + * @return {!webdriver.promise.ControlFlow} The control flow used by this + * instance. + */ + controlFlow(): webdriver.promise.ControlFlow; + + /** + * Schedules a {@link command.Command} to be executed by this driver's + * {@link command.Executor}. + * + * @param {!command.Command} command The command to schedule. + * @param {string} description A description of the command for debugging. + * @return {!promise.Promise} A promise that will be resolved + * with the command result. + * @template T + */ + schedule(command: Command, description: string): webdriver.promise.Promise; + + + /** + * Sets the {@linkplain input.FileDetector file detector} that should be + * used with this instance. + * @param {input.FileDetector} detector The detector to use or {@code null}. + */ + setFileDetector(detector: FileDetector): void; + + + /** + * @return {!webdriver.promise.Promise.} A promise for this + * client's session. + */ + getSession(): webdriver.promise.Promise; + + + /** + * @return {!webdriver.promise.Promise.} A promise + * that will resolve with the this instance's capabilities. + */ + getCapabilities(): webdriver.promise.Promise; + + + /** + * Schedules a command to quit the current session. After calling quit, this + * instance will be invalidated and may no longer be used to issue commands + * against the browser. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the command has completed. + */ + quit(): webdriver.promise.Promise; + + /** + * Creates a new action sequence using this driver. The sequence will not be + * scheduled for execution until {@link actions.ActionSequence#perform} is + * called. Example: + * + * driver.actions(). + * mouseDown(element1). + * mouseMove(element2). + * mouseUp(). + * perform(); + * + * @return {!actions.ActionSequence} A new action sequence for this instance. + */ + actions(): ActionSequence; + + + /** + * Creates a new touch sequence using this driver. The sequence will not be + * scheduled for execution until {@link actions.TouchSequence#perform} is + * called. Example: + * + * driver.touchActions(). + * tap(element1). + * doubleTap(element2). + * perform(); + * + * @return {!actions.TouchSequence} A new touch sequence for this instance. + */ + touchActions(): TouchSequence; + + + /** + * Schedules a command to execute JavaScript in the context of the currently + * selected frame or window. The script fragment will be executed as the body + * of an anonymous function. If the script is provided as a function object, + * that function will be converted to a string for injection into the target + * window. + * + * Any arguments provided in addition to the script will be included as script + * arguments and may be referenced using the {@code arguments} object. + * Arguments may be a boolean, number, string, or {@code webdriver.WebElement}. + * Arrays and objects may also be used as script arguments as long as each item + * adheres to the types previously mentioned. + * + * The script may refer to any variables accessible from the current window. + * Furthermore, the script will execute in the window's context, thus + * {@code document} may be used to refer to the current document. Any local + * variables will not be available once the script has finished executing, + * though global variables will persist. + * + * If the script has a return value (i.e. if the script contains a return + * statement), then the following steps will be taken for resolving this + * functions return value: + * + * - For a HTML element, the value will resolve to a + * {@link webdriver.WebElement} + * - Null and undefined return values will resolve to null + * - Booleans, numbers, and strings will resolve as is + * - Functions will resolve to their string representation + * - For arrays and objects, each member item will be converted according to + * the rules above + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {!webdriver.promise.Promise.} A promise that will resolve to the + * scripts return value. + * @template T + */ + executeScript(script: string|Function, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to execute asynchronous JavaScript in the context of the + * currently selected frame or window. The script fragment will be executed as + * the body of an anonymous function. If the script is provided as a function + * object, that function will be converted to a string for injection into the + * target window. + * + * Any arguments provided in addition to the script will be included as script + * arguments and may be referenced using the {@code arguments} object. + * Arguments may be a boolean, number, string, or {@code webdriver.WebElement}. + * Arrays and objects may also be used as script arguments as long as each item + * adheres to the types previously mentioned. + * + * Unlike executing synchronous JavaScript with {@link #executeScript}, + * scripts executed with this function must explicitly signal they are finished + * by invoking the provided callback. This callback will always be injected + * into the executed function as the last argument, and thus may be referenced + * with {@code arguments[arguments.length - 1]}. The following steps will be + * taken for resolving this functions return value against the first argument + * to the script's callback function: + * + * - For a HTML element, the value will resolve to a + * {@link webdriver.WebElement} + * - Null and undefined return values will resolve to null + * - Booleans, numbers, and strings will resolve as is + * - Functions will resolve to their string representation + * - For arrays and objects, each member item will be converted according to + * the rules above + * + * __Example #1:__ Performing a sleep that is synchronized with the currently + * selected window: + * + * var start = new Date().getTime(); + * driver.executeAsyncScript( + * 'window.setTimeout(arguments[arguments.length - 1], 500);'). + * then(function() { + * console.log( + * 'Elapsed time: ' + (new Date().getTime() - start) + ' ms'); + * }); + * + * __Example #2:__ Synchronizing a test with an AJAX application: + * + * var button = driver.findElement(By.id('compose-button')); + * button.click(); + * driver.executeAsyncScript( + * 'var callback = arguments[arguments.length - 1];' + + * 'mailClient.getComposeWindowWidget().onload(callback);'); + * driver.switchTo().frame('composeWidget'); + * driver.findElement(By.id('to')).sendKeys('dog@example.com'); + * + * __Example #3:__ Injecting a XMLHttpRequest and waiting for the result. In + * this example, the inject script is specified with a function literal. When + * using this format, the function is converted to a string for injection, so it + * should not reference any symbols not defined in the scope of the page under + * test. + * + * driver.executeAsyncScript(function() { + * var callback = arguments[arguments.length - 1]; + * var xhr = new XMLHttpRequest(); + * xhr.open("GET", "/resource/data.json", true); + * xhr.onreadystatechange = function() { + * if (xhr.readyState == 4) { + * callback(xhr.responseText); + * } + * } + * xhr.send(''); + * }).then(function(str) { + * console.log(JSON.parse(str)['food']); + * }); + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {!webdriver.promise.Promise.} A promise that will resolve to the + * scripts return value. + * @template T + */ + executeAsyncScript(script: string|Function, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to execute a custom function. + * @param {function(...): (T|webdriver.promise.Promise.)} fn The function to + * execute. + * @param {Object=} opt_scope The object in whose scope to execute the function. + * @param {...*} var_args Any arguments to pass to the function. + * @return {!webdriver.promise.Promise.} A promise that will be resolved' + * with the function's result. + * @template T + */ + call(fn: (...var_args: any[])=>(T|webdriver.promise.Promise), opt_scope?: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to wait for a condition to hold. The condition may be + * specified by a {@link webdriver.until.Condition}, as a custom function, or + * as a {@link webdriver.promise.Promise}. + * + * For a {@link webdriver.until.Condition} or function, the wait will repeatedly + * evaluate the condition until it returns a truthy value. If any errors occur + * while evaluating the condition, they will be allowed to propagate. In the + * event a condition returns a {@link webdriver.promise.Promise promise}, the + * polling loop will wait for it to be resolved and use the resolved value for + * whether the condition has been satisified. Note the resolution time for + * a promise is factored into whether a wait has timed out. + * + * *Example:* waiting up to 10 seconds for an element to be present and visible + * on the page. + * + * var button = driver.wait(until.elementLocated(By.id('foo'), 10000); + * button.click(); + * + * This function may also be used to block the command flow on the resolution + * of a {@link webdriver.promise.Promise promise}. When given a promise, the + * command will simply wait for its resolution before completing. A timeout may + * be provided to fail the command if the promise does not resolve before the + * timeout expires. + * + * *Example:* Suppose you have a function, `startTestServer`, that returns a + * promise for when a server is ready for requests. You can block a `WebDriver` + * client on this promise with: + * + * var started = startTestServer(); + * driver.wait(started, 5 * 1000, 'Server should start within 5 seconds'); + * driver.get(getServerUrl()); + * + * @param {!(webdriver.promise.Promise| + * webdriver.until.Condition| + * function(!webdriver.WebDriver): T)} condition The condition to + * wait on, defined as a promise, condition object, or a function to + * evaluate as a condition. + * @param {number=} opt_timeout How long to wait for the condition to be true. + * @param {string=} opt_message An optional message to use if the wait times + * out. + * @return {!webdriver.promise.Promise} A promise that will be fulfilled + * with the first truthy value returned by the condition function, or + * rejected if the condition times out. + * @template T + */ + wait(condition: webdriver.promise.Promise|webdriver.until.Condition|((driver: WebDriver)=>T), timeout?: number, opt_message?: string): webdriver.promise.Promise; + + /** + * Schedules a command to make the driver sleep for the given amount of time. + * @param {number} ms The amount of time, in milliseconds, to sleep. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the sleep has finished. + */ + sleep(ms: number): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve they current window handle. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the current window handle. + */ + getWindowHandle(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the current list of available window handles. + * @return {!webdriver.promise.Promise.>} A promise that will + * be resolved with an array of window handles. + */ + getAllWindowHandles(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the current page's source. The page source + * returned is a representation of the underlying DOM: do not expect it to be + * formatted or escaped in the same way as the response sent from the web + * server. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the current page source. + */ + getPageSource(): webdriver.promise.Promise; + + /** + * Schedules a command to close the current window. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when this command has completed. + */ + close(): webdriver.promise.Promise; + + /** + * Schedules a command to navigate to the given URL. + * @param {string} url The fully qualified URL to open. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the document has finished loading. + */ + get(url: string): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the URL of the current page. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the current URL. + */ + getCurrentUrl(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the current page's title. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the current page's title. + */ + getTitle(): webdriver.promise.Promise; + + /** + * Schedule a command to find an element on the page. If the element cannot be + * found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned + * by the driver. Unlike other commands, this error cannot be suppressed. In + * other words, scheduling a command to find an element doubles as an assert + * that the element is present on the page. To test whether an element is + * present on the page, use {@link #isElementPresent} instead. + * + * The search criteria for an element may be defined using one of the + * factories in the {@link webdriver.By} namespace, or as a short-hand + * {@link webdriver.By.Hash} object. For example, the following two statements + * are equivalent: + * + * var e1 = driver.findElement(By.id('foo')); + * var e2 = driver.findElement({id:'foo'}); + * + * You may also provide a custom locator function, which takes as input this + * instance and returns a {@link WebElement}, or a promise that will resolve + * to a WebElement. If the returned promise resolves to an array of + * WebElements, WebDriver will use the first element. For example, to find the + * first visible link on a page, you could write: + * + * var link = driver.findElement(firstVisibleLink); + * + * function firstVisibleLink(driver) { + * var links = driver.findElements(By.tagName('a')); + * return promise.filter(links, function(link) { + * return link.isDisplayed(); + * }); + * } + * + * @param {!(by.By|Function)} locator The locator to use. + * @return {!WebElementPromise} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: By|Function): WebElementPromise; + + /** + * Schedules a command to test if an element is present on the page. + * + * If given a DOM element, this function will check if it belongs to the + * document the driver is currently focused on. Otherwise, the function will + * test if at least one element can be found with the given search criteria. + * + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise} A promise that will resolve + * with whether the element is present on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * driver.findElements(locator).then(e => !!e.length); + */ + isElementPresent(locatorOrElement: By|Function): webdriver.promise.Promise; + + /** + * Schedule a command to search for multiple elements on the page. + * + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise.>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: By|Function): webdriver.promise.Promise; + + /** + * Schedule a command to take a screenshot. The driver makes a best effort to + * return a screenshot of the following, in order of preference: + * + * 1. Entire page + * 2. Current window + * 3. Visible portion of the current frame + * 4. The entire display containing the browser + * + * @return {!promise.Promise} A promise that will be + * resolved to the screenshot as a base-64 encoded PNG. + */ + takeScreenshot(): webdriver.promise.Promise; + + /** + * @return {!webdriver.WebDriver.Options} The options interface for this + * instance. + */ + manage(): webdriver.Options; + + /** + * @return {!webdriver.WebDriver.Navigation} The navigation interface for this + * instance. + */ + navigate(): Navigation; + + /** + * @return {!webdriver.WebDriver.TargetLocator} The target locator interface for + * this instance. + */ + switchTo(): webdriver.TargetLocator; + + //endregion + } + + interface IWebElementId { + [ELEMENT:string]: string; + } + + /** + * Represents a DOM element. WebElements can be found by searching from the + * document root using a {@code webdriver.WebDriver} instance, or by searching + * under another {@code webdriver.WebElement}: + *

    
    +     *   driver.get('http://www.google.com');
    +     *   var searchForm = driver.findElement(By.tagName('form'));
    +     *   var searchBox = searchForm.findElement(By.name('q'));
    +     *   searchBox.sendKeys('webdriver');
    +     * 
    + * + * The WebElement is implemented as a promise for compatibility with the promise + * API. It will always resolve itself when its internal state has been fully + * resolved and commands may be issued against the element. This can be used to + * catch errors when an element cannot be located on the page: + *
    
    +     *   driver.findElement(By.id('not-there')).then(function(element) {
    +     *     alert('Found an element that was not expected to be there!');
    +     *   }, function(error) {
    +     *     alert('The element was not found, as expected');
    +     *   });
    +     * 
    + */ + interface IWebElement { + //region Methods + + /** + * Schedules a command to click on this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the click command has completed. + */ + click(): webdriver.promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * instance. + *

    + * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + *

      + *
    • The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + *
    • + *
    • The {@code webdriver.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys("text was", + * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, + * "now text is"); + * // Alternatively: + * element.sendKeys("text was", + * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), + * "now text is"); + *
    • + *
    • The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + *
    • + *
    + * Note: On browsers where native keyboard events are not yet + * supported (e.g. Firefox on OS X), key events will be synthesized. Special + * punctionation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...string} var_args The sequence of keys to + * type. All arguments will be joined into a single sequence (var_args is + * permitted for convenience). + * @return {!webdriver.promise.Promise} A promise that will be resolved when all + * keys have been typed. + */ + sendKeys(...var_args: string[]): webdriver.promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's tag name. + */ + getTagName(): webdriver.promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + *

    + * Warning: the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * requested CSS value. + */ + getCssValue(cssStyleProperty: string): webdriver.promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value even if it has been modified after the + * page has been loaded. More exactly, this method will return the value of the + * given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned. The "style" attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be "boolean" attributes and will be returned as thus: + * + *

    async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + *

    Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + *

      + *
    • "class" + *
    • "readonly" + *
    + * @param {string} attributeName The name of the attribute to query. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * attribute's value. + */ + getAttribute(attributeName: string): webdriver.promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's visible text. + */ + getText(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's size as a {@code {width:number, height:number}} object. + */ + getSize(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * element's location as a {@code {x:number, y:number}} object. + */ + getLocation(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently enabled. + */ + isEnabled(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently selected. + */ + isSelected(): webdriver.promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the form has been submitted. + */ + submit(): webdriver.promise.Promise; + + /** + * Schedules a command to clear the {@code value} of this element. This command + * has no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the element has been cleared. + */ + clear(): webdriver.promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently visible on the page. + */ + isDisplayed(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the element's outer HTML. + */ + getOuterHtml(): webdriver.promise.Promise; + + /** + * @return {!webdriver.promise.Promise.} A promise + * that resolves to this element's JSON representation as defined by the + * WebDriver wire protocol. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol + */ + getId(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): webdriver.promise.Promise; + + //endregion + } + + interface IWebElementFinders { + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + * + *

    The search criteria for an element may be defined using one of the + * factories in the {@link webdriver.By} namespace, or as a short-hand + * {@link webdriver.By.Hash} object. For example, the following two statements + * are equivalent: + *

    +         * var e1 = element.findElement(By.id('foo'));
    +         * var e2 = element.findElement({id:'foo'});
    +         * 
    + * + *

    You may also provide a custom locator function, which takes as input + * this WebDriver instance and returns a {@link webdriver.WebElement}, or a + * promise that will resolve to a WebElement. For example, to find the first + * visible link on a page, you could write: + *

    +         * var link = element.findElement(firstVisibleLink);
    +         *
    +         * function firstVisibleLink(element) {
    +         *   var links = element.findElements(By.tagName('a'));
    +         *   return webdriver.promise.filter(links, function(link) {
    +         *     return links.isDisplayed();
    +         *   }).then(function(visibleLinks) {
    +         *     return visibleLinks[0];
    +         *   });
    +         * }
    +         * 
    + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!webdriver.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: By|Function): WebElementPromise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether an element could be located on the page. + */ + isElementPresent(locator: By|Function): webdriver.promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that + * match the given search criteria. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the elements. + * @return {!webdriver.promise.Promise.>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: By|Function): webdriver.promise.Promise; + } + + /** + * Defines an object that can be asynchronously serialized to its WebDriver + * wire representation. + * + * @constructor + * @template T + */ + interface Serializable { + /** + * Returns either this instance's serialized represention, if immediately + * available, or a promise for its serialized representation. This function is + * conceptually equivalent to objects that have a {@code toJSON()} property, + * except the serialize() result may be a promise or an object containing a + * promise (which are not directly JSON friendly). + * + * @return {!(T|IThenable.)} This instance's serialized wire format. + */ + serialize(): T|webdriver.promise.IThenable; + } + + /** + * Represents a DOM element. WebElements can be found by searching from the + * document root using a {@link webdriver.WebDriver} instance, or by searching + * under another WebElement: + * + * driver.get('http://www.google.com'); + * var searchForm = driver.findElement(By.tagName('form')); + * var searchBox = searchForm.findElement(By.name('q')); + * searchBox.sendKeys('webdriver'); + * + * The WebElement is implemented as a promise for compatibility with the promise + * API. It will always resolve itself when its internal state has been fully + * resolved and commands may be issued against the element. This can be used to + * catch errors when an element cannot be located on the page: + * + * driver.findElement(By.id('not-there')).then(function(element) { + * alert('Found an element that was not expected to be there!'); + * }, function(error) { + * alert('The element was not found, as expected'); + * }); + * + * @extends {webdriver.Serializable.} + */ + class WebElement implements Serializable { + /** + * @param {!WebDriver} driver the parent WebDriver instance for this element. + * @param {(!IThenable|string)} id The server-assigned opaque ID for + * the underlying DOM element. + */ + constructor(driver: webdriver.WebDriver, id: webdriver.promise.Promise|string); + + /** + * @param {string} id The raw ID. + * @param {boolean=} opt_noLegacy Whether to exclude the legacy element key. + * @return {!Object} The element ID for use with WebDriver's wire protocol. + */ + static buildId(id: string, opt_noLegacy?: boolean): Object; + + /** + * Extracts the encoded WebElement ID from the object. + * + * @param {?} obj The object to extract the ID from. + * @return {string} the extracted ID. + * @throws {TypeError} if the object is not a valid encoded ID. + */ + static extractId(obj: IWebElementId): string; + + /** + * @param {?} obj the object to test. + * @return {boolean} whether the object is a valid encoded WebElement ID. + */ + static isId(obj: IWebElementId): boolean; + + /** + * Compares two WebElements for equality. + * + * @param {!WebElement} a A WebElement. + * @param {!WebElement} b A WebElement. + * @return {!promise.Promise} A promise that will be + * resolved to whether the two WebElements are equal. + */ + static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; + + /** + * @return {!webdriver.WebDriver} The parent driver for this instance. + */ + getDriver(): webdriver.WebDriver; + + /** + * @return {!promise.Promise} A promise that resolves to + * the server-assigned opaque ID assigned to this element. + */ + getId(): webdriver.promise.Promise; + + /** + * @deprecated Use {@link #getId()} instead. + */ + getRawId(): any; + + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@link #isElementPresent} instead. + * + * The search criteria for an element may be defined using one of the + * factories in the {@link webdriver.By} namespace, or as a short-hand + * {@link webdriver.By.Hash} object. For example, the following two statements + * are equivalent: + * + * var e1 = element.findElement(By.id('foo')); + * var e2 = element.findElement({id:'foo'}); + * + * You may also provide a custom locator function, which takes as input + * this WebDriver instance and returns a {@link webdriver.WebElement}, or a + * promise that will resolve to a WebElement. For example, to find the first + * visible link on a page, you could write: + * + * var link = element.findElement(firstVisibleLink); + * + * function firstVisibleLink(element) { + * var links = element.findElements(By.tagName('a')); + * return webdriver.promise.filter(links, function(link) { + * return links.isDisplayed(); + * }).then(function(visibleLinks) { + * return visibleLinks[0]; + * }); + * } + * + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!WebElementPromise} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: By|Function): WebElementPromise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise} A promise that will be + * resolved with whether an element could be located on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * element.findElements(locator).then(e => !!e.length); + */ + isElementPresent(locator: By|Function): webdriver.promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that + * match the given search criteria. + * + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: By|Function): webdriver.promise.Promise; + + /** + * Schedules a command to click on this element. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the click command has completed. + */ + click(): webdriver.promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * promsieinstance. + * + * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + * + * - The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + * - The {@link webdriver.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys("text was", + * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, + * "now text is"); + * // Alternatively: + * element.sendKeys("text was", + * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), + * "now text is"); + * + * - The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + * + * If this element is a file input ({@code }), the + * specified key sequence should specify the path to the file to attach to + * the element. This is analgous to the user clicking "Browse..." and entering + * the path into the file select dialog. + * + * var form = driver.findElement(By.css('form')); + * var element = form.findElement(By.css('input[type=file]')); + * element.sendKeys('/path/to/file.txt'); + * form.submit(); + * + * For uploads to function correctly, the entered path must reference a file + * on the _browser's_ machine, not the local machine running this script. When + * running against a remote Selenium server, a {@link webdriver.FileDetector} + * may be used to transparently copy files to the remote machine before + * attempting to upload them in the browser. + * + * __Note:__ On browsers where native keyboard events are not supported + * (e.g. Firefox on OS X), key events will be synthesized. Special + * punctionation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...(string|!webdriver.promise.Promise)} var_args The sequence + * of keys to type. All arguments will be joined into a single sequence. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when all keys have been typed. + */ + sendKeys(...var_args: Array>): webdriver.promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the element's tag name. + */ + getTagName(): webdriver.promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + * + * _Warning:_ the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!promise.Promise} A promise that will be + * resolved with the requested CSS value. + */ + getCssValue(cssStyleProperty: string): webdriver.promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value, even if it has been modified after + * the page has been loaded. More exactly, this method will return the value of + * the given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned (for example, the "value" property of a textarea + * element). The "style" attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be "boolean" attributes and will return either "true" or null: + * + * async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + * Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + * + * - "class" + * - "readonly" + * + * @param {string} attributeName The name of the attribute to query. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the attribute's value. The returned value will always be + * either a string or null. + */ + getAttribute(attributeName: string): webdriver.promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the element's visible text. + */ + getText(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!webdriver.promise.Promise.<{width: number, height: number}>} A + * promise that will be resolved with the element's size as a + * {@code {width:number, height:number}} object. + */ + getSize(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!webdriver.promise.Promise.<{x: number, y: number}>} A promise that + * will be resolved to the element's location as a + * {@code {x:number, y:number}} object. + */ + getLocation(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether this element is currently enabled. + */ + isEnabled(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether this element is currently selected. + */ + isSelected(): webdriver.promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the form has been submitted. + */ + submit(): webdriver.promise.Promise; + + /** + * Schedules a command to clear the `value` of this element. This command has + * no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!promise.Promise} A promise that will be resolved + * when the element has been cleared. + */ + clear(): webdriver.promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether this element is currently visible on the page. + */ + isDisplayed(): webdriver.promise.Promise; + + /** + * Take a screenshot of the visible region encompassed by this element's + * bounding rectangle. + * + * @param {boolean=} opt_scroll Optional argument that indicates whether the + * element should be scrolled into view before taking a screenshot. + * Defaults to false. + * @return {!promise.Promise} A promise that will be + * resolved to the screenshot as a base-64 encoded PNG. + */ + takeScreenshot(opt_scroll?: boolean): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the element's outer HTML. + */ + getOuterHtml(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): webdriver.promise.Promise; + + /** @override */ + serialize(): webdriver.promise.Promise; + } + + /** + * WebElementPromise is a promise that will be fulfilled with a WebElement. + * This serves as a forward proxy on WebElement, allowing calls to be + * scheduled without directly on this instance before the underlying + * WebElement has been fulfilled. In other words, the following two statements + * are equivalent: + *
    
    +     *     driver.findElement({id: 'my-button'}).click();
    +     *     driver.findElement({id: 'my-button'}).then(function(el) {
    +     *       return el.click();
    +     *     });
    +     * 
    + * + * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!webdriver.promise.Promise.} el A promise + * that will resolve to the promised element. + * @constructor + * @extends {webdriver.WebElement} + * @implements {webdriver.promise.Thenable.} + * @final + */ + class WebElementPromise extends WebElement implements webdriver.promise.IThenable { + /** + * @param {!WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!promise.Promise} el A promise + * that will resolve to the promised element. + */ + constructor(driver: webdriver.WebDriver, el: webdriver.promise.Promise); + + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. This method is a no-op if the promise has alreayd been resolved. + * + * @param {string=} opt_reason The reason this promise is being cancelled. + */ + cancel(opt_reason?: string): void; + + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: WebElement) => webdriver.promise.Promise, opt_errback?: (error: any) => any): webdriver.promise.Promise; + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: WebElement) => R, opt_errback?: (error: any) => any): webdriver.promise.Promise; + + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *
    
    +         *   // Synchronous API:
    +         *   try {
    +         *     doSynchronousWork();
    +         *   } catch (ex) {
    +         *     console.error(ex);
    +         *   }
    +         *
    +         *   // Asynchronous promise API:
    +         *   doAsynchronousWork().thenCatch(function(ex) {
    +         *     console.error(ex);
    +         *   });
    +         * 
    + * + * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!webdriver.promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): webdriver.promise.Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *
    
    +         *   // Synchronous API:
    +         *   try {
    +         *     doSynchronousWork();
    +         *   } finally {
    +         *     cleanUp();
    +         *   }
    +         *
    +         *   // Asynchronous promise API:
    +         *   doAsynchronousWork().thenFinally(cleanUp);
    +         * 
    + * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *
    
    +         *   try {
    +         *     throw Error('one');
    +         *   } finally {
    +         *     throw Error('two');  // Hides Error: one
    +         *   }
    +         *
    +         *   webdriver.promise.rejected(Error('one'))
    +         *       .thenFinally(function() {
    +         *         throw Error('two');  // Hides Error: one
    +         *       });
    +         * 
    + * + * + * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): webdriver.promise.Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): webdriver.promise.Promise; + } + + /** + * Contains information about a WebDriver session. + */ + class Session { + + //region Constructors + + /** + * @param {string} id The session ID. + * @param {!(Object|webdriver.Capabilities)} capabilities The session + * capabilities. + * @constructor + */ + constructor(id: string, capabilities: Capabilities|Object); + + //endregion + + //region Methods + + /** + * @return {string} This session's ID. + */ + getId(): string; + + /** + * @return {!webdriver.Capabilities} This session's capabilities. + */ + getCapabilities(): webdriver.Capabilities; + + /** + * Retrieves the value of a specific capability. + * @param {string} key The capability to retrieve. + * @return {*} The capability value. + */ + getCapability(key: string): any; + + /** + * Returns the JSON representation of this object, which is just the string + * session ID. + * @return {string} The JSON representation of this Session. + */ + toJSON(): string; + + //endregion + } +} + +declare namespace testing { + /** + * Registers a new test suite. + * @param name The suite name. + * @param fn The suite function, or {@code undefined} to define a pending test suite. + */ + function describe(name: string, fn: Function): void; + + /** + * Defines a suppressed test suite. + * @param name The suite name. + * @param fn The suite function, or {@code undefined} to define a pending test suite. + */ + function xdescribe(name: string, fn: Function): void; + + /** + * Register a function to call after the current suite finishes. + * @param fn + */ + function after(fn: Function): void; + + /** + * Register a function to call after each test in a suite. + * @param fn + */ + function afterEach(fn: Function): void; + + /** + * Register a function to call before the current suite starts. + * @param fn + */ + function before(fn: Function): void; + + /** + * Register a function to call before each test in a suite. + * @param fn + */ + function beforeEach(fn: Function): void; + + /** + * Add a test to the current suite. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ + function it(name: string, fn: Function): void; + + /** + * An alias for {@link #it()} that flags the test as the only one that should + * be run within the current suite. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ + function iit(name: string, fn: Function): void; + + /** + * Adds a test to the current suite while suppressing it so it is not run. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ + function xit(name: string, fn: Function): void; +} + +declare module 'selenium-webdriver/chrome' { + export = chrome; +} + +declare module 'selenium-webdriver/executors' { + export = executors; +} + +declare module 'selenium-webdriver' { + export = webdriver; +} + +declare module 'selenium-webdriver/testing' { + export = testing; +} diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 548048b695..e1301d5b58 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1,6 +1,6 @@ // Type definitions for Selenium WebDriverJS 2.44.0 // Project: https://code.google.com/p/selenium/ -// Definitions by: Bill Armstrong , Yuki Kokubun +// Definitions by: Bill Armstrong , Yuki Kokubun , Craig Nishina // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace chrome { diff --git a/serialport/serialport.d.ts b/serialport/serialport.d.ts index 53d8a4e92e..60c240bbda 100644 --- a/serialport/serialport.d.ts +++ b/serialport/serialport.d.ts @@ -13,10 +13,10 @@ declare module 'serialport' { pause(): void; resume(): void; disconnected(err: Error): void; - close(callback?: () => void): void; - flush(callback?: () => void): void; + close(callback?: (err:any) => void): void; + flush(callback?: (err:any) => void): void; set(options: SerialPort.setOptions, callback: () => void): void; - drain(callback?: () => void): void; + drain(callback?: (err:any) => void): void; update(options: SerialPort.updateOptions, callback?: () => void): void; static list(callback: (err: string, ports: SerialPort.portConfig[]) => void): void; static parsers: { diff --git a/shapefile/shapefile-tests.ts b/shapefile/shapefile-tests.ts new file mode 100644 index 0000000000..1a827d2706 --- /dev/null +++ b/shapefile/shapefile-tests.ts @@ -0,0 +1,19 @@ +/// +import * as shapefile from 'shapefile' + +shapefile.open('./example.shp') + .then(source => { + source.bbox + source.read() + .then(result => { + result.value + result.done + }) + }) + +shapefile.read("example.shp") + .then(result => { + result.bbox + result.features + result.type + }) diff --git a/shapefile/shapefile.d.ts b/shapefile/shapefile.d.ts new file mode 100644 index 0000000000..20a0b85c7b --- /dev/null +++ b/shapefile/shapefile.d.ts @@ -0,0 +1,31 @@ +// Type definitions for shapefile 0.5.6 +// Project: https://github.com/mbostock/shapefile +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare const shapefile: shapefile.ShapefileStatic; + +declare namespace shapefile { + interface Options { + encoding: string + highWaterMark: number + } + interface Feature { + done: boolean + value: GeoJSON.Feature + } + interface Shapefile { + bbox: Array + read(): Promise; + } + interface ShapefileStatic { + open(shp: any, dbf?: any, options?: Options): Promise; + read(shp: any, dbf?: any, options?: Options): Promise>; + } +} + +declare module "shapefile" { + export = shapefile +} diff --git a/smoothie/smoothie.d.ts b/smoothie/smoothie.d.ts index 98f205f598..c396261c52 100644 --- a/smoothie/smoothie.d.ts +++ b/smoothie/smoothie.d.ts @@ -141,6 +141,8 @@ declare module "smoothie" */ export class SmoothieChart { + options: IChartOptions; + constructor(chartOptions?: IChartOptions); /** @@ -188,5 +190,7 @@ declare module "smoothie" updateValueRange(): void; render(canvas?: HTMLCanvasElement, time?: number): void; + + static timeFormatter(date: Date): string; } } diff --git a/strftime/strftime-tests.ts b/strftime/strftime-tests.ts new file mode 100644 index 0000000000..3f24a53c48 --- /dev/null +++ b/strftime/strftime-tests.ts @@ -0,0 +1,37 @@ +/// + +import * as strftime from "strftime"; + +strftime('%B %d, %Y %H:%M:%S'); +strftime('%F %T', new Date(1307472705067)); + +var it_IT = { + days: ['domenica', 'lunedi', 'martedi', 'mercoledi', 'giovedi', 'venerdi', 'sabato'], + shortDays: ['dom', 'lun', 'mar', 'mer', 'gio', 'ven', 'sab'], + months: ['gennaio', 'febbraio', 'marzo', 'aprile', 'maggio', 'giugno', 'luglio', 'agosto', 'settembre', 'ottobre', 'novembre', 'dicembre'], + shortMonths: ['gen', 'feb', 'mar', 'apr', 'mag', 'giu', 'lug', 'ago', 'set', 'ott', 'nov', 'dic'], + AM: 'AM', + PM: 'PM', + am: 'am', + pm: 'pm', + formats: { + D: '%m/%d/%y', + F: '%Y-%m-%d', + R: '%H:%M', + X: '%T', + c: '%a %b %d %X %Y', + r: '%I:%M:%S %p', + T: '%H:%M:%S', + v: '%e-%b-%Y', + x: '%D' + } +}; + +var strftimeIT = strftime.localize(it_IT); +strftimeIT('%B %d, %Y %H:%M:%S'); +strftimeIT('%B %d, %Y %H:%M:%S', new Date(1307472705067)); + +var strftimePDT = strftime.timezone(-420); +var strftimeCEST = strftime.timezone(120); +strftimePDT('%B %d, %y %H:%M:%S', new Date(1307472705067)); +strftimeCEST('%F %T', new Date(1307472705067)); \ No newline at end of file diff --git a/strftime/strftime.d.ts b/strftime/strftime.d.ts new file mode 100644 index 0000000000..4c4b8ad835 --- /dev/null +++ b/strftime/strftime.d.ts @@ -0,0 +1,72 @@ +// Type definitions for strftime 0.9.2 +// Project: https://github.com/samsonjs/strftime +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "strftime" { + type strftimeFunction = (format: string, date?: Date) => string; + + namespace strftime { + /** + * Sets locale. + * @param {Locale} locale A locale. + * @return {strftimeFunction} A strftime function. + */ + export function localize(locale: Locale): strftimeFunction; + + /** + * Sets timezone. + * @param {number|string} offset A offset. + * @return {strftimeFunction} A strftime function. + */ + export function timezone(offset: number | string): strftimeFunction; + + /** + * Locale formats. + * @interface + */ + export interface LocaleFormats { + D?: string; + F?: string; + R?: string; + T?: string; + X?: string; + c?: string; + r?: string; + v?: string; + x?: string; + } + + /** + * Locale. + * @interface + */ + export interface Locale { + days?: Array; + shortDays?: Array; + months?: Array; + shortMonths?: Array; + AM?: string; + PM?: string; + am?: string; + pm?: string; + formats: LocaleFormats + } + } + + /** + * Format a local time/date according to locale settings + * @param {string} format A format. + * @return {string} Returns a string formatted. + */ + function strftime(format: string): string; + + /** + * Format a local time/date according to locale settings + * @param {string} format A format. + * @param {Date} date A date. + * @return {string} Returns a string formatted according format using the given date or the current local time. + */ + function strftime(format: string, date: Date): string; + export = strftime; +} diff --git a/tether-drop/tether-drop-tests.ts b/tether-drop/tether-drop-tests.ts index f67f746a7c..8976f0344c 100644 --- a/tether-drop/tether-drop-tests.ts +++ b/tether-drop/tether-drop-tests.ts @@ -24,7 +24,7 @@ d.remove(); d.toggle(); d.position(); d.destroy(); -d.element.appendChild(document.createElement("div")); +d.content.appendChild(document.createElement("div")); d.tether.position(); d.on("open", () => false); diff --git a/tether-drop/tether-drop.d.ts b/tether-drop/tether-drop.d.ts index 19c48ec7a1..8ee8ca1c02 100644 --- a/tether-drop/tether-drop.d.ts +++ b/tether-drop/tether-drop.d.ts @@ -10,7 +10,6 @@ declare class Drop { constructor(options: Drop.IDropOptions); public content: HTMLElement; - public element: HTMLElement; public tether: Tether; public open(): void; public close(): void; diff --git a/turf/turf-2.0-tests.ts b/turf/turf-2.0-tests.ts new file mode 100644 index 0000000000..45d9dbcc42 --- /dev/null +++ b/turf/turf-2.0-tests.ts @@ -0,0 +1,522 @@ +/// + +/////////////////////////////////////////// +// Tests data initialisation +/////////////////////////////////////////// + +var point1: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-75.343, 39.984] + } +}; + +var point2: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-75.534, 39.123] + } +}; + +var line: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "LineString", + "coordinates": [ + [-77.031669, 38.878605], + [-77.029609, 38.881946], + [-77.020339, 38.884084], + [-77.025661, 38.885821], + [-77.021884, 38.889563], + [-77.019824, 38.892368] + ] + } +}; + +var polygons: GeoJSON.FeatureCollection = { + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [-67.031021, 10.458102], + [-67.031021, 10.53372], + [-66.929397, 10.53372], + [-66.929397, 10.458102], + [-67.031021, 10.458102] + ]] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [-66.919784, 10.397325], + [-66.919784, 10.513467], + [-66.805114, 10.513467], + [-66.805114, 10.397325], + [-66.919784, 10.397325] + ]] + } + } + ] +}; + +var polygon1: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [105.818939,21.004714], + [105.818939,21.061754], + [105.890007,21.061754], + [105.890007,21.004714], + [105.818939,21.004714] + ]] + } +}; + +var polygon2: GeoJSON.Feature = { + "type": "Feature", + "properties": { + "fill": "#00f" + }, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [-122.520217, 45.535693], + [-122.64038, 45.553967], + [-122.720031, 45.526554], + [-122.669906, 45.507309], + [-122.723464, 45.446643], + [-122.532577, 45.408574], + [-122.487258, 45.477466], + [-122.520217, 45.535693] + ]] + } +} + +var features: GeoJSON.FeatureCollection = { + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.522259, 35.4691] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.502754, 35.463455] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.508269, 35.463245] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.516809, 35.465779] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.515372, 35.467072] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.509363, 35.463053] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.511123, 35.466601] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.518547, 35.469327] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.519706, 35.469659] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.517839, 35.466998] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.508678, 35.464942] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.514914, 35.463453] + } + } + ] +}; + +var triangle: GeoJSON.Feature = { + "type": "Feature", + "properties": { + "a": 11, + "b": 122, + "c": 44 + }, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [-75.1221, 39.57], + [-75.58, 39.18], + [-75.97, 39.86], + [-75.1221, 39.57] + ]] + } +}; + +var aggregations = [ + { + aggregation: 'sum', + inField: 'population', + outField: 'pop_sum' + }, + { + aggregation: 'average', + inField: 'population', + outField: 'pop_avg' + }, + { + aggregation: 'median', + inField: 'population', + outField: 'pop_median' + }, + { + aggregation: 'min', + inField: 'population', + outField: 'pop_min' + }, + { + aggregation: 'max', + inField: 'population', + outField: 'pop_max' + }, + { + aggregation: 'deviation', + inField: 'population', + outField: 'pop_deviation' + }, + { + aggregation: 'variance', + inField: 'population', + outField: 'pop_variance' + }, + { + aggregation: 'count', + inField: '', + outField: 'point_count' + } +]; + +/////////////////////////////////////////// +// Tests Aggregation +/////////////////////////////////////////// + +// -- Test aggregate -- +var aggregated = turf.aggregate(polygons, points, aggregations); + +// -- Test average -- +var averaged = turf.average(polygons, points, 'population', 'pop_avg'); + +// -- Test count -- +var counted = turf.count(polygons, points, 'pt_count'); + +// -- Test deviation -- +var deviated = turf.deviation(polygons, points, 'population', 'pop_deviation'); + +// -- Test max -- +var aggregated = turf.max(polygons, points, 'population', 'max'); + +// -- Test median -- +var medians = turf.median(polygons, points, 'population', 'median'); + +// -- Test min -- +var minimums = turf.min(polygons, points, 'population', 'min'); + +// -- Test sum -- +var summed = turf.sum(polygons, points, 'population', 'sum'); + +// -- Test variance -- +var varianced = turf.variance(polygons, points, 'population', 'variance'); + +/////////////////////////////////////////// +// Tests Measurement +/////////////////////////////////////////// + +// -- Test along -- +var along = turf.along(line, 1, 'miles'); + +// -- Test area -- +var area = turf.area(polygons); + +// -- Test bboxPolygon -- +var bbox = [0, 0, 10, 10]; +var poly = turf.bboxPolygon(bbox); + +// -- Test bearing -- +var bearing = turf.bearing(point1, point2); + +// -- Test center +var centerPt = turf.center(features); + +// -- Test centroid -- +var centroidPt = turf.centroid(polygon1); + +// -- Test destination -- +var distance = 50; +var bearing = 90; +var units = 'miles'; +var destination = turf.destination(point1, distance, bearing, units); + +// -- Test distance -- +var units = "miles"; +var distance = turf.distance(point1, point2, units); + +// -- Test envelope -- +var enveloped = turf.envelope(polygons); + +// -- Test extent -- +var bbox = turf.extent(polygons); + +// -- Test lineDistance +var length = turf.lineDistance(line, 'miles'); + +// -- Test midpoint -- +var midpointed = turf.midpoint(point1, point2); + +// -- Test pointOnSurface -- +var pointOnPolygon = turf.pointOnSurface(polygon1); + +// -- Test size -- +var resized = turf.size(bbox, 2); + +// -- Test square -- +var squared = turf.square(bbox); + +/////////////////////////////////////////// +// Tests Transformation +/////////////////////////////////////////// + +// -- Test bezier -- +var curved = turf.bezier(line); + +// -- Test buffer -- +var buffered = turf.buffer(point1, 500, units); + +// -- Test concave -- +var hull = turf.concave(features, 1, 'miles'); + +// -- Test convex -- +var hull = turf.convex(features); + +// -- Test difference -- +var differenced = turf.difference(polygon1, polygon2); + +// -- Test intersect -- +var intersection = turf.intersect(polygon1, polygon2); + +// -- Test merge -- +var merged = turf.merge(polygons); + +// -- Test simplify -- +var tolerance = 0.01; +var simplified = turf.simplify(polygon1, tolerance, false); + +// -- Test union -- +var union = turf.union(polygon1, polygon2); + +/////////////////////////////////////////// +// Tests Misc +/////////////////////////////////////////// + +// -- Test combine -- +var combined = turf.combine(features); + +// -- Test explode -- +var points = turf.explode(polygon1); + +// -- Test flip -- +var flipedPoint = turf.flip(point1); + +// -- Test kinks -- +var kinks = turf.kinks(polygon1); + +// -- Test lineSlice -- +var sliced = turf.lineSlice(point1, point2, line); + +// -- Test pointOnLine -- +var snapped = turf.pointOnLine(line, point1); + +/////////////////////////////////////////// +// Tests Helper +/////////////////////////////////////////// + +// -- Test featurecollection -- +var fc = turf.featurecollection([point1, point2]); + +// -- Test linestring -- +var linestring1 = turf.linestring([ + [-21.964416, 64.148203], + [-21.956176, 64.141316], + [-21.93901, 64.135924], + [-21.927337, 64.136673] +]); +var linestring2 = turf.linestring([ + [-21.929054, 64.127985], + [-21.912918, 64.134726], + [-21.916007, 64.141016], + [-21.930084, 64.14446] +], {name: 'line 1', distance: 145}); + +// -- Test point -- +var pt1 = turf.point([-75.343, 39.984]); +var pt2 = turf.point([-75.343, 39.984], {name: 'point 1', distance: 145}); + +// -- Test polygon -- +var polygon = turf.polygon([[ + [-2.275543, 53.464547], + [-2.275543, 53.489271], + [-2.215118, 53.489271], + [-2.215118, 53.464547], + [-2.275543, 53.464547] +]], { name: 'poly1', population: 400}); + +/////////////////////////////////////////// +// Tests Data +/////////////////////////////////////////// + +// -- Test filter -- +var key = "species"; +var value = "oak"; +var filtered = turf.filter(features, key, value); + +// -- Test random -- +var randomPoints = turf.random('points', 100, { + bbox: [-70, 40, -60, 60] +}); + +var randomPoints = turf.random('points', 100, { + bbox: [-70, 40, -60, 60], + num_vertices: 2, + max_radial_length: 10 +}); + +// -- Test remove -- +var filtered = turf.remove(points, 'marker-color', '#00f'); + +// -- Test sample -- +var randomPoints = turf.random('points', 1000); +var sample = turf.sample(points, 10); + +/////////////////////////////////////////// +// Tests Interpolation +/////////////////////////////////////////// + +// -- Test hexGrid -- +var cellWidth = 50; +var hexgrid = turf.hexGrid(bbox, cellWidth, units); + +// -- Test isolines -- +var breaks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; +var isolined = turf.isolines(points, 'z', 15, breaks); + +// -- Test planepoint -- +var zValue = turf.planepoint(point1, triangle); + +// -- Test pointGrid -- +var extent = [-70.823364, -33.553984, -70.473175, -33.302986]; +var cellWidth = 3; +var grid = turf.pointGrid(extent, cellWidth, units); + +// -- Test squareGrid -- +var squareGrid = turf.squareGrid(extent, cellWidth, units); + +// -- Test tin -- +var tin = turf.tin(points, 'z'); + +// -- Test triangleGrid -- +var triangleGrid = turf.triangleGrid(extent, cellWidth, units); + +/////////////////////////////////////////// +// Tests Joins +/////////////////////////////////////////// + +// -- Test inside -- +var isInside1 = turf.inside(point1, polygon); + +// -- Test tag -- +var tagged = turf.tag(points, triangleGrid, 'fill', 'marker-color'); + +// -- Test within -- +var ptsWithin = turf.within(points, polygons); + +/////////////////////////////////////////// +// Tests Classification +/////////////////////////////////////////// + +// -- Test jenks -- +var breaks = turf.jenks(points, 'population', 3); + +// -- Test nearest -- +var nearest = turf.nearest(point1, points); + +// -- Test quantile -- +var breaks = turf.quantile(points, 'population', [25, 50, 75, 99]); + +// -- Test reclass -- +var translations = [ + [0, 200, "small"], + [200, 400, "medium"], + [400, 600, "large"] +]; +var reclassed = turf.reclass(points, 'population', 'size', translations); diff --git a/turf/turf-2.0.d.ts b/turf/turf-2.0.d.ts new file mode 100644 index 0000000000..647df93398 --- /dev/null +++ b/turf/turf-2.0.d.ts @@ -0,0 +1,580 @@ +// Type definitions for Turf 2.0 +// Project: http://turfjs.org/ +// Definitions by: Guillaume Croteau +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module turf { + ////////////////////////////////////////////////////// + // Aggregation + ////////////////////////////////////////////////////// + + /** + * Calculates a series of aggregations for a set of points within a set of polygons. + * Sum, average, count, min, max, and deviation are supported. + * @param polygons Polygons with values on which to aggregate + * @param points Points to be aggregated + * @param aggregations An array of aggregation objects + * @returns Polygons with properties listed based on outField values in aggregations + */ + function aggregate(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, aggregations: Array<{aggregation: string, inField: string, outField: string}>): GeoJSON.FeatureCollection; + + /** + * Calculates the average value of a field for a set of points within a set of polygons. + * @param polygons Polygons with values on which to average + * @param points Points from which to calculate the average + * @param field The field in the points features from which to pull values to average + * @param outField The field in polygons to put results of the averages + * @returns Polygons with the value of outField set to the calculated averages + */ + function average(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, field: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Takes a set of points and a set of polygons and calculates the number of points that fall within the set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param countField A field to append to the attributes of the Polygon features representing Point counts + * @returns Polygons with countField appended + */ + function count(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, countField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the standard deviation value of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in points from which to aggregate + * @param outField The field to append to polygons representing deviation + * @returns Polygons with appended field representing deviation + */ + function deviation(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the maximum value of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in input data to analyze + * @param outField The field in which to store results + * @returns Polygons with properties listed as outField values + */ + function max(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the median value of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in input data to analyze + * @param outField The field in which to store results + * @returns Polygons with properties listed as outField values + */ + function median(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the minimum value of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in input data to analyze + * @param outField The field in which to store results + * @returns Polygons with properties listed as outField values + */ + function min(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the sum of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in input data to analyze + * @param outField The field in which to store results + * @returns Polygons with properties listed as outField + */ + function sum(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the variance value of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in input data to analyze + * @param outField The field in which to store results + * @returns Polygons with properties listed as outField + */ + function variance(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + ////////////////////////////////////////////////////// + // Measurement + ////////////////////////////////////////////////////// + + /** + * Takes a line and returns a point at a specified distance along the line. + * @param line Input line + * @param distance Distance along the line + * @param [units=miles] 'miles', 'kilometers', 'radians' or 'degrees' + * @returns Point along the line + */ + function along(line: GeoJSON.Feature, distance: number, units?: string): GeoJSON.Feature; + + /** + * Takes one or more features and returns their area in square meters. + * @param input Input features + * @returns Area in square meters + */ + function area(input: GeoJSON.Feature | GeoJSON.FeatureCollection): number; + + /** + * Takes a bbox and returns an equivalent polygon. + * @param bbox An Array of bounding box coordinates in the form: [xLow, yLow, xHigh, yHigh] + * @returns A Polygon representation of the bounding box + */ + function bboxPolygon(bbox: Array): GeoJSON.Feature; + + /** + * Takes two points and finds the geographic bearing between them. + * @param start Starting Point + * @param end Ending point + * @returns Bearing in decimal degrees + */ + function bearing(start: GeoJSON.Feature, end: GeoJSON.Feature): number; + + /** + * Takes a FeatureCollection and returns the absolute center point of all features. + * @param features Input features + * @returns A Point feature at the absolute center point of all input features + */ + function center(features: GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes one or more features and calculates the centroid using the arithmetic mean of all vertices. + * This lessens the effect of small islands and artifacts when calculating the centroid of a set of polygons. + * @param features Input features + * @returns The centroid of the input features + */ + function centroid(features: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes a Point and calculates the location of a destination point given a distance in degrees, radians, miles, or kilometers; and bearing in degrees. + * This uses the Haversine formula to account for global curvature. + * @param start Starting point + * @param distance Distance from the starting point + * @param bearing Ranging from -180 and 180 + * @param units 'miles', 'kilometers', 'radians', or 'degrees' + * @returns Destination point + */ + function destination(start: GeoJSON.Feature, distance: number, bearing: number, units: string): GeoJSON.Feature; + + /** + * Calculates the distance between two points in degress, radians, miles, or kilometers. + * This uses the Haversine formula to account for global curvature. + * @param from Origin point + * @param to Destination point + * @param [units=kilometers] 'miles', 'kilometers', 'radians', or 'degrees' + * @returns Distance between the two points + */ + function distance(from: GeoJSON.Feature, to: GeoJSON.Feature, units?: string): number; + + /** + * Takes any number of features and returns a rectangular Polygon that encompasses all vertices. + * @param fc Input features + * @returns A rectangular Polygon feature that encompasses all vertices + */ + function envelope(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes a set of features, calculates the extent of all input features, and returns a bounding box. + * @param input Input features + * @returns The bounding box of input given as an array in WSEN order (west, south, east, north) + */ + function extent(input: GeoJSON.Feature | GeoJSON.FeatureCollection): Array; + + /** + * Takes a line and measures its length in the specified units. + * @param line Line to measure + * @param units 'miles', 'kilometers', 'radians', or 'degrees' + * @returns Length of the input line + */ + function lineDistance(line: GeoJSON.Feature, units: string): number; + + /** + * Takes two points and returns a point midway between them. + * @param pt1 First point + * @param pt2 Second point + * @returns A point midway between pt1 and pt2 + */ + function midpoint(pt1: GeoJSON.Feature, pt2: GeoJSON.Feature): GeoJSON.Feature; + + /** + * Takes a feature and returns a Point guaranteed to be on the surface of the feature. Given a Polygon, the point will be in the area of the polygon. + * Given a LineString, the point will be along the string. Given a Point, the point will the same as the input. + * @param input Any feature or set of features + * @returns A point on the surface of input + */ + function pointOnSurface(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes a bounding box and returns a new bounding box with a size expanded or contracted by a factor of X. + * @param bbox A bounding box + * @param factor The ratio of the new bbox to the input bbox + * @returns The resized bbox + */ + function size(bbox: Array, factor: number): Array; + + /** + * Takes a bounding box and calculates the minimum square bounding box that would contain the input. + * @param bbox A bounding box + * @returns A square surrounding bbox + */ + function square(bbox: Array): Array; + + ////////////////////////////////////////////////////// + // Transformation + ////////////////////////////////////////////////////// + + /** + * Takes a line and returns a curved version by applying a Bezier spline algorithm. + * The bezier spline implementation is by Leszek Rybicki. + * @param line Input LineString + * @param [resolution=10000] Time in milliseconds between points + * @param [sharpness=0.85] A measure of how curvy the path should be between splines + * @returns Curved line + */ + function bezier(line: GeoJSON.Feature, resolution?: number, sharpness?: number): GeoJSON.Feature; + + /** + * Calculates a buffer for input features for a given radius. Units supported are miles, kilometers, and degrees. + * @param feature Input to be buffered + * @param distance Distance to draw the buffer + * @param units 'miles', 'kilometers', 'radians', or 'degrees' + * @returns Buffered features + */ + function buffer(feature: GeoJSON.Feature | GeoJSON.FeatureCollection, distance: number, units: string): GeoJSON.FeatureCollection | GeoJSON.FeatureCollection | GeoJSON.Polygon | GeoJSON.MultiPolygon; + + /** + * Takes a set of points and returns a concave hull polygon. Internally, this implements a Monotone chain algorithm. + * @param points Input points + * @param maxEdge The size of an edge necessary for part of the hull to become concave (in miles) + * @param units Used for maxEdge distance (miles or kilometers) + * @returns A concave hull + */ + function concave(points: GeoJSON.FeatureCollection, maxEdge: number, units: string): GeoJSON.Feature; + + /** + * Takes a set of points and returns a convex hull polygon. Internally this uses the convex-hull module that implements a monotone chain hull. + * @param input Input points + * @returns A convex hull + */ + function convex(input: GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Finds the difference between two polygons by clipping the second polygon from the first. + * @param poly1 Input Polygon feaure + * @param poly2 Polygon feature to difference from poly1 + * @returns A Polygon feature showing the area of poly1 excluding the area of poly2 + */ + function difference(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; + + /** + * Takes two polygons and finds their intersection. + * If they share a border, returns the border; if they don't intersect, returns undefined. + * @param poly1 The first polygon + * @param poly2 The second polygon + * @returns If poly1 and poly2 overlap, returns a Polygon feature representing the area they overlap; + * if poly1 and poly2 do not overlap, returns undefined; + * if poly1 and poly2 share a border, a MultiLineString of the locations where their borders are shared + */ + function intersect(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature | typeof undefined; + + /** + * Takes a set of polygons and returns a single merged polygon feature. + * If the input polygon features are not contiguous, this function returns a MultiPolygon feature. + * @param fc Input polygons + * @returns Merged polygon or multipolygon + */ + function merge(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes a LineString or Polygon and returns a simplified version. + * Internally uses simplify-js to perform simplification. + * @param feature Feature to be simplified + * @param tolerance Simplification tolerance + * @param highQuality Whether or not to spend more time to create a higher-quality simplification with a different algorithm + * @returns A simplified feature + */ + function simplify(feature: GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection, tolerance: number, highQuality: boolean): GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection; + + /** + * Takes two polygons and returns a combined polygon. + * If the input polygons are not contiguous, this function returns a MultiPolygon feature. + * @param poly1 Input polygon + * @param poly2 Another input polygon + * @returns A combined Polygon or MultiPolygon feature + */ + function union(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; + + ////////////////////////////////////////////////////// + // Misc + ////////////////////////////////////////////////////// + + /** + * Combines a FeatureCollection of Point, LineString, or Polygon features into MultiPoint, MultiLineString, or MultiPolygon features. + * @param fc A FeatureCollection of any type + * @returns A FeatureCollection of corresponding type to input + */ + function combine(fc: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + + /** + * Takes a feature or set of features and returns all positions as points. + * @param input Input features + * @returns Points representing the exploded input features + */ + function explode(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + + /** + * Takes input features and flips all of their coordinates from [x, y] to [y, x]. + * @param input Input features + * @returns A feature or set of features of the same type as input with flipped coordinates + */ + function flip(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature | GeoJSON.FeatureCollection; + + /** + * Takes a polygon and returns points at all self-intersections. + * @param polygon Input polygon + * @returns Self-intersections + */ + function kinks(polygon: GeoJSON.Feature): GeoJSON.FeatureCollection; + + /** + * Takes a line, a start Point, and a stop point and returns the line in between those points. + * @param point1 Starting point + * @param point2 Stopping point + * @param line Line to slice + * @returns Sliced line + */ + function lineSlice(point1: GeoJSON.Feature, point2: GeoJSON.Feature, line: GeoJSON.Feature): GeoJSON.Feature; + + /** + * Takes a Point and a LineString and calculates the closest Point on the LineString. + * @param line Line to snap to + * @param point Point to snap from + * @returns Closest point on the line to point + */ + function pointOnLine(line: GeoJSON.Feature, point: GeoJSON.Feature): GeoJSON.Feature; + + ////////////////////////////////////////////////////// + // Helper + ////////////////////////////////////////////////////// + + /** + * Takes one or more Features and creates a FeatureCollection. + * @param features Input features + * @returns A FeatureCollection of input features + */ + function featurecollection(features: Array>): GeoJSON.FeatureCollection; + + /** + * Creates a LineString based on a coordinate array. Properties can be added optionally. + * @param coordinates An array of Positions + * @param [properties] An Object of key-value pairs to add as properties + * @returns A LineString feature + */ + function linestring(coordinates: Array>, properties?: any): GeoJSON.Feature; + + /** + * Takes coordinates and properties (optional) and returns a new Point feature. + * @param coordinates Longitude, latitude position (each in decimal degrees) + * @param [properties] An Object of key-value pairs to add as properties + * @returns A Point feature + */ + function point(coordinates: Array, properties?: any): GeoJSON.Feature; + + /** + * Takes an array of LinearRings and optionally an Object with properties and returns a Polygon feature. + * @param rings An array of LinearRings + * @param [properties] An Object of key-value pairs to add as properties + * @returns A Polygon feature + */ + function polygon(rings: Array>>, properties?: any): GeoJSON.Feature; + + ////////////////////////////////////////////////////// + // Data + ////////////////////////////////////////////////////// + + /** + * Takes a FeatureCollection and filters it by a given property and value. + * @param features Input features + * @param key The property on which to filter + * @param value The value of that property on which to filter + * @returns A filtered collection with only features that match input key and value + */ + function filter(features: GeoJSON.FeatureCollection, key: string, value: string): GeoJSON.FeatureCollection; + + /** + * Generates random GeoJSON data, including Points and Polygons, for testing and experimentation. + * @param [type='point'] Type of features desired: 'points' or 'polygons' + * @param [count=1] How many geometries should be generated. + * @param [options] Options relevant to the feature desired. Can include: + * - A bounding box inside of which geometries are placed. In the case of Point features, they are guaranteed to be within this bounds, while Polygon features have their centroid within the bounds. + * - The number of vertices added to polygon features. Default is 10; + * - The total number of decimal degrees longitude or latitude that a polygon can extent outwards to from its center. Default is 10. + * @returns Generated random features + */ + function random(type?: string, count?: number, options?: {bbox?: Array; num_vertices?: number; max_radial_length?: number;}): GeoJSON.FeatureCollection; + + /** + * Takes a FeatureCollection of any type, a property, and a value and returns a FeatureCollection with features matching that property-value pair removed. + * @param features Set of input features + * @param property The property to remove + * @param value The value to remove + * @returns The resulting FeatureCollection without features that match the property-value pair + */ + function remove(features: GeoJSON.FeatureCollection, property: string, value: string): GeoJSON.FeatureCollection; + + /** + * Takes a FeatureCollection and returns a FeatureCollection with given number of features at random. + * @param features Set of input features + * @param n Number of features to select + * @returns A FeatureCollection with n features + */ + function sample(features: GeoJSON.FeatureCollection, n: number): GeoJSON.FeatureCollection; + + ////////////////////////////////////////////////////// + // Interpolation + ////////////////////////////////////////////////////// + + /** + * Takes a bounding box and a cell size in degrees and returns a FeatureCollection of flat-topped hexagons (Polygon features) aligned in an "odd-q" vertical grid as described in Hexagonal Grids. + * @param bbox Bounding box in [minX, minY, maxX, maxY] order + * @param cellWidth Width of cell in specified units + * @param units Used in calculating cellWidth ('miles' or 'kilometers') + * @returns A hexagonal grid + */ + function hexGrid(bbox: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + + /** + * Takes points with z-values and an array of value breaks and generates isolines. + * @param points Input points + * @param z The property name in points from which z-values will be pulled + * @param resolution Resolution of the underlying grid + * @param breaks Where to draw contours + * @returns Isolines + */ + function isolines(points: GeoJSON.FeatureCollection, z: string, resolution: number, breaks: Array): GeoJSON.FeatureCollection; + + /** + * Takes a triangular plane as a Polygon and a Point within that triangle and returns the z-value at that point. + * The Polygon needs to have properties a, b, and c that define the values at its three corners. + * @param interpolatedPoint The Point for which a z-value will be calculated + * @param triangle A Polygon feature with three vertices + * @returns The z-value for interpolatedPoint + */ + function planepoint(interpolatedpoint: GeoJSON.Feature, triangle: GeoJSON.Feature): number; + + /** + * Takes a bounding box and a cell depth and returns a set of points in a grid. + * @param extent Extent in [minX, minY, maxX, maxY] order + * @param cellWidth The distance across each cell + * @param units Used in calculating cellWidth ('miles' or 'kilometers') + * @returns Grid of points + */ + function pointGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + + /** + * Takes a bounding box and a cell depth and returns a set of square polygons in a grid. + * @param extent Extent in [minX, minY, maxX, maxY] order + * @param cellWidth Width of each cell + * @param units Used in calculating cellWidth ('miles' or 'kilometers') + * @returns Grid of polygons + */ + function squareGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + + /** + * Takes a set of points and the name of a z-value property and creates a Triangulated Irregular Network, or a TIN for short, returned as a collection of Polygons. + * These are often used for developing elevation contour maps or stepped heat visualizations. + * This triangulates the points, as well as adds properties called a, b, and c representing the value of the given propertyName at each of the points that represent the corners of the triangle. + * @param points Input points + * @param [propertyName] Name of the property from which to pull z values This is optional: if not given, then there will be no extra data added to the derived triangles. + * @returns TIN output + */ + function tin(points: GeoJSON.FeatureCollection, propertyName?: string): GeoJSON.FeatureCollection; + + /** + * Takes a bounding box and a cell depth and returns a set of triangular polygons in a grid. + * @param extent Extent in [minX, minY, maxX, maxY] order + * @param cellWidth Width of each cell + * @param units Used in calculating cellWidth ('miles' or 'kilometers') + * @returns Grid of triangles + */ + function triangleGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + + ////////////////////////////////////////////////////// + // Joins + ////////////////////////////////////////////////////// + + /** + * Takes a Point and a Polygon or MultiPolygon and determines if the point resides inside the polygon. + * The polygon can be convex or concave. The function accounts for holes. + * @param point Input point + * @param polygon Input polygon or multipolygon + * @returns true if the Point is inside the Polygon; false if the Point is not inside the Polygon + */ + function inside(point: GeoJSON.Feature, polygon: GeoJSON.Feature): boolean; + + /** + * Takes a set of points and a set of polygons and performs a spatial join. + * @param points Input points + * @param polygons Input polygons + * @param polyId Property in polygons to add to joined Point features + * @param containingPolyId Property in points in which to store joined property from polygons + * @returns Points with containingPolyId property containing values from polyId + */ + function tag(points: GeoJSON.FeatureCollection, polygons: GeoJSON.FeatureCollection, polyId: string, containingPolyId: string): GeoJSON.FeatureCollection; + + /** + * Takes a set of points and a set of polygons and returns the points that fall within the polygons. + * @param points Input points + * @param polygons Input polygons + * @returns Points that land within at least one polygon + */ + function within(points: GeoJSON.FeatureCollection, polygons: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + + ////////////////////////////////////////////////////// + // Classification + ////////////////////////////////////////////////////// + + /** + * Takes a set of features and returns an array of the Jenks Natural breaks for a given property. + * @param input Input features + * @param field The property in input on which to calculate Jenks natural breaks + * @param numberOfBreaks Number of classes in which to group the data + * @returns The break number for each class plus the minimum and maximum values + */ + function jenks(input: GeoJSON.FeatureCollection, field: string, numberOfBreaks: number): Array; + + /** + * Takes a reference point and a set of points and returns the point from the set closest to the reference. + * @param point The reference point + * @param against Input point set + * @returns The closest point in the set to the reference point + */ + function nearest(point: GeoJSON.Feature, against: GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes a FeatureCollection, a property name, and a set of percentiles and returns a quantile array. + * @param input Set of features + * @param field The property in input from which to retrieve quantile values + * @param percentiles An Array of percentiles on which to calculate quantile values + * @returns An array of the break values + */ + function quantile(input: GeoJSON.FeatureCollection, field: string, percentiles: Array): Array; + + /** + * Takes a FeatureCollection, an input field, an output field, and an array of translations and outputs an identical FeatureCollection with the output field property populated. + * @param input Set of input features + * @param inField The field to translate + * @param outField The field in which to store translated results + * @param translations An array of translations + * @returns A FeatureCollection with identical geometries to input but with outField populated. + */ + function reclass(input: GeoJSON.FeatureCollection, inField: string, outField: string, translations: Array): GeoJSON.FeatureCollection; +} + +declare module 'turf' { + export= turf; +} diff --git a/turf/turf-tests.ts b/turf/turf-tests.ts index e671035892..31462adc51 100644 --- a/turf/turf-tests.ts +++ b/turf/turf-tests.ts @@ -1,28 +1,114 @@ /// +import * as turf from '@turf/turf' +// AGGREGATION +import * as collect from '@turf/collect' +// MEASUREMENT +import * as along from '@turf/along' +import * as area from '@turf/area' +import * as bboxPolygon from '@turf/bbox-polygon' +import * as bearing from '@turf/bearing' +import * as center from '@turf/center' +import * as centroid from '@turf/centroid' +import * as destination from '@turf/destination' +import * as envelope from '@turf/envelope' +import * as lineDistance from '@turf/line-distance' +import * as midpoint from '@turf/midpoint' +import * as pointOnSurce from '@turf/point-on-surface' +import * as square from '@turf/square' +// TRANSFORMATION +import * as bezier from '@turf/bezier' +import * as buffer from '@turf/buffer' +import * as concave from '@turf/concave' +import * as convex from '@turf/convex' +import * as difference from '@turf/difference' +import * as intersect from '@turf/intersect' +import * as simplify from '@turf/simplify' +import * as union from '@turf/union' +// MISC +import * as combine from '@turf/combine' +import * as explode from '@turf/explode' +import * as flip from '@turf/flip' +import * as kinks from '@turf/kinks' +import * as lineSlice from '@turf/line-slice' +import * as pointOnLine from '@turf/point-on-line' +// HELPER +import { + featureCollection, + feature, + lineString, + multiLineString, + point, + multiPoint, + polygon, + multiPolygon, + geometryCollection } from '@turf/helpers' +// DATA +import * as random from '@turf/random' +import * as sample from '@turf/sample' +// INTERPOLATION +import * as isolines from '@turf/isolines' +import * as planepoint from '@turf/planepoint' +import * as tin from '@turf/tin' +// JOINS +import * as inside from '@turf/inside' +import * as tag from '@turf/tag' +import * as within from '@turf/within' +// GRIDS +import * as hexGrid from '@turf/hex-grid' +import * as pointGrid from '@turf/point-grid' +import * as squareGrid from '@turf/square-grid' +import * as triangleGrid from '@turf/triangle-grid' +// CLASSIFICATION +import * as nearest from '@turf/nearest' +// // META +// import * as propEach from '@turf/propEach' +// import * as coordEach from '@turf/coordEach' +// import * as coordReduce from '@turf/coordReduce' +// import * as featureEach from '@turf/featureEach' +// import * as getCoord from '@turf/getCoord' +// // ASSERTIONS +// import * as featureOf from '@turf/featureOf' +// import * as collectionOf from '@turf/collectionOf' +import * as bboxAssertions from '@turf/bbox' +// import * as circle from '@turf/circle' +// import * as geojsonType from '@turf/geojsonType' +// import * as propReduce from '@turf/propReduce' +// import * as coordAll from '@turf/coordAll' +// import * as tesselate from '@turf/tesselate' /////////////////////////////////////////// // Tests data initialisation /////////////////////////////////////////// - -var point1: GeoJSON.Feature = { +const bbox = [0, 0, 10, 10] +const properties = {pop: 3000} +const point1: GeoJSON.Feature = { "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [-75.343, 39.984] } -}; +} -var point2: GeoJSON.Feature = { +const point2: GeoJSON.Feature = { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-75.534, 39.123] - } -}; + "coordinates": [-75.401, 39.884] + } +} -var line: GeoJSON.Feature = { +const multiPoint1: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "MultiPoint", + "coordinates": [ [100.0, 0.0], [101.0, 1.0] ] + } +} + +const lineString1: GeoJSON.Feature = { "type": "Feature", "properties": {}, "geometry": { @@ -36,9 +122,21 @@ var line: GeoJSON.Feature = { [-77.019824, 38.892368] ] } -}; +} -var polygons: GeoJSON.FeatureCollection = { +const multiLineString1: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "MultiLineString", + "coordinates": [ + [ [100.0, 0.0], [101.0, 1.0] ], + [ [102.0, 2.0], [103.0, 3.0] ] + ] + } +} + +const polygons: GeoJSON.FeatureCollection = { "type": "FeatureCollection", "features": [ { @@ -69,9 +167,9 @@ var polygons: GeoJSON.FeatureCollection = { } } ] -}; +} -var polygon1: GeoJSON.Feature = { +const polygon1: GeoJSON.Feature = { "type": "Feature", "properties": {}, "geometry": { @@ -84,13 +182,11 @@ var polygon1: GeoJSON.Feature = { [105.818939,21.004714] ]] } -}; +} -var polygon2: GeoJSON.Feature = { +const polygon2: GeoJSON.Feature = { "type": "Feature", - "properties": { - "fill": "#00f" - }, + "properties": {}, "geometry": { "type": "Polygon", "coordinates": [[ @@ -106,7 +202,20 @@ var polygon2: GeoJSON.Feature = { } } -var features: GeoJSON.FeatureCollection = { +const multiPolygon1: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "MultiPolygon", + "coordinates": [ + [[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]], + [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]], + [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]] + ] + } +} + +const points: GeoJSON.FeatureCollection = { "type": "FeatureCollection", "features": [ { @@ -114,96 +223,50 @@ var features: GeoJSON.FeatureCollection = { "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.522259, 35.4691] + "coordinates": [-63.601226, 44.642643] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.502754, 35.463455] + "coordinates": [-63.591442, 44.651436] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.508269, 35.463245] + "coordinates": [-63.580799, 44.648749] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.516809, 35.465779] + "coordinates": [-63.573589, 44.641788] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.515372, 35.467072] + "coordinates": [-63.587665, 44.64533] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.509363, 35.463053] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.511123, 35.466601] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.518547, 35.469327] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.519706, 35.469659] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.517839, 35.466998] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.508678, 35.464942] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.514914, 35.463453] + "coordinates": [-63.595218, 44.64765] } } ] -}; +} -var triangle: GeoJSON.Feature = { +const triangle: GeoJSON.Feature = { "type": "Feature", - "properties": { - "a": 11, - "b": 122, - "c": 44 - }, + "properties": {}, "geometry": { "type": "Polygon", "coordinates": [[ @@ -213,310 +276,231 @@ var triangle: GeoJSON.Feature = { [-75.1221, 39.57] ]] } -}; - -var aggregations = [ - { - aggregation: 'sum', - inField: 'population', - outField: 'pop_sum' - }, - { - aggregation: 'average', - inField: 'population', - outField: 'pop_avg' - }, - { - aggregation: 'median', - inField: 'population', - outField: 'pop_median' - }, - { - aggregation: 'min', - inField: 'population', - outField: 'pop_min' - }, - { - aggregation: 'max', - inField: 'population', - outField: 'pop_max' - }, - { - aggregation: 'deviation', - inField: 'population', - outField: 'pop_deviation' - }, - { - aggregation: 'variance', - inField: 'population', - outField: 'pop_variance' - }, - { - aggregation: 'count', - inField: '', - outField: 'point_count' - } -]; - -/////////////////////////////////////////// -// Tests Aggregation -/////////////////////////////////////////// - -// -- Test aggregate -- -var aggregated = turf.aggregate(polygons, points, aggregations); - -// -- Test average -- -var averaged = turf.average(polygons, points, 'population', 'pop_avg'); - -// -- Test count -- -var counted = turf.count(polygons, points, 'pt_count'); - -// -- Test deviation -- -var deviated = turf.deviation(polygons, points, 'population', 'pop_deviation'); - -// -- Test max -- -var aggregated = turf.max(polygons, points, 'population', 'max'); - -// -- Test median -- -var medians = turf.median(polygons, points, 'population', 'median'); - -// -- Test min -- -var minimums = turf.min(polygons, points, 'population', 'min'); - -// -- Test sum -- -var summed = turf.sum(polygons, points, 'population', 'sum'); - -// -- Test variance -- -var varianced = turf.variance(polygons, points, 'population', 'variance'); +} /////////////////////////////////////////// // Tests Measurement /////////////////////////////////////////// // -- Test along -- -var along = turf.along(line, 1, 'miles'); +turf.along(lineString1, 50) +turf.along(lineString1, 50, 'miles') // -- Test area -- -var area = turf.area(polygons); +turf.area(polygons) // -- Test bboxPolygon -- -var bbox = [0, 0, 10, 10]; -var poly = turf.bboxPolygon(bbox); +turf.bboxPolygon(bbox) // -- Test bearing -- -var bearing = turf.bearing(point1, point2); +turf.bearing(point1, point2) // -- Test center -var centerPt = turf.center(features); +turf.center(points) // -- Test centroid -- -var centroidPt = turf.centroid(polygon1); +turf.centroid(polygon1) // -- Test destination -- -var distance = 50; -var bearing = 90; -var units = 'miles'; -var destination = turf.destination(point1, distance, bearing, units); +turf.destination(point1, 50, 90) +turf.destination(point1, 50, 90, 'miles') // -- Test distance -- -var units = "miles"; -var distance = turf.distance(point1, point2, units); +turf.distance(point1, point2) +turf.distance(point1, point2, 'miles') // -- Test envelope -- -var enveloped = turf.envelope(polygons); - -// -- Test extent -- -var bbox = turf.extent(polygons); +turf.envelope(polygons) // -- Test lineDistance -var length = turf.lineDistance(line, 'miles'); +turf.lineDistance(lineString1) +turf.lineDistance(lineString1, 'miles') // -- Test midpoint -- -var midpointed = turf.midpoint(point1, point2); +turf.midpoint(point1, point2) // -- Test pointOnSurface -- -var pointOnPolygon = turf.pointOnSurface(polygon1); - -// -- Test size -- -var resized = turf.size(bbox, 2); +turf.pointOnSurface(polygon1) // -- Test square -- -var squared = turf.square(bbox); +turf.square(bbox) /////////////////////////////////////////// // Tests Transformation /////////////////////////////////////////// // -- Test bezier -- -var curved = turf.bezier(line); +turf.bezier(lineString1) // -- Test buffer -- -var buffered = turf.buffer(point1, 500, units); +turf.buffer(point1, 50) +turf.buffer(point1, 50, 'miles') // -- Test concave -- -var hull = turf.concave(features, 1, 'miles'); +turf.concave(points, 1, 'miles') // -- Test convex -- -var hull = turf.convex(features); +turf.convex(points) // -- Test difference -- -var differenced = turf.difference(polygon1, polygon2); +turf.difference(polygon1, polygon2) // -- Test intersect -- -var intersection = turf.intersect(polygon1, polygon2); - -// -- Test merge -- -var merged = turf.merge(polygons); +turf.intersect(polygon1, polygon2) +turf.intersect(point1, polygon1) +turf.intersect(point1, point1) +turf.intersect(polygon1, point1) +turf.intersect(polygon1, lineString1) +turf.intersect(lineString1, point1) // -- Test simplify -- -var tolerance = 0.01; -var simplified = turf.simplify(polygon1, tolerance, false); + +turf.simplify(polygon1, 0.01, false) // -- Test union -- -var union = turf.union(polygon1, polygon2); +turf.union(polygon1, polygon2) /////////////////////////////////////////// // Tests Misc /////////////////////////////////////////// // -- Test combine -- -var combined = turf.combine(features); +turf.combine(points) // -- Test explode -- -var points = turf.explode(polygon1); +turf.explode(polygon1) // -- Test flip -- -var flipedPoint = turf.flip(point1); +turf.flip(point1) // -- Test kinks -- -var kinks = turf.kinks(polygon1); +turf.kinks(polygon1) // -- Test lineSlice -- -var sliced = turf.lineSlice(point1, point2, line); +turf.lineSlice(point1, point2, lineString1) // -- Test pointOnLine -- -var snapped = turf.pointOnLine(line, point1); +turf.pointOnLine(lineString1, point1) /////////////////////////////////////////// // Tests Helper /////////////////////////////////////////// // -- Test featurecollection -- -var fc = turf.featurecollection([point1, point2]); +turf.featureCollection([point1, point2]) +turf.featureCollection([point1, polygon1]) +turf.featureCollection([polygon1, polygon2]) +turf.featureCollection([lineString1, polygon1]) +turf.featureCollection([lineString1, point1]) -// -- Test linestring -- -var linestring1 = turf.linestring([ - [-21.964416, 64.148203], - [-21.956176, 64.141316], - [-21.93901, 64.135924], - [-21.927337, 64.136673] -]); -var linestring2 = turf.linestring([ - [-21.929054, 64.127985], - [-21.912918, 64.134726], - [-21.916007, 64.141016], - [-21.930084, 64.14446] -], {name: 'line 1', distance: 145}); +// -- Test feature -- +turf.feature(point1) +turf.feature(polygon1) +turf.feature(lineString1) + +// -- Test lineString -- +turf.lineString(lineString1.geometry.coordinates) +turf.lineString(lineString1.geometry.coordinates, properties) + +// -- Test multiLineString -- +turf.multiLineString(multiLineString1.geometry.coordinates) // -- Test point -- -var pt1 = turf.point([-75.343, 39.984]); -var pt2 = turf.point([-75.343, 39.984], {name: 'point 1', distance: 145}); +turf.point(point1.geometry.coordinates) +turf.point(point1.geometry.coordinates, properties) + +// -- Test multiPoint -- +turf.multiPoint(multiPoint1.geometry.coordinates) // -- Test polygon -- -var polygon = turf.polygon([[ - [-2.275543, 53.464547], - [-2.275543, 53.489271], - [-2.215118, 53.489271], - [-2.215118, 53.464547], - [-2.275543, 53.464547] -]], { name: 'poly1', population: 400}); +turf.polygon(polygon1.geometry.coordinates, properties) + +// -- Test multiPolygon -- +turf.multiPolygon(multiPolygon1.geometry.coordinates, properties) + +// -- Test geometryCollection -- +turf.geometryCollection([point1.geometry, lineString1.geometry]); /////////////////////////////////////////// // Tests Data /////////////////////////////////////////// -// -- Test filter -- -var key = "species"; -var value = "oak"; -var filtered = turf.filter(features, key, value); - // -- Test random -- -var randomPoints = turf.random('points', 100, { - bbox: [-70, 40, -60, 60] -}); - -var randomPoints = turf.random('points', 100, { - bbox: [-70, 40, -60, 60], - num_vertices: 2, +turf.random('points', 100) +turf.random('points', 100, { bbox }) +turf.random('polygons', 100, { + bbox, + num_vertices: 10, max_radial_length: 10 -}); - -// -- Test remove -- -var filtered = turf.remove(points, 'marker-color', '#00f'); +}) // -- Test sample -- -var randomPoints = turf.random('points', 1000); -var sample = turf.sample(points, 10); +turf.random('points', 100) +turf.sample(points, 10) /////////////////////////////////////////// // Tests Interpolation /////////////////////////////////////////// // -- Test hexGrid -- -var cellWidth = 50; -var hexgrid = turf.hexGrid(bbox, cellWidth, units); - -// -- Test isolines -- -var breaks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; -var isolined = turf.isolines(points, 'z', 15, breaks); - -// -- Test planepoint -- -var zValue = turf.planepoint(point1, triangle); +turf.hexGrid(bbox, 50) +turf.hexGrid(bbox, 50, 'miles') // -- Test pointGrid -- -var extent = [-70.823364, -33.553984, -70.473175, -33.302986]; -var cellWidth = 3; -var grid = turf.pointGrid(extent, cellWidth, units); +turf.pointGrid(bbox, 50) +turf.pointGrid(bbox, 50, 'miles') // -- Test squareGrid -- -var squareGrid = turf.squareGrid(extent, cellWidth, units); - -// -- Test tin -- -var tin = turf.tin(points, 'z'); +turf.squareGrid(bbox, 50) +turf.squareGrid(bbox, 50, 'miles') // -- Test triangleGrid -- -var triangleGrid = turf.triangleGrid(extent, cellWidth, units); +turf.triangleGrid(bbox, 50) +turf.triangleGrid(bbox, 50, 'miles') + +/////////////////////////////////////////// +// Tests Interpolation +/////////////////////////////////////////// + +// -- Test isolines -- +turf.isolines(points, 'z', 15, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + +// -- Test planepoint -- +turf.planepoint(point1, triangle) + +// -- Test tin -- +turf.tin(points, 'z') /////////////////////////////////////////// // Tests Joins /////////////////////////////////////////// // -- Test inside -- -var isInside1 = turf.inside(point1, polygon); +turf.inside(point1, polygon1) // -- Test tag -- -var tagged = turf.tag(points, triangleGrid, 'fill', 'marker-color'); +turf.tag(points, polygons, 'pop', 'population') // -- Test within -- -var ptsWithin = turf.within(points, polygons); +turf.within(points, polygons) /////////////////////////////////////////// // Tests Classification /////////////////////////////////////////// -// -- Test jenks -- -var breaks = turf.jenks(points, 'population', 3); - // -- Test nearest -- -var nearest = turf.nearest(point1, points); +turf.nearest(point1, points) -// -- Test quantile -- -var breaks = turf.quantile(points, 'population', [25, 50, 75, 99]); +/////////////////////////////////////////// +// Tests Aggregation +/////////////////////////////////////////// +turf.collect(polygons, points, 'population', 'values') -// -- Test reclass -- -var translations = [ - [0, 200, "small"], - [200, 400, "medium"], - [400, 600, "large"] -]; -var reclassed = turf.reclass(points, 'population', 'size', translations); +/////////////////////////////////////////// +// Tests Assertions +/////////////////////////////////////////// +turf.bbox(polygon1) +turf.bbox(point1) +turf.bbox(lineString1) +turf.bbox(multiLineString1) +turf.bbox(multiPolygon1) \ No newline at end of file diff --git a/turf/turf.d.ts b/turf/turf.d.ts index 647df93398..e90cf69276 100644 --- a/turf/turf.d.ts +++ b/turf/turf.d.ts @@ -1,103 +1,130 @@ -// Type definitions for Turf 2.0 +// Type definitions for Turf 3.5.2 // Project: http://turfjs.org/ -// Definitions by: Guillaume Croteau +// Definitions by: Guillaume Croteau , Denis Carriere // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +/** +#### TODO: + +Update all methods with newest JSDocs & tests based on the latest TurfJS library. + +AGGREGATION +- [x] collect +MEASUREMENT +- [ ] along +- [ ] area +- [ ] bboxPolygon +- [ ] bearing +- [ ] center +- [ ] centroid +- [ ] destination +- [ ] distance +- [ ] envelope +- [ ] lineDistance +- [ ] midpoint +- [ ] pointOnSurface +- [ ] square +TRANSFORMATION +- [ ] bezier +- [ ] buffer +- [ ] concave +- [ ] convex +- [ ] difference +- [ ] intersect +- [ ] simplify +- [ ] union +MISC +- [ ] combine +- [ ] explode +- [ ] flip +- [ ] kinks +- [ ] lineSlice +- [ ] pointOnLine +HELPER +- [x] featureCollection +- [x] feature +- [x] lineString +- [x] multiLineString +- [x] point +- [x] multiPoint +- [x] polygon +- [x] multiPolygon +- [x] geometryCollection +DATA +- [x] random +- [x] sample +INTERPOLATION +- [ ] isolines +- [ ] planepoint +- [ ] tin +JOINS +- [x] inside +- [x] tag +- [ ] within +GRIDS +- [x] hexGrid +- [x] pointGrid +- [x] squareGrid +- [x] triangleGrid +CLASSIFICATION +- [ ] nearest +META +- [ ] propEach +- [ ] coordEach +- [ ] coordReduce +- [ ] featureEach +- [ ] getCoord +ASSERTIONS +- [ ] featureOf +- [ ] collectionOf +- [x] bbox +- [ ] circle +- [ ] geojsonType +- [ ] propReduce +- [ ] coordAll +- [ ] tesselate + */ + +declare const turf: turf.TurfStatic; +declare const TemplateUnits: 'miles' | 'nauticalmiles' | 'degrees' | 'radians' | 'inches' | 'yards' | 'meters' | 'metres' | 'kilometers' | 'kilometres' +declare const TemplateType: 'point'| 'points' | 'polygon' | 'polygons' declare module turf { + interface TurfStatic { ////////////////////////////////////////////////////// // Aggregation ////////////////////////////////////////////////////// /** - * Calculates a series of aggregations for a set of points within a set of polygons. - * Sum, average, count, min, max, and deviation are supported. - * @param polygons Polygons with values on which to aggregate - * @param points Points to be aggregated - * @param aggregations An array of aggregation objects - * @returns Polygons with properties listed based on outField values in aggregations - */ - function aggregate(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, aggregations: Array<{aggregation: string, inField: string, outField: string}>): GeoJSON.FeatureCollection; - - /** - * Calculates the average value of a field for a set of points within a set of polygons. - * @param polygons Polygons with values on which to average - * @param points Points from which to calculate the average - * @param field The field in the points features from which to pull values to average - * @param outField The field in polygons to put results of the averages - * @returns Polygons with the value of outField set to the calculated averages - */ - function average(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, field: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Takes a set of points and a set of polygons and calculates the number of points that fall within the set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param countField A field to append to the attributes of the Polygon features representing Point counts - * @returns Polygons with countField appended - */ - function count(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, countField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the standard deviation value of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in points from which to aggregate - * @param outField The field to append to polygons representing deviation - * @returns Polygons with appended field representing deviation - */ - function deviation(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the maximum value of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in input data to analyze - * @param outField The field in which to store results - * @returns Polygons with properties listed as outField values - */ - function max(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the median value of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in input data to analyze - * @param outField The field in which to store results - * @returns Polygons with properties listed as outField values - */ - function median(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the minimum value of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in input data to analyze - * @param outField The field in which to store results - * @returns Polygons with properties listed as outField values - */ - function min(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the sum of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in input data to analyze - * @param outField The field in which to store results - * @returns Polygons with properties listed as outField - */ - function sum(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the variance value of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in input data to analyze - * @param outField The field in which to store results - * @returns Polygons with properties listed as outField - */ - function variance(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + * Merges a specified property from a FeatureCollection of points into a FeatureCollection of polygons. Given an `inProperty` on points and an `outProperty` for polygons, this finds every point that lies within each polygon, collects the `inProperty` values from those points, and adds them as an array to `outProperty` on the polygon. + * + * @name [collect](http://turfjs.org/docs/#collect) + * @param {FeatureCollection} polygons polygons with values on which to aggregate + * @param {FeatureCollection} points points to be aggregated + * @param {string} inProperty property to be nested from + * @param {string} outProperty property to be nested into + * @return {FeatureCollection} polygons with properties listed based on `outField` + * @example + * var poly1 = polygon([[[0,0],[10,0],[10,10],[0,10],[0,0]]]) + * var poly2 = polygon([[[10,0],[20,10],[20,20],[20,0],[10,0]]]) + * var polyFC = featurecollection([poly1, poly2]) + * var pt1 = point([5,5], {population: 200}) + * var pt2 = point([1,3], {population: 600}) + * var pt3 = point([14,2], {population: 100}) + * var pt4 = point([13,1], {population: 200}) + * var pt5 = point([19,7], {population: 300}) + * var ptFC = featurecollection([pt1, pt2, pt3, pt4, pt5]) + * var aggregated = aggregate(polyFC, ptFC, 'population', 'values') + * + * aggregated.features[0].properties.values // => [200, 600]) + */ + collect( + polygons: GeoJSON.FeatureCollection, + points: GeoJSON.FeatureCollection, + inProperty: string, + outProperty: string + ): GeoJSON.FeatureCollection; ////////////////////////////////////////////////////// // Measurement @@ -110,21 +137,49 @@ declare module turf { * @param [units=miles] 'miles', 'kilometers', 'radians' or 'degrees' * @returns Point along the line */ - function along(line: GeoJSON.Feature, distance: number, units?: string): GeoJSON.Feature; + along( + line: GeoJSON.Feature, + distance: number, + units?: typeof TemplateUnits + ): GeoJSON.Feature; /** * Takes one or more features and returns their area in square meters. * @param input Input features * @returns Area in square meters */ - function area(input: GeoJSON.Feature | GeoJSON.FeatureCollection): number; + area(input: GeoJSON.Feature | GeoJSON.FeatureCollection): number; + + /** + * Takes a set of features, calculates the bbox of all input features, and returns a bounding box. + * + * @name bbox + * @param {(Feature|FeatureCollection)} geojson input features + * @return {Array} bbox extent in [minX, minY, maxX, maxY] order + * @example + * var pt1 = point([114.175329, 22.2524]) + * var pt2 = point([114.170007, 22.267969]) + * var pt3 = point([114.200649, 22.274641]) + * var pt4 = point([114.200649, 22.274641]) + * var pt5 = point([114.186744, 22.265745]) + * var features = featureCollection([pt1, pt2, pt3, pt4, pt5]) + * + * var bbox = turf.bbox(features); + * + * var bboxPolygon = turf.bboxPolygon(bbox); + * + * //=bbox + * + * //=bboxPolygon + */ + bbox(bbox: GeoJSON.Feature | GeoJSON.FeatureCollection): Array; /** * Takes a bbox and returns an equivalent polygon. * @param bbox An Array of bounding box coordinates in the form: [xLow, yLow, xHigh, yHigh] * @returns A Polygon representation of the bounding box */ - function bboxPolygon(bbox: Array): GeoJSON.Feature; + bboxPolygon(bbox: Array): GeoJSON.Feature; /** * Takes two points and finds the geographic bearing between them. @@ -132,14 +187,14 @@ declare module turf { * @param end Ending point * @returns Bearing in decimal degrees */ - function bearing(start: GeoJSON.Feature, end: GeoJSON.Feature): number; + bearing(start: GeoJSON.Feature, end: GeoJSON.Feature): number; /** * Takes a FeatureCollection and returns the absolute center point of all features. * @param features Input features * @returns A Point feature at the absolute center point of all input features */ - function center(features: GeoJSON.FeatureCollection): GeoJSON.Feature; + center(features: GeoJSON.FeatureCollection): GeoJSON.Feature; /** * Takes one or more features and calculates the centroid using the arithmetic mean of all vertices. @@ -147,10 +202,10 @@ declare module turf { * @param features Input features * @returns The centroid of the input features */ - function centroid(features: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; + centroid(features: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; /** - * Takes a Point and calculates the location of a destination point given a distance in degrees, radians, miles, or kilometers; and bearing in degrees. + * Takes a Point and calculates the location of a destination point given a distance in degrees, radians, miles, or kilometers and bearing in degrees. * This uses the Haversine formula to account for global curvature. * @param start Starting point * @param distance Distance from the starting point @@ -158,7 +213,12 @@ declare module turf { * @param units 'miles', 'kilometers', 'radians', or 'degrees' * @returns Destination point */ - function destination(start: GeoJSON.Feature, distance: number, bearing: number, units: string): GeoJSON.Feature; + destination( + start: GeoJSON.Feature, + distance: number, + bearing: number, + units?: typeof TemplateUnits + ): GeoJSON.Feature; /** * Calculates the distance between two points in degress, radians, miles, or kilometers. @@ -168,21 +228,18 @@ declare module turf { * @param [units=kilometers] 'miles', 'kilometers', 'radians', or 'degrees' * @returns Distance between the two points */ - function distance(from: GeoJSON.Feature, to: GeoJSON.Feature, units?: string): number; + distance( + from: GeoJSON.Feature, + to: GeoJSON.Feature, + units?: typeof TemplateUnits + ): number; /** * Takes any number of features and returns a rectangular Polygon that encompasses all vertices. * @param fc Input features * @returns A rectangular Polygon feature that encompasses all vertices */ - function envelope(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; - - /** - * Takes a set of features, calculates the extent of all input features, and returns a bounding box. - * @param input Input features - * @returns The bounding box of input given as an array in WSEN order (west, south, east, north) - */ - function extent(input: GeoJSON.Feature | GeoJSON.FeatureCollection): Array; + envelope(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; /** * Takes a line and measures its length in the specified units. @@ -190,7 +247,10 @@ declare module turf { * @param units 'miles', 'kilometers', 'radians', or 'degrees' * @returns Length of the input line */ - function lineDistance(line: GeoJSON.Feature, units: string): number; + lineDistance( + line: GeoJSON.Feature, + units?: typeof TemplateUnits + ): number; /** * Takes two points and returns a point midway between them. @@ -198,7 +258,7 @@ declare module turf { * @param pt2 Second point * @returns A point midway between pt1 and pt2 */ - function midpoint(pt1: GeoJSON.Feature, pt2: GeoJSON.Feature): GeoJSON.Feature; + midpoint(pt1: GeoJSON.Feature, pt2: GeoJSON.Feature): GeoJSON.Feature; /** * Takes a feature and returns a Point guaranteed to be on the surface of the feature. Given a Polygon, the point will be in the area of the polygon. @@ -206,22 +266,14 @@ declare module turf { * @param input Any feature or set of features * @returns A point on the surface of input */ - function pointOnSurface(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; - - /** - * Takes a bounding box and returns a new bounding box with a size expanded or contracted by a factor of X. - * @param bbox A bounding box - * @param factor The ratio of the new bbox to the input bbox - * @returns The resized bbox - */ - function size(bbox: Array, factor: number): Array; + pointOnSurface(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; /** * Takes a bounding box and calculates the minimum square bounding box that would contain the input. * @param bbox A bounding box * @returns A square surrounding bbox */ - function square(bbox: Array): Array; + square(bbox: Array): Array; ////////////////////////////////////////////////////// // Transformation @@ -235,7 +287,7 @@ declare module turf { * @param [sharpness=0.85] A measure of how curvy the path should be between splines * @returns Curved line */ - function bezier(line: GeoJSON.Feature, resolution?: number, sharpness?: number): GeoJSON.Feature; + bezier(line: GeoJSON.Feature, resolution?: number, sharpness?: number): GeoJSON.Feature; /** * Calculates a buffer for input features for a given radius. Units supported are miles, kilometers, and degrees. @@ -244,7 +296,14 @@ declare module turf { * @param units 'miles', 'kilometers', 'radians', or 'degrees' * @returns Buffered features */ - function buffer(feature: GeoJSON.Feature | GeoJSON.FeatureCollection, distance: number, units: string): GeoJSON.FeatureCollection | GeoJSON.FeatureCollection | GeoJSON.Polygon | GeoJSON.MultiPolygon; + buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; + buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; + buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; + buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; + buffer(feature: GeoJSON.FeatureCollection, distance: number, units?: typeof TemplateUnits): GeoJSON.FeatureCollection; + buffer(feature: GeoJSON.FeatureCollection, distance: number, units?: typeof TemplateUnits): GeoJSON.FeatureCollection; + buffer(feature: GeoJSON.FeatureCollection, distance: number, units?: typeof TemplateUnits): GeoJSON.FeatureCollection; + buffer(feature: GeoJSON.FeatureCollection, distance: number, units?: typeof TemplateUnits): GeoJSON.FeatureCollection; /** * Takes a set of points and returns a concave hull polygon. Internally, this implements a Monotone chain algorithm. @@ -253,14 +312,20 @@ declare module turf { * @param units Used for maxEdge distance (miles or kilometers) * @returns A concave hull */ - function concave(points: GeoJSON.FeatureCollection, maxEdge: number, units: string): GeoJSON.Feature; + concave( + points: GeoJSON.FeatureCollection, + maxEdge: number, + units?: typeof TemplateUnits + ): GeoJSON.Feature; /** * Takes a set of points and returns a convex hull polygon. Internally this uses the convex-hull module that implements a monotone chain hull. * @param input Input points * @returns A convex hull */ - function convex(input: GeoJSON.FeatureCollection): GeoJSON.Feature; + convex( + input: GeoJSON.FeatureCollection + ): GeoJSON.Feature; /** * Finds the difference between two polygons by clipping the second polygon from the first. @@ -268,26 +333,54 @@ declare module turf { * @param poly2 Polygon feature to difference from poly1 * @returns A Polygon feature showing the area of poly1 excluding the area of poly2 */ - function difference(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; + difference( + poly1: GeoJSON.Feature, + poly2: GeoJSON.Feature + ): GeoJSON.Feature; /** - * Takes two polygons and finds their intersection. - * If they share a border, returns the border; if they don't intersect, returns undefined. - * @param poly1 The first polygon - * @param poly2 The second polygon - * @returns If poly1 and poly2 overlap, returns a Polygon feature representing the area they overlap; - * if poly1 and poly2 do not overlap, returns undefined; - * if poly1 and poly2 share a border, a MultiLineString of the locations where their borders are shared - */ - function intersect(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature | typeof undefined; - - /** - * Takes a set of polygons and returns a single merged polygon feature. - * If the input polygon features are not contiguous, this function returns a MultiPolygon feature. - * @param fc Input polygons - * @returns Merged polygon or multipolygon - */ - function merge(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; + * Takes two Features and finds their intersection. + * If they share a border, returns the border if they don't intersect, returns undefined. + * + * @name [intersect](http://turfjs.org/docs/#intersect) + * @param {Feature} poly1 + * @param {Feature} poly2 + * @returns {Feature|undefined} A feature representing the point(s) they share (in case of a {Point} or {MultiPoint}), the borders they share (in case of a {LineString} or a {MultiLineString}), the area they share (in case of {Polygon} or {MultiPolygon}). If they do not share any point, returns `undefined`. + * @example + * var poly1 = polygon([[ + * [-122.801742, 45.48565], + * [-122.801742, 45.60491], + * [-122.584762, 45.60491], + * [-122.584762, 45.48565], + * [-122.801742, 45.48565] + * ]]); + * + * var poly2 = polygon([[ + * [-122.520217, 45.535693], + * [-122.64038, 45.553967], + * [-122.720031, 45.526554], + * [-122.669906, 45.507309], + * [-122.723464, 45.446643], + * [-122.532577, 45.408574], + * [-122.487258, 45.477466], + * [-122.520217, 45.535693] + * ]]); + * var polygons = featureCollection([poly1, poly2]); + * + * var intersection = turf.intersect(poly1, poly2); + * + * //=polygons + * + * //=intersection + */ + intersect( + feature1: GeoJSON.Feature, + feature2: GeoJSON.Feature + ): GeoJSON.Feature; + intersect( + feature1: GeoJSON.Feature, + feature2: GeoJSON.Feature + ): GeoJSON.Feature; /** * Takes a LineString or Polygon and returns a simplified version. @@ -297,16 +390,16 @@ declare module turf { * @param highQuality Whether or not to spend more time to create a higher-quality simplification with a different algorithm * @returns A simplified feature */ - function simplify(feature: GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection, tolerance: number, highQuality: boolean): GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection; + simplify(feature: GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection, tolerance: number, highQuality: boolean): GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection; /** * Takes two polygons and returns a combined polygon. - * If the input polygons are not contiguous, this function returns a MultiPolygon feature. + * If the input polygons are not contiguous, this function returns a MultiPolygon feature.; * @param poly1 Input polygon * @param poly2 Another input polygon * @returns A combined Polygon or MultiPolygon feature */ - function union(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; + union(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; ////////////////////////////////////////////////////// // Misc @@ -317,28 +410,28 @@ declare module turf { * @param fc A FeatureCollection of any type * @returns A FeatureCollection of corresponding type to input */ - function combine(fc: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + combine(fc: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; /** * Takes a feature or set of features and returns all positions as points. * @param input Input features * @returns Points representing the exploded input features */ - function explode(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + explode(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; /** * Takes input features and flips all of their coordinates from [x, y] to [y, x]. * @param input Input features * @returns A feature or set of features of the same type as input with flipped coordinates */ - function flip(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature | GeoJSON.FeatureCollection; + flip(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature | GeoJSON.FeatureCollection; /** * Takes a polygon and returns points at all self-intersections. * @param polygon Input polygon * @returns Self-intersections */ - function kinks(polygon: GeoJSON.Feature): GeoJSON.FeatureCollection; + kinks(polygon: GeoJSON.Feature): GeoJSON.FeatureCollection; /** * Takes a line, a start Point, and a stop point and returns the line in between those points. @@ -347,7 +440,7 @@ declare module turf { * @param line Line to slice * @returns Sliced line */ - function lineSlice(point1: GeoJSON.Feature, point2: GeoJSON.Feature, line: GeoJSON.Feature): GeoJSON.Feature; + lineSlice(point1: GeoJSON.Feature, point2: GeoJSON.Feature, line: GeoJSON.Feature): GeoJSON.Feature; /** * Takes a Point and a LineString and calculates the closest Point on the LineString. @@ -355,98 +448,348 @@ declare module turf { * @param point Point to snap from * @returns Closest point on the line to point */ - function pointOnLine(line: GeoJSON.Feature, point: GeoJSON.Feature): GeoJSON.Feature; + pointOnLine(line: GeoJSON.Feature, point: GeoJSON.Feature): GeoJSON.Feature; ////////////////////////////////////////////////////// // Helper ////////////////////////////////////////////////////// /** - * Takes one or more Features and creates a FeatureCollection. - * @param features Input features - * @returns A FeatureCollection of input features - */ - function featurecollection(features: Array>): GeoJSON.FeatureCollection; + * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}. + * + * @name [featureCollection](http://turfjs.org/docs/#featurecollection) + * @param {Feature[]} features input features + * @returns {FeatureCollection} a FeatureCollection of input features + * @example + * var features = [ + * turf.point([-75.343, 39.984], {name: 'Location A'}), + * turf.point([-75.833, 39.284], {name: 'Location B'}), + * turf.point([-75.534, 39.123], {name: 'Location C'}) + * ] + * + * var fc = turf.featureCollection(features) + * + * //=fc + */ + featureCollection(features: Array>): GeoJSON.FeatureCollection; /** - * Creates a LineString based on a coordinate array. Properties can be added optionally. - * @param coordinates An array of Positions - * @param [properties] An Object of key-value pairs to add as properties - * @returns A LineString feature - */ - function linestring(coordinates: Array>, properties?: any): GeoJSON.Feature; + * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}. + * + * @name [feature](http://turfjs.org/docs/#feature) + * @param {Geometry} geometry input geometry + * @param {Object} properties properties + * @returns {FeatureCollection} a FeatureCollection of input features + * @example + * var geometry = { + * "type": "Point", + * "coordinates": [ + * 67.5, + * 32.84267363195431 + * ] + * } + * + * var feature = turf.feature(geometry) + * + * //=feature + */ + feature(geometry:GeoJSON.Feature, properties?: any): GeoJSON.Feature; /** - * Takes coordinates and properties (optional) and returns a new Point feature. - * @param coordinates Longitude, latitude position (each in decimal degrees) - * @param [properties] An Object of key-value pairs to add as properties - * @returns A Point feature - */ - function point(coordinates: Array, properties?: any): GeoJSON.Feature; + * Creates a {@link LineString} based on a coordinate array. Properties can be added optionally. + * + * @name [lineString](http://turfjs.org/docs/#linestring) + * @param {Array>} coordinates an array of Positions + * @param {Object=} properties an Object of key-value pairs to add as properties + * @returns {Feature} a LineString feature + * @throws {Error} if no coordinates are passed + * @example + * var linestring1 = turf.lineString([ + * [-21.964416, 64.148203], + * [-21.956176, 64.141316], + * [-21.93901, 64.135924], + * [-21.927337, 64.136673] + * ]) + * var linestring2 = turf.lineString([ + * [-21.929054, 64.127985], + * [-21.912918, 64.134726], + * [-21.916007, 64.141016], + * [-21.930084, 64.14446] + * ], {name: 'line 1', distance: 145}) + * + * //=linestring1 + * + * //=linestring2 + */ + lineString(coordinates: Array>, properties?: any): GeoJSON.Feature; /** - * Takes an array of LinearRings and optionally an Object with properties and returns a Polygon feature. - * @param rings An array of LinearRings - * @param [properties] An Object of key-value pairs to add as properties - * @returns A Polygon feature - */ - function polygon(rings: Array>>, properties?: any): GeoJSON.Feature; + * Creates a {@link Feature} based on a coordinate array. Properties can be added optionally. + * + * @name [multiLineString](http://turfjs.org/docs/#multilinestring) + * @param {Array>>} coordinates an array of LineStrings + * @param {Object=} properties an Object of key-value pairs to add as properties + * @returns {Feature} a MultiLineString feature + * @throws {Error} if no coordinates are passed + * @example + * var multiLine = turf.multiLineString([[[0,0],[10,10]]]) + * + * //=multiLine + * + */ + multiLineString(coordinates: Array>>, properties?: any): GeoJSON.Feature; + + /** + * Takes coordinates and properties (optional) and returns a new {@link Point} feature. + * + * @name [point](http://turfjs.org/docs/#point) + * @param {Array} coordinates longitude, latitude position (each in decimal degrees) + * @param {Object=} properties an Object that is used as the {@link Feature}'s + * properties + * @returns {Feature} a Point feature + * @example + * var pt1 = turf.point([-75.343, 39.984]); + * + * //=pt1 + */ + point(coordinates: Array, properties?: any): GeoJSON.Feature; + + /** + * Creates a {@link Feature} based on a coordinate array. Properties can be added optionally. + * + * @name [multiPoint](http://turfjs.org/docs/#multipoint) + * @param {Array>} coordinates an array of Positions + * @param {Object=} properties an Object of key-value pairs to add as properties + * @returns {Feature} a MultiPoint feature + * @throws {Error} if no coordinates are passed + * @example + * var multiPt = turf.multiPoint([[0,0],[10,10]]) + * + * //=multiPt + * + */ + multiPoint(coordinates: Array>, properties?: any): GeoJSON.Feature; + + /** + * Takes an array of LinearRings and optionally an {@link Object} with properties and returns a {@link Polygon} feature. + * + * @name [polygon](http://turfjs.org/docs/#polygon) + * @param {Array>>} coordinates an array of LinearRings + * @param {Object=} properties a properties object + * @returns {Feature} a Polygon feature + * @throws {Error} throw an error if a LinearRing of the polygon has too few positions + * or if a LinearRing of the Polygon does not have matching Positions at the + * beginning & end. + * @example + * var polygon = turf.polygon([[ + * [-2.275543, 53.464547], + * [-2.275543, 53.489271], + * [-2.215118, 53.489271], + * [-2.215118, 53.464547], + * [-2.275543, 53.464547] + * ]], { name: 'poly1', population: 400}); + * + * //=polygon + */ + polygon(coordinates: Array>>, properties?: any): GeoJSON.Feature; + + /** + * Creates a {@link Feature} based on a coordinate array. Properties can be added optionally. + * + * @name [multiPolygon](http://turfjs.org/docs/#multipolygon) + * @param {Array>>>} coordinates an array of Polygons + * @param {Object=} properties an Object of key-value pairs to add as properties + * @returns {Feature} a multipolygon feature + * @throws {Error} if no coordinates are passed + * @example + * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]); + * + * //=multiPoly + * + */ + multiPolygon(coordinates: Array>>>, properties?: any): GeoJSON.Feature; + + /** + * Creates a {@link Feature} based on acoordinate array. Properties can be added optionally. + * + * @name [geometryCollection](http://turfjs.org/docs/#geometrycollection) + * @param {Array<{Geometry}>} geometries an array of GeoJSON Geometries + * @param {Object=} properties an Object of key-value pairs to add as properties + * @returns {Feature} a GeoJSON GeometryCollection Feature + * @example + * var point = { + * "type": "Point", + * "coordinates": [100, 0] + * }; + * var line = { + * "type": "LineString", + * "coordinates": [ [101, 0], [102, 1] ] + * }; + * var collection = turf.geometryCollection([point, line]); + * + * //=collection + */ + geometryCollection(geometries: Array, properties?: any): GeoJSON.GeometryCollection; ////////////////////////////////////////////////////// // Data ////////////////////////////////////////////////////// /** - * Takes a FeatureCollection and filters it by a given property and value. - * @param features Input features - * @param key The property on which to filter - * @param value The value of that property on which to filter - * @returns A filtered collection with only features that match input key and value - */ - function filter(features: GeoJSON.FeatureCollection, key: string, value: string): GeoJSON.FeatureCollection; + * Generates random {@link GeoJSON} data, including {@link Point|Points} and {@link Polygon|Polygons}, for testing and experimentation. + * + * @name [random](http://turfjs.org/docs/#random) + * @param {String} [type='point'] type of features desired: 'points' or 'polygons' + * @param {Number} [count=1] how many geometries should be generated. + * @param {Object} options options relevant to the feature desired. Can include: + * @param {Array} options.bbox a bounding box inside of which geometries + * are placed. In the case of {@link Point} features, they are guaranteed to be within this bounds, + * while {@link Polygon} features have their centroid within the bounds. + * @param {Number} [options.num_vertices=10] options.vertices the number of vertices added + * to polygon features. + * @param {Number} [options.max_radial_length=10] the total number of decimal + * degrees longitude or latitude that a polygon can extent outwards to + * from its center. + * @return {FeatureCollection} generated random features + * @example + * var points = turf.random('points', 100, { + * bbox: [-70, 40, -60, 60] + * }) + * + * //=points + * + * var polygons = turf.random('polygons', 4, { + * bbox: [-70, 40, -60, 60] + * }) + * + * //=polygons + */ + random(type?: typeof TemplateType, count?: number, options?: { + bbox?: Array + num_vertices?: number + max_radial_length?: number + }): GeoJSON.FeatureCollection; /** - * Generates random GeoJSON data, including Points and Polygons, for testing and experimentation. - * @param [type='point'] Type of features desired: 'points' or 'polygons' - * @param [count=1] How many geometries should be generated. - * @param [options] Options relevant to the feature desired. Can include: - * - A bounding box inside of which geometries are placed. In the case of Point features, they are guaranteed to be within this bounds, while Polygon features have their centroid within the bounds. - * - The number of vertices added to polygon features. Default is 10; - * - The total number of decimal degrees longitude or latitude that a polygon can extent outwards to from its center. Default is 10. - * @returns Generated random features - */ - function random(type?: string, count?: number, options?: {bbox?: Array; num_vertices?: number; max_radial_length?: number;}): GeoJSON.FeatureCollection; + * Takes a {@link FeatureCollection} and returns a FeatureCollection with given number of {@link Feature|features} at random. + * + * @name [sample](http://turfjs.org/docs/#sample) + * @param {FeatureCollection} featurecollection set of input features + * @param {number} num number of features to select + * @return {FeatureCollection} a FeatureCollection with `n` features + * @example + * var points = turf.random('points', 1000); + * + * //=points + * + * var sample = turf.sample(points, 10); + * + * //=sample + */ + sample(featurecollection: GeoJSON.FeatureCollection, num: number): GeoJSON.FeatureCollection; + + ////////////////////////////////////////////////////// + // GRIDS + ////////////////////////////////////////////////////// /** - * Takes a FeatureCollection of any type, a property, and a value and returns a FeatureCollection with features matching that property-value pair removed. - * @param features Set of input features - * @param property The property to remove - * @param value The value to remove - * @returns The resulting FeatureCollection without features that match the property-value pair - */ - function remove(features: GeoJSON.FeatureCollection, property: string, value: string): GeoJSON.FeatureCollection; + * Takes a bounding box and a cell size in degrees and returns a {@link FeatureCollection} of flat-topped hexagons ({@link Polygon} features) aligned in an "odd-q" vertical grid as described in [Hexagonal Grids](http://www.redblobgames.com/grids/hexagons/). + * + * @name [hexGrid](http://turfjs.org/docs/#hexgrid) + * @param {Array} bbox bounding box in [minX, minY, maxX, maxY] order + * @param {number} cellSize dimension of cell in specified units + * @param {string} units used in calculating cellSize ('miles' or 'kilometers') + * @param {boolean} triangles whether to return as triangles instead of hexagons + * @return {FeatureCollection} a hexagonal grid + * @example + * var bbox = [-96,31,-84,40]; + * var cellSize = 50; + * var units = 'miles'; + * + * var hexgrid = turf.hexGrid(bbox, cellSize, units); + * + * //=hexgrid + */ + hexGrid( + bbox: Array, + cellSize: number, + units?: typeof TemplateUnits, + triangles?: boolean + ): GeoJSON.FeatureCollection; /** - * Takes a FeatureCollection and returns a FeatureCollection with given number of features at random. - * @param features Set of input features - * @param n Number of features to select - * @returns A FeatureCollection with n features - */ - function sample(features: GeoJSON.FeatureCollection, n: number): GeoJSON.FeatureCollection; + * Takes a bounding box and a cell depth and returns a set of {@link Point|points} in a grid. + * + * @name [pointGrid](http://turfjs.org/docs/#pointgrid) + * @param {Array} bbox extent in [minX, minY, maxX, maxY] order + * @param {number} cellSize the distance across each cell + * @param {string} [units=kilometers] used in calculating cellSize, can be degrees, radians, miles, or kilometers + * @return {FeatureCollection} grid of points + * @example + * var extent = [-70.823364, -33.553984, -70.473175, -33.302986]; + * var cellSize = 3; + * var units = 'miles'; + * + * var grid = turf.pointGrid(extent, cellSize, units); + * + * //=grid + */ + pointGrid( + bbox: Array, + cellSize: number, + units?: typeof TemplateUnits + ): GeoJSON.FeatureCollection; + + /** + * Takes a bounding box and a cell depth and returns a set of square {@link Polygon|polygons} in a grid. + * + * @name [squareGrid](http://turfjs.org/docs/#squaregrid) + * @param {Array} bbox extent in [minX, minY, maxX, maxY] order + * @param {number} cellSize width of each cell + * @param {string} [units=kilometers] used in calculating cellSize, can be degrees, radians, miles, or kilometers + * @return {FeatureCollection} grid a grid of polygons + * @example + * var bbox = [-96,31,-84,40] + * var cellSize = 10 + * var units = 'miles' + * + * var squareGrid = turf.squareGrid(bbox, cellSize, units) + * + * //=squareGrid + */ + squareGrid( + bbox: Array, + cellSize: number, + units?: typeof TemplateUnits + ): GeoJSON.FeatureCollection; + + /** + * Takes a bounding box and a cell depth and returns a set of triangular {@link Polygon|polygons} in a grid. + * + * @name [triangleGrid](http://turfjs.org/docs/#trianglegrid)) + * @param {Array} bbox extent in [minX, minY, maxX, maxY] order + * @param {number} cellSize dimension of each cell + * @param {string} [units=kilometers] used in calculating cellSize, can be degrees, radians, miles, or kilometers + * @return {FeatureCollection} grid of polygons + * @example + * var bbox = [-96,31,-84,40] + * var cellSize = 10; + * var units = 'miles'; + * + * var triangleGrid = turf.triangleGrid(extent, cellSize, units); + * + * //=triangleGrid + */ + triangleGrid( + bbox: Array, + cellSize: number, + units?: typeof TemplateUnits + ): GeoJSON.FeatureCollection; ////////////////////////////////////////////////////// // Interpolation ////////////////////////////////////////////////////// - /** - * Takes a bounding box and a cell size in degrees and returns a FeatureCollection of flat-topped hexagons (Polygon features) aligned in an "odd-q" vertical grid as described in Hexagonal Grids. - * @param bbox Bounding box in [minX, minY, maxX, maxY] order - * @param cellWidth Width of cell in specified units - * @param units Used in calculating cellWidth ('miles' or 'kilometers') - * @returns A hexagonal grid - */ - function hexGrid(bbox: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; - /** * Takes points with z-values and an array of value breaks and generates isolines. * @param points Input points @@ -455,7 +798,7 @@ declare module turf { * @param breaks Where to draw contours * @returns Isolines */ - function isolines(points: GeoJSON.FeatureCollection, z: string, resolution: number, breaks: Array): GeoJSON.FeatureCollection; + isolines(points: GeoJSON.FeatureCollection, z: string, resolution: number, breaks: Array): GeoJSON.FeatureCollection; /** * Takes a triangular plane as a Polygon and a Point within that triangle and returns the z-value at that point. @@ -464,25 +807,7 @@ declare module turf { * @param triangle A Polygon feature with three vertices * @returns The z-value for interpolatedPoint */ - function planepoint(interpolatedpoint: GeoJSON.Feature, triangle: GeoJSON.Feature): number; - - /** - * Takes a bounding box and a cell depth and returns a set of points in a grid. - * @param extent Extent in [minX, minY, maxX, maxY] order - * @param cellWidth The distance across each cell - * @param units Used in calculating cellWidth ('miles' or 'kilometers') - * @returns Grid of points - */ - function pointGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; - - /** - * Takes a bounding box and a cell depth and returns a set of square polygons in a grid. - * @param extent Extent in [minX, minY, maxX, maxY] order - * @param cellWidth Width of each cell - * @param units Used in calculating cellWidth ('miles' or 'kilometers') - * @returns Grid of polygons - */ - function squareGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + planepoint(interpolatedpoint: GeoJSON.Feature, triangle: GeoJSON.Feature): number; /** * Takes a set of points and the name of a z-value property and creates a Triangulated Irregular Network, or a TIN for short, returned as a collection of Polygons. @@ -492,39 +817,59 @@ declare module turf { * @param [propertyName] Name of the property from which to pull z values This is optional: if not given, then there will be no extra data added to the derived triangles. * @returns TIN output */ - function tin(points: GeoJSON.FeatureCollection, propertyName?: string): GeoJSON.FeatureCollection; - - /** - * Takes a bounding box and a cell depth and returns a set of triangular polygons in a grid. - * @param extent Extent in [minX, minY, maxX, maxY] order - * @param cellWidth Width of each cell - * @param units Used in calculating cellWidth ('miles' or 'kilometers') - * @returns Grid of triangles - */ - function triangleGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + tin(points: GeoJSON.FeatureCollection, propertyName?: string): GeoJSON.FeatureCollection; ////////////////////////////////////////////////////// // Joins ////////////////////////////////////////////////////// /** - * Takes a Point and a Polygon or MultiPolygon and determines if the point resides inside the polygon. - * The polygon can be convex or concave. The function accounts for holes. - * @param point Input point - * @param polygon Input polygon or multipolygon - * @returns true if the Point is inside the Polygon; false if the Point is not inside the Polygon - */ - function inside(point: GeoJSON.Feature, polygon: GeoJSON.Feature): boolean; + * Takes a {} and a {} or {} and determines if the point resides inside the polygon. The polygon can be convex or concave. The function accounts for holes. + * + * @name [inside](http://turfjs.org/docs/#inside) + * @param {Feature} point input point + * @param {Feature<(Polygon|MultiPolygon)>} polygon input polygon or multipolygon + * @return {Boolean} `true` if the Point is inside the Polygon; `false` if the Point is not inside the Polygon + * @example + * var pt = point([-77, 44]) + * var poly = polygon([[[-81, 41], [-81, 47], [-72, 47], [-72, 41], [-81, 41]]]) + * + * var isInside = turf.inside(pt, poly) + * + * //=isInside + */ + inside( + point: GeoJSON.Feature, + polygon: GeoJSON.Feature + ): boolean; /** - * Takes a set of points and a set of polygons and performs a spatial join. - * @param points Input points - * @param polygons Input polygons - * @param polyId Property in polygons to add to joined Point features - * @param containingPolyId Property in points in which to store joined property from polygons - * @returns Points with containingPolyId property containing values from polyId - */ - function tag(points: GeoJSON.FeatureCollection, polygons: GeoJSON.FeatureCollection, polyId: string, containingPolyId: string): GeoJSON.FeatureCollection; + * Takes a {FeatureCollection} and a {FeatureCollection} and performs a spatial join. + * + * @name [tag](http://turfjs.org/docs/#inside) + * @param {FeatureCollection} points input points + * @param {FeatureCollection} polygons input polygons + * @param {string} field property in `polygons` to add to joined {} features + * @param {string} outField property in `points` in which to store joined property from `polygons` + * @return {FeatureCollection} points with `containingPolyId` property containing values from `polyId` + * @example + * var pt1 = point([-77, 44]) + * var pt2 = point([-77, 38]) + * var poly1 = polygon([[[-81, 41], [-81, 47], [-72, 47], [-72, 41], [-81, 41]]], {pop: 1000}) + * var poly2 = polygon([[[-81, 35], [-81, 41], [-72, 41], [-72, 35], [-81, 35]]], {pop: 3000}) + * + * var points = featureCollection([pt1, pt2]) + * var polygons = featureCollection([poly1, poly2]) + * + * var tagged = turf.tag(points, polygons, 'pop', 'population') + * //=tagged + */ + tag( + points: GeoJSON.FeatureCollection, + polygons: GeoJSON.FeatureCollection, + field: string, + outField: string + ): GeoJSON.FeatureCollection; /** * Takes a set of points and a set of polygons and returns the points that fall within the polygons. @@ -532,49 +877,331 @@ declare module turf { * @param polygons Input polygons * @returns Points that land within at least one polygon */ - function within(points: GeoJSON.FeatureCollection, polygons: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + within( + points: GeoJSON.FeatureCollection, + polygons: GeoJSON.FeatureCollection + ): GeoJSON.FeatureCollection; ////////////////////////////////////////////////////// // Classification ////////////////////////////////////////////////////// - /** - * Takes a set of features and returns an array of the Jenks Natural breaks for a given property. - * @param input Input features - * @param field The property in input on which to calculate Jenks natural breaks - * @param numberOfBreaks Number of classes in which to group the data - * @returns The break number for each class plus the minimum and maximum values - */ - function jenks(input: GeoJSON.FeatureCollection, field: string, numberOfBreaks: number): Array; - /** * Takes a reference point and a set of points and returns the point from the set closest to the reference. * @param point The reference point * @param against Input point set * @returns The closest point in the set to the reference point */ - function nearest(point: GeoJSON.Feature, against: GeoJSON.FeatureCollection): GeoJSON.Feature; - - /** - * Takes a FeatureCollection, a property name, and a set of percentiles and returns a quantile array. - * @param input Set of features - * @param field The property in input from which to retrieve quantile values - * @param percentiles An Array of percentiles on which to calculate quantile values - * @returns An array of the break values - */ - function quantile(input: GeoJSON.FeatureCollection, field: string, percentiles: Array): Array; - - /** - * Takes a FeatureCollection, an input field, an output field, and an array of translations and outputs an identical FeatureCollection with the output field property populated. - * @param input Set of input features - * @param inField The field to translate - * @param outField The field in which to store translated results - * @param translations An array of translations - * @returns A FeatureCollection with identical geometries to input but with outField populated. - */ - function reclass(input: GeoJSON.FeatureCollection, inField: string, outField: string, translations: Array): GeoJSON.FeatureCollection; + nearest( + point: GeoJSON.Feature, + against: GeoJSON.FeatureCollection + ): GeoJSON.Feature; + } } -declare module 'turf' { - export= turf; +// NPM Stable version of Turf +declare module "turf" { + export = turf } + +// Latest version of Turf +declare module "@turf/turf" { + export = turf +} + +// AGGREGATION +declare module "@turf/collect" { + const collect: typeof turf.collect; + export = collect; +} + +// MEASUREMENT +declare module "@turf/along" { + const along: typeof turf.along; + export = along; +} + +declare module "@turf/area" { + const area: typeof turf.area; + export = area; +} + +declare module "@turf/bbox-polygon" { + const bboxPolygon: typeof turf.bboxPolygon; + export = bboxPolygon; +} + +declare module "@turf/bearing" { + const bearing: typeof turf.bearing; + export = bearing; +} + +declare module "@turf/center" { + const center: typeof turf.center; + export = center; +} + +declare module "@turf/centroid" { + const centroid: typeof turf.centroid; + export = centroid; +} + +declare module "@turf/destination" { + const destination: typeof turf.destination; + export = destination; +} + +declare module "@turf/distance" { + const distance: typeof turf.distance; + export = distance; +} + +declare module "@turf/envelope" { + const envelope: typeof turf.envelope; + export = envelope; +} + +declare module "@turf/line-distance" { + const lineDistance: typeof turf.lineDistance; + export = lineDistance; +} + +declare module "@turf/midpoint" { + const midpoint: typeof turf.midpoint; + export = midpoint; +} + +declare module "@turf/point-on-surface" { + const pointOnSurface: typeof turf.pointOnSurface; + export = pointOnSurface; +} + +declare module "@turf/square" { + const square: typeof turf.square; + export = square; +} + +// TRANSFORMATION +declare module "@turf/bezier" { + const bezier: typeof turf.bezier; + export = bezier; +} + +declare module "@turf/buffer" { + const buffer: typeof turf.buffer; + export = buffer; +} + +declare module "@turf/concave" { + const concave: typeof turf.concave; + export = concave; +} + +declare module "@turf/convex" { + const convex: typeof turf.convex; + export = convex; +} + +declare module "@turf/difference" { + const difference: typeof turf.difference; + export = difference; +} + +declare module "@turf/intersect" { + const intersect: typeof turf.intersect; + export = intersect; +} + +declare module "@turf/simplify" { + const simplify: typeof turf.simplify; + export = simplify; +} + +declare module "@turf/union" { + const union: typeof turf.union; + export = union; +} + +// MISC +declare module "@turf/combine" { + const combine: typeof turf.combine; + export = combine; +} + +declare module "@turf/explode" { + const explode: typeof turf.explode; + export = explode; +} + +declare module "@turf/flip" { + const flip: typeof turf.flip; + export = flip; +} + +declare module "@turf/kinks" { + const kinks: typeof turf.kinks; + export = kinks; +} + +declare module "@turf/line-slice" { + const lineSlice: typeof turf.lineSlice; + export = lineSlice; +} + +declare module "@turf/point-on-line" { + const pointOnLine: typeof turf.pointOnLine; + export = pointOnLine; +} + +// HELPER +declare module "@turf/helpers" { + const helpers: { + featureCollection: typeof turf.featureCollection, + feature: typeof turf.feature, + lineString: typeof turf.lineString, + multiLineString: typeof turf.multiLineString, + point: typeof turf.point, + multiPoint: typeof turf.multiPoint, + polygon: typeof turf.polygon, + multiPolygon: typeof turf.multiPolygon, + geometryCollection: typeof turf.geometryCollection, + }; + export = helpers; +} + +// DATA +declare module "@turf/random" { + const random: typeof turf.random; + export = random; +} + +declare module "@turf/sample" { + const sample: typeof turf.sample; + export = sample; +} + +// INTERPOLATION +declare module "@turf/isolines" { + const isolines: typeof turf.isolines; + export = isolines; +} + +declare module "@turf/planepoint" { + const planepoint: typeof turf.planepoint; + export = planepoint; +} + +declare module "@turf/tin" { + const tin: typeof turf.tin; + export = tin; +} + +// JOINS +declare module "@turf/inside" { + const inside: typeof turf.inside; + export = inside; +} + +declare module "@turf/tag" { + const tag: typeof turf.tag; + export = tag; +} + +declare module "@turf/within" { + const within: typeof turf.within; + export = within; +} + +// GRIDS +declare module "@turf/hex-grid" { + const hexGrid: typeof turf.hexGrid; + export = hexGrid; +} + +declare module "@turf/point-grid" { + const pointGrid: typeof turf.pointGrid; + export = pointGrid; +} + +declare module "@turf/square-grid" { + const squareGrid: typeof turf.squareGrid; + export = squareGrid; +} + +declare module "@turf/triangle-grid" { + const triangleGrid: typeof turf.triangleGrid; + export = triangleGrid; +} + +// CLASSIFICATION +declare module "@turf/nearest" { + const nearest: typeof turf.nearest; + export = nearest; +} + +// // META +// declare module "@turf/propEach" { +// const propEach: typeof turf.propEach; +// export = propEach; +// } + +// declare module "@turf/coordEach" { +// const coordEach: typeof turf.coordEach; +// export = coordEach; +// } + +// declare module "@turf/coordReduce" { +// const coordReduce: typeof turf.coordReduce; +// export = coordReduce; +// } + +// declare module "@turf/featureEach" { +// const featureEach: typeof turf.featureEach; +// export = featureEach; +// } + +// declare module "@turf/getCoord" { +// const getCoord: typeof turf.getCoord; +// export = getCoord; +// } + +// // ASSERTIONS +// declare module "@turf/featureOf" { +// const featureOf: typeof turf.featureOf; +// export = featureOf; +// } + +// declare module "@turf/collectionOf" { +// const collectionOf: typeof turf.collectionOf; +// export = collectionOf; +// } + +declare module "@turf/bbox" { + const bbox: typeof turf.bbox; + export = bbox; +} + +// declare module "@turf/circle" { +// const circle: typeof turf.circle; +// export = circle; +// } + +// declare module "@turf/geojsonType" { +// const geojsonType: typeof turf.geojsonType; +// export = geojsonType; +// } + +// declare module "@turf/propReduce" { +// const propReduce: typeof turf.propReduce; +// export = propReduce; +// } + +// declare module "@turf/coordAll" { +// const coordAll: typeof turf.coordAll; +// export = coordAll; +// } + +// declare module "@turf/tesselate" { +// const tesselate: typeof turf.tesselate; +// export = tesselate; +// } diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index 8ef14760b8..d6c2dfebf7 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -449,7 +449,7 @@ declare module twilio { export function webhook(options?: string | webhookOptions): MiddlewareFunction; export function validateRequest(authToken: string, twilioHeader: string, url: string, params?: any): boolean; - export function validateExpressRequest(request: Express.Request, authToken: string, options?: WebhookExpressOptions): boolean; + export function validateExpressRequest(request: express.Request, authToken: string, options?: WebhookExpressOptions): boolean; /// resources/Accounts.js export interface OutgoingCallerIdInstance extends InstanceResource { diff --git a/typescript-stl/typescript-stl.d.ts b/typescript-stl/typescript-stl.d.ts index 96d22ceb8f..36ad79e4a1 100644 --- a/typescript-stl/typescript-stl.d.ts +++ b/typescript-stl/typescript-stl.d.ts @@ -1,4 +1,4 @@ -// Type definitions for TypeScript-STL v1.0.1 +// Type definitions for TypeScript-STL v1.0.8 // Project: https://github.com/samchon/typescript-stl // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -2984,7 +2984,7 @@ declare namespace std { /** * @hidden */ - protected abstract create_neighbor(): This; + protected abstract create_neighbor(base: Base): This; /** *

    Get value of the iterator is pointing.

    * @@ -3292,7 +3292,7 @@ declare namespace std { * @param container Another container object of the same type (with the same class template * arguments T), whose contents are either copied or acquired. */ - constructor(container: base.IContainer); + constructor(container: Deque); /** *

    Range Constructor.

    * @@ -3339,6 +3339,10 @@ declare namespace std { * @inheritdoc */ size(): number; + /** + * @inheritdoc + */ + empty(): boolean; /** * @inheritdoc */ @@ -3360,11 +3364,9 @@ declare namespace std { */ back(): T; /** - *

    Fetch row and column's index.

    - * - *

    Fetches index of row and column of {@link matrix_} from sequence number.

    - * - * @param index Sequence number + // Fetch row and column's index. + /** + * @hidden */ private fetch_index(index); /** @@ -3418,11 +3420,11 @@ declare namespace std { /** * @hidden */ - protected insert_by_repeating_val(position: DequeIterator, n: number, val: T): DequeIterator; + protected _Insert_by_repeating_val(position: DequeIterator, n: number, val: T): DequeIterator; /** * @hidden */ - protected insert_by_range>(position: DequeIterator, begin: InputIterator, end: InputIterator): DequeIterator; + protected _Insert_by_range>(position: DequeIterator, begin: InputIterator, end: InputIterator): DequeIterator; /** * @hidden */ @@ -3446,15 +3448,29 @@ declare namespace std { /** * @hidden */ - protected erase_by_range(first: DequeIterator, last: DequeIterator): DequeIterator; + protected _Erase_by_range(first: DequeIterator, last: DequeIterator): DequeIterator; + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link Deque container} object with same type of elements. Sizes and container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were in obj + * before the call, and the elements of obj are those which were in this. All iterators, references and + * pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link Deque container} of the same type of elements (i.e., instantiated + * with the same template parameter, T) whose content is swapped with that of this + * {@link container Deque}. + */ + swap(obj: Deque): void; /** * @inheritdoc */ swap(obj: base.IContainer): void; - /** - * @hidden - */ - private swap_deque(obj); } } declare namespace std { @@ -3556,7 +3572,10 @@ declare namespace std { /** * @hidden */ - protected create_neighbor(): DequeReverseIterator; + protected create_neighbor(base: DequeIterator): DequeReverseIterator; + /** + * @inheritdoc + */ /** * Set value of the iterator is pointing to. * @@ -4438,7 +4457,7 @@ declare namespace std.base { * * @author Jeongho Nam */ - abstract class MapContainer extends base.Container> { + abstract class MapContainer extends Container> { /** *

    {@link List} storing elements.

    * @@ -4447,45 +4466,11 @@ declare namespace std.base { * by storing {@link ListIterator iterators} ({@link MapIterator} references {@link ListIterator}) who are * created from {@link data_ here}.

    */ - protected data_: List>; + private data_; /** * Default Constructor. */ constructor(); - /** - * Construct from elements. - */ - constructor(items: Array>); - /** - * Contruct from tuples. - * - * @param array Tuples to be contained. - */ - constructor(array: Array<[Key, T]>); - /** - * Copy Constructor. - */ - constructor(container: IContainer>); - /** - * Construct from range iterators. - */ - constructor(begin: Iterator>, end: Iterator>); - /** - * @hidden - */ - protected init(): void; - /** - * @hidden - */ - protected construct_from_array(items: Array | [Key, T]>): void; - /** - * @hidden - */ - protected construct_from_container(container: IContainer>): void; - /** - * @hidden - */ - protected construct_from_range>>(begin: InputIterator, end: InputIterator): void; /** * @inheritdoc */ @@ -4595,6 +4580,7 @@ declare namespace std.base { * Return the number of elements in the map. */ size(): number; + protected _Get_data(): List>; /** * @inheritdoc */ @@ -4670,7 +4656,7 @@ declare namespace std.base { /** * @hidden */ - protected abstract insert_by_pair(pair: Pair): any; + protected abstract _Insert_by_pair(pair: Pair): any; /** * @hidden */ @@ -4678,7 +4664,7 @@ declare namespace std.base { /** * @hidden */ - protected abstract insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + protected abstract _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; /** * @hidden */ @@ -4686,7 +4672,7 @@ declare namespace std.base { /** * @hidden */ - protected abstract insert_by_range>>(first: InputIterator, last: InputIterator): void; + protected abstract _Insert_by_range>>(first: InputIterator, last: InputIterator): void; /** *

    Erase an elemet by key.

    * @@ -4785,7 +4771,7 @@ declare namespace std.base { * [first, last), which contains all the elements between first and last, * including the element pointed by first but not the element pointed by last. */ - protected abstract handle_insert(first: MapIterator, last: MapIterator): void; + protected abstract _Handle_insert(first: MapIterator, last: MapIterator): void; /** *

    Abstract method handling deletions for indexing.

    * @@ -4806,7 +4792,11 @@ declare namespace std.base { * [first, last), which contains all the elements between first and last, * including the element pointed by first but not the element pointed by last. */ - protected abstract handle_erase(first: MapIterator, last: MapIterator): void; + protected abstract _Handle_erase(first: MapIterator, last: MapIterator): void; + /** + * @hidden + */ + protected _Swap(obj: MapContainer): void; } } declare namespace std { @@ -4899,7 +4889,7 @@ declare namespace std { /** * @hidden */ - protected create_neighbor(): MapReverseIterator; + protected create_neighbor(base: MapIterator): MapReverseIterator; /** * Get first, key element. */ @@ -5160,24 +5150,6 @@ declare namespace std.base { * @hidden */ private insert_or_assign_with_hint(hint, key, value); - /** - *

    Swap content.

    - * - *

    Exchanges the content of the container by the content of obj, which is another - * {@link UniqueMap map} of the same type. Sizes abd container type may differ.

    - * - *

    After the call to this member function, the elements in this container are those which were - * in obj before the call, and the elements of obj are those which were in this. All - * iterators, references and pointers remain valid for the swapped objects.

    - * - *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

    - * - * @param obj Another {@link UniqueMap map container} of the same type of elements as this (i.e., - * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link UniqueMap container}. - */ - swap(obj: UniqueMap): void; } } declare namespace std.base { @@ -5268,24 +5240,6 @@ declare namespace std.base { * @inheritdoc */ insert>>(first: InputIterator, last: InputIterator): void; - /** - *

    Swap content.

    - * - *

    Exchanges the content of the container by the content of obj, which is another - * {@link UniqueMap map} of the same type. Sizes abd container type may differ.

    - * - *

    After the call to this member function, the elements in this container are those which were - * in obj before the call, and the elements of obj are those which were in this. All - * iterators, references and pointers remain valid for the swapped objects.

    - * - *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

    - * - * @param obj Another {@link MultiMap map container} of the same type of elements as this (i.e., - * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link MultiMap container}. - */ - swap(obj: MultiMap): void; } } declare namespace std.HashMap { @@ -5348,13 +5302,27 @@ declare namespace std { */ private hash_buckets_; /** - * @hidden + * Default Constructor. */ - protected init(): void; + constructor(); /** - * @hidden + * Construct from elements. */ - protected construct_from_array(items: Array>): void; + constructor(items: Pair[]); + /** + * Contruct from tuples. + * + * @param array Tuples to be contained. + */ + constructor(array: [Key, T][]); + /** + * Copy Constructor. + */ + constructor(container: HashMap); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator>, end: Iterator>); /** * @inheritdoc */ @@ -5426,31 +5394,45 @@ declare namespace std { /** * @hidden */ - protected insert_by_pair(pair: Pair): any; + protected _Insert_by_pair(pair: Pair): any; /** * @hidden */ - protected insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; /** * @hidden */ - protected insert_by_range>>(first: InputIterator, last: InputIterator): void; + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(first: MapIterator, last: MapIterator): void; + protected _Handle_insert(first: MapIterator, last: MapIterator): void; /** * @inheritdoc */ - protected handle_erase(first: MapIterator, last: MapIterator): void; + protected _Handle_erase(first: MapIterator, last: MapIterator): void; + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link HashMap map} of the same type. Sizes abd container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link HashMap map container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link HashMap container}. + */ + swap(obj: HashMap): void; /** * @inheritdoc */ - swap(obj: base.UniqueMap): void; - /** - * @hidden - */ - private swap_hash_map(obj); + swap(obj: base.IContainer>): void; } } declare namespace std.HashMultiMap { @@ -5461,15 +5443,15 @@ declare namespace std { /** *

    Hashed, unordered Multimap.

    * - *

    {@link HashMap}s are associative containers that store elements formed by the combination of - * a key value and a mapped value, much like {@link HashMap} containers, but allowing + *

    {@link HashMultiMap}s are associative containers that store elements formed by the combination of + * a key value and a mapped value, much like {@link HashMultiMap} containers, but allowing * different elements to have equivalent keys.

    * - *

    In an {@link HashMap}, the key value is generally used to uniquely identify the + *

    In an {@link HashMultiMap}, the key value is generally used to uniquely identify the * element, while the mapped value is an object with the content associated to this key. * Types of key and mapped value may differ.

    * - *

    Internally, the elements in the {@link HashMap} are not sorted in any particular order with + *

    Internally, the elements in the {@link HashMultiMap} are not sorted in any particular order with * respect to either their key or mapped values, but organized into buckets depending on * their hash values to allow for fast access to individual elements directly by their key values * (with a constant average time complexity on average).

    @@ -5500,9 +5482,9 @@ declare namespace std { * * * @param Type of the key values. - * Each element in an {@link HashMap} is identified by a key value. + * Each element in an {@link HashMultiMap} is identified by a key value. * @param Type of the mapped value. - * Each element in an {@link HashMap} is used to store some data as its mapped value. + * Each element in an {@link HashMultiMap} is used to store some data as its mapped value. * * @reference http://www.cplusplus.com/reference/unordered_map/unordered_multimap * @author Jeongho Nam @@ -5513,13 +5495,27 @@ declare namespace std { */ private hash_buckets_; /** - * @hidden + * Default Constructor. */ - protected init(): void; + constructor(); /** - * @hidden + * Construct from elements. */ - protected construct_from_array(items: Array>): void; + constructor(items: Pair[]); + /** + * Contruct from tuples. + * + * @param array Tuples to be contained. + */ + constructor(array: [Key, T][]); + /** + * Copy Constructor. + */ + constructor(container: HashMultiMap); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator>, end: Iterator>); /** * @inheritdoc */ @@ -5595,31 +5591,45 @@ declare namespace std { /** * @hidden */ - protected insert_by_pair(pair: Pair): any; + protected _Insert_by_pair(pair: Pair): any; /** * @hidden */ - protected insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; /** * @hidden */ - protected insert_by_range>>(first: InputIterator, last: InputIterator): void; + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(first: MapIterator, last: MapIterator): void; + protected _Handle_insert(first: MapIterator, last: MapIterator): void; /** * @inheritdoc */ - protected handle_erase(first: MapIterator, last: MapIterator): void; + protected _Handle_erase(first: MapIterator, last: MapIterator): void; + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link HashMultiMap map} of the same type. Sizes abd container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link HashMultiMap map container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link HashMultiMap container}. + */ + swap(obj: HashMultiMap): void; /** * @inheritdoc */ - swap(obj: base.MultiMap): void; - /** - * @hidden - */ - private swap_hash_multimap(obj); + swap(obj: base.IContainer>): void; } } declare namespace std.base { @@ -5666,39 +5676,11 @@ declare namespace std.base { * by storing {@link ListIterator iterators} ({@link SetIterator} references {@link ListIterator}) who are * created from {@link data_ here}.

    */ - protected data_: List; + private data_; /** * Default Constructor. */ constructor(); - /** - * Construct from elements. - */ - constructor(items: Array); - /** - * Copy Constructor. - */ - constructor(container: IContainer); - /** - * Construct from range iterators. - */ - constructor(begin: Iterator, end: Iterator); - /** - * @hidden - */ - protected init(): void; - /** - * @hidden - */ - protected construct_from_array(items: Array): void; - /** - * @hidden - */ - protected construct_from_container(container: IContainer): void; - /** - * @hidden - */ - protected construct_from_range>(begin: InputIterator, end: InputIterator): void; /** * @inheritdoc */ @@ -5762,6 +5744,10 @@ declare namespace std.base { * @inheritdoc */ size(): number; + /** + * @hidden + */ + _Get_data(): List; /** * @inheritdoc */ @@ -5805,15 +5791,15 @@ declare namespace std.base { /** * @hidden */ - protected abstract insert_by_val(val: T): any; + protected abstract _Insert_by_val(val: T): any; /** * @hidden */ - protected abstract insert_by_hint(hint: SetIterator, val: T): SetIterator; + protected abstract _Insert_by_hint(hint: SetIterator, val: T): SetIterator; /** * @hidden */ - protected abstract insert_by_range>(begin: InputIterator, end: InputIterator): void; + protected abstract _Insert_by_range>(begin: InputIterator, end: InputIterator): void; /** *

    Erase an element.

    *

    Removes from the set container the elements whose value is key.

    @@ -5886,7 +5872,7 @@ declare namespace std.base { * [first, last), which contains all the elements between first and last, * including the element pointed by first but not the element pointed by last. */ - protected abstract handle_insert(first: SetIterator, last: SetIterator): void; + protected abstract _Handle_insert(first: SetIterator, last: SetIterator): void; /** *

    Abstract method handling deletions for indexing.

    * @@ -5907,7 +5893,11 @@ declare namespace std.base { * [first, last), which contains all the elements between first and last, * including the element pointed by first but not the element pointed by last. */ - protected abstract handle_erase(first: SetIterator, last: SetIterator): void; + protected abstract _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + * @hidden + */ + protected _Swap(obj: SetContainer): void; } } declare namespace std { @@ -5990,7 +5980,7 @@ declare namespace std { /** * @hidden */ - protected create_neighbor(): SetReverseIterator; + protected create_neighbor(base: SetIterator): SetReverseIterator; } } declare namespace std.base { @@ -6055,10 +6045,6 @@ declare namespace std.base { * @inheritdoc */ insert>(begin: InputIterator, end: InputIterator): void; - /** - * @inheritdoc - */ - swap(obj: MultiSet): void; } } declare namespace std.HashMultiSet { @@ -6070,7 +6056,7 @@ declare namespace std { *

    Hashed, unordered Multiset.

    * *

    {@link HashMultiSet HashMultiSets} are containers that store elements in no particular order, allowing fast - * retrieval of individual elements based on their value, much like {@link HashSet} containers, + * retrieval of individual elements based on their value, much like {@link HashMultiSet} containers, * but allowing different elements to have equivalent values.

    * *

    In an {@link HashMultiSet}, the value of an element is at the same time its key, used to @@ -6116,13 +6102,21 @@ declare namespace std { */ private hash_buckets_; /** - * @hidden + * Default Constructor. */ - protected init(): void; + constructor(); /** - * @hidden + * Construct from elements. */ - protected construct_from_array(items: Array): void; + constructor(items: T[]); + /** + * Copy Constructor. + */ + constructor(container: HashMultiSet); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator, end: Iterator); /** * @inheritdoc */ @@ -6198,31 +6192,45 @@ declare namespace std { /** * @hidden */ - protected insert_by_val(val: T): any; + protected _Insert_by_val(val: T): any; /** * @hidden */ - protected insert_by_hint(hint: SetIterator, val: T): SetIterator; + protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; /** * @hidden */ - protected insert_by_range>(first: InputIterator, last: InputIterator): void; + protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(first: SetIterator, last: SetIterator): void; + protected _Handle_insert(first: SetIterator, last: SetIterator): void; /** * @inheritdoc */ - protected handle_erase(first: SetIterator, last: SetIterator): void; + protected _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link HashMultiSet set} of the same type. Sizes abd container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link HashMultiSet set container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link HashMultiSet container}. + */ + swap(obj: HashMultiSet): void; /** * @inheritdoc */ - swap(obj: base.MultiSet): void; - /** - * @hidden - */ - private swap_tree_set(obj); + swap(obj: base.IContainer): void; } } declare namespace std.base { @@ -6344,10 +6352,6 @@ declare namespace std.base { * @inheritdoc */ insert>(begin: InputIterator, end: InputIterator): void; - /** - * @inheritdoc - */ - swap(obj: UniqueSet): void; } } declare namespace std.HashSet { @@ -6399,19 +6403,27 @@ declare namespace std { * @reference http://www.cplusplus.com/reference/unordered_set/unordered_set * @author Jeongho Nam */ - class HashSet extends base.UniqueSet { + class HashSet extends base.UniqueSet implements base.IHashSet { /** * @hidden */ private hash_buckets_; /** - * @hidden + * Default Constructor. */ - protected init(): void; + constructor(); /** - * @hidden + * Construct from elements. */ - protected construct_from_array(items: Array): void; + constructor(items: T[]); + /** + * Copy Constructor. + */ + constructor(container: HashSet); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator, end: Iterator); /** * @inheritdoc */ @@ -6483,31 +6495,45 @@ declare namespace std { /** * @hidden */ - protected insert_by_val(val: T): any; + protected _Insert_by_val(val: T): any; /** * @hidden */ - protected insert_by_hint(hint: SetIterator, val: T): SetIterator; + protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; /** * @hidden */ - protected insert_by_range>(first: InputIterator, last: InputIterator): void; + protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(first: SetIterator, last: SetIterator): void; + protected _Handle_insert(first: SetIterator, last: SetIterator): void; /** * @inheritdoc */ - protected handle_erase(first: SetIterator, last: SetIterator): void; + protected _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link HashSet set} of the same type. Sizes abd container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link HashSet set container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link HashSet container}. + */ + swap(obj: HashSet): void; /** * @inheritdoc */ - swap(obj: base.UniqueSet): void; - /** - * @hidden - */ - private swap_tree_set(obj); + swap(obj: base.IContainer): void; } } declare namespace std.List { @@ -6563,15 +6589,15 @@ declare namespace std { /** * @hidden */ - protected begin_: ListIterator; + private begin_; /** * @hidden */ - protected end_: ListIterator; + private end_; /** * @hidden */ - protected size_: number; + private size_; /** *

    Default Constructor.

    * @@ -6604,7 +6630,7 @@ declare namespace std { * @param container Another container object of the same type (with the same class template * arguments T), whose contents are either copied or acquired. */ - constructor(container: base.IContainer); + constructor(container: List); /** *

    Range Constructor.

    * @@ -6794,11 +6820,11 @@ declare namespace std { /** * @hidden */ - protected insert_by_repeating_val(position: ListIterator, size: number, val: T): ListIterator; + protected _Insert_by_repeating_val(position: ListIterator, size: number, val: T): ListIterator; /** * @hidden */ - protected insert_by_range>(position: ListIterator, begin: InputIterator, end: InputIterator): ListIterator; + protected _Insert_by_range>(position: ListIterator, begin: InputIterator, end: InputIterator): ListIterator; /** *

    Erase an element.

    * @@ -6868,7 +6894,7 @@ declare namespace std { /** * @hidden */ - protected erase_by_range(first: ListIterator, last: ListIterator): ListIterator; + protected _Erase_by_range(first: ListIterator, last: ListIterator): ListIterator; /** *

    Remove duplicate values.

    * @@ -7105,14 +7131,28 @@ declare namespace std { * @hidden */ private partition(first, last, compare); + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link List container} object with same type of elements. Sizes and container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were in obj + * before the call, and the elements of obj are those which were in this. All iterators, references and + * pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link List container} of the same type of elements (i.e., instantiated + * with the same template parameter, T) whose content is swapped with that of this + * {@link container List}. + */ + swap(obj: List): void; /** * @inheritdoc */ swap(obj: base.IContainer): void; - /** - * @hidden - */ - private swap_list(obj); } } declare namespace std { @@ -7142,14 +7182,6 @@ declare namespace std { * @param value Value to be stored in the node (iterator). */ constructor(source: List, prev: ListIterator, next: ListIterator, value: T); - /** - * @inheritdoc - */ - set_prev(it: ListIterator): void; - /** - * @inheritdoc - */ - set_next(next: ListIterator): void; private list(); /** * @inheritdoc @@ -7172,6 +7204,14 @@ declare namespace std { * @param val Value to set. */ value: T; + /** + * @hidden + */ + _Set_prev(it: ListIterator): void; + /** + * @hidden + */ + _Set_next(it: ListIterator): void; /** * @inheritdoc */ @@ -7204,7 +7244,10 @@ declare namespace std { /** * @hidden */ - protected create_neighbor(): ListReverseIterator; + protected create_neighbor(base: ListIterator): ListReverseIterator; + /** + * @inheritdoc + */ /** * Set value of the iterator is pointing to. * @@ -7213,6 +7256,192 @@ declare namespace std { value: T; } } +declare namespace std { + /** + *

    Priority queue.

    + * + *

    {@link PriorityQueue Priority queues} are a type of container adaptors, specifically designed such that its + * first element is always the greatest of the elements it contains, according to some strict weak ordering + * criterion.

    + * + *

    This context is similar to a heap, where elements can be inserted at any moment, and only the + * max heap element can be retrieved (the one at the top in the {@link PriorityQueue priority queue}).

    + * + *

    {@link PriorityQueue Priority queues} are implemented as container adaptors, which are classes that + * use an encapsulated object of a specific container class as its {@link container_ underlying container}, + * providing a specific set of member functions to access its elements. Elements are popped from the "back" + * of the specific container, which is known as the top of the {@link PriorityQueue Priority queue}.

    + * + *

    The {@link container_ underlying container} may be any of the standard container class templates or some + * other specifically designed container class. The container shall be accessible through + * {@link IArrayIterator random access iterators} and support the following operations:

    + * + *
      + *
    • empty()
    • + *
    • size()
    • + *
    • front()
    • + *
    • push_back()
    • + *
    • pop_back()
    • + *
    + * + *

    The standard container classes {@link Vector} and {@link Deque} fulfill these requirements. By default, if + * no container class is specified for a particular {@link PriorityQueue} class instantiation, the standard + * container {@link Vector} is used.

    + * + *

    Support of {@link IArrayIterator random access iterators} is required to keep a heap structure internally + * at all times. This is done automatically by the container adaptor by automatically calling the algorithm + * functions make_heap, push_heap and pop_heap when needed.

    + * + * @param Type of the elements. + * + * @reference http://www.cplusplus.com/reference/queue/priority_queue/ + * @author Jeongho Nam + */ + class PriorityQueue { + /** + *

    The underlying container for implementing the priority queue.

    + * + *

    Following standard definition from the C++ committee, the underlying container should be one of + * {@link Vector} or {@link Deque}, however, I've adopted {@link TreeMultiSet} instead of them. Of course, + * there are proper reasons for adapting the {@link TreeMultiSet} even violating standard advice.

    + * + *

    Underlying container of {@link PriorityQueue} must keep a condition; the highest (or lowest) + * element must be placed on the terminal node for fast retrieval and deletion. To keep the condition with + * {@link Vector} or {@link Deque}, lots of times will only be spent for re-arranging elements. It calls + * rearrangement functions like make_heap, push_heap and pop_head for rearrangement.

    + * + *

    However, the {@link TreeMultiSet} container always keeps arrangment automatically without additional + * operations and it even meets full criteria of {@link PriorityQueue}. Those are the reason why I've adopted + * {@link TreeMultiSet} as the underlying container of {@link PriorityQueue}.

    + */ + private container_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from compare. + * + * @param compare A binary predicate determines order of elements. + */ + constructor(compare: (left: T, right: T) => boolean); + /** + * Contruct from elements. + * + * @param array Elements to be contained. + */ + constructor(array: Array); + /** + * Contruct from elements with compare. + * + * @param array Elements to be contained. + * @param compare A binary predicate determines order of elements. + */ + constructor(array: Array, compare: (left: T, right: T) => boolean); + /** + * Copy Constructor. + */ + constructor(container: base.IContainer); + /** + * Copy Constructor with compare. + * + * @param container A container to be copied. + * @param compare A binary predicate determines order of elements. + */ + constructor(container: base.IContainer, compare: (left: T, right: T) => boolean); + /** + * Range Constructor. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + */ + constructor(begin: Iterator, end: Iterator); + /** + * Range Constructor with compare. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * @param compare A binary predicate determines order of elements. + */ + constructor(begin: Iterator, end: Iterator, compare: (left: T, right: T) => boolean); + /** + *

    Return size.

    + * + *

    Returns the number of elements in the {@link PriorityQueue}.

    + * + *

    This member function effectively calls member {@link IArray.size size} of the + * {@link container_ underlying container} object.

    + * + * @return The number of elements in the underlying + */ + size(): number; + /** + *

    Test whether container is empty.

    + * + *

    Returns whether the {@link PriorityQueue} is empty: i.e. whether its {@link size} is zero.

    + * + *

    This member function effectively calls member {@link IARray.empty empty} of the + * {@link container_ underlying container} object.

    + */ + empty(): boolean; + /** + *

    Access top element.

    + * + *

    Returns a constant reference to the top element in the {@link PriorityQueue}.

    + * + *

    The top element is the element that compares higher in the {@link PriorityQueue}, and the next that is + * removed from the container when {@link PriorityQueue.pop} is called.

    + * + *

    This member function effectively calls member {@link IArray.front front} of the + * {@link container_ underlying container} object.

    + * + * @return A reference to the top element in the {@link PriorityQueue}. + */ + top(): T; + /** + *

    Insert element.

    + * + *

    Inserts a new element in the {@link PriorityQueue}. The content of this new element is initialized to + * val. + * + *

    This member function effectively calls the member function {@link IArray.push_back push_back} of the + * {@link container_ underlying container} object, and then reorders it to its location in the heap by calling + * the push_heap algorithm on the range that includes all the elements of the

    + * + * @param val Value to which the inserted element is initialized. + */ + push(val: T): void; + /** + *

    Remove top element.

    + * + *

    Removes the element on top of the {@link PriorityQueue}, effectively reducing its {@link size} by one. + * The element removed is the one with the highest (or lowest) value.

    + * + *

    The value of this element can be retrieved before being popped by calling member + * {@link PriorityQueue.top}.

    + * + *

    This member function effectively calls the pop_heap algorithm to keep the heap property of + * {@link PriorityQueue PriorityQueues} and then calls the member function {@link IArray.pop_back pop_back} of + * the {@link container_ underlying container} object to remove the element.

    + */ + pop(): void; + /** + *

    Swap contents.

    + * + *

    Exchanges the contents of the container adaptor by those of obj, swapping both the + * {@link container_ underlying container} value and their comparison function using the corresponding + * {@link std.swap swap} non-member functions (unqualified).

    + * + *

    This member function has a noexcept specifier that matches the combined noexcept of the + * {@link IArray.swap swap} operations on the {@link container_ underlying container} and the comparison + * functions.

    + * + * @param obj {@link PriorityQueue} container adaptor of the same type (i.e., instantiated with the same + * template parameters, T). Sizes may differ. + */ + swap(obj: PriorityQueue): void; + } +} declare namespace std { /** *

    FIFO queue.

    @@ -7349,204 +7578,6 @@ declare namespace std { swap(obj: Queue): void; } } -declare namespace std { - /** - *

    Priority queue.

    - * - *

    {@link PriorityQueue Priority queues} are a type of container adaptors, specifically designed such that its - * first element is always the greatest of the elements it contains, according to some strict weak ordering - * criterion.

    - * - *

    This context is similar to a heap, where elements can be inserted at any moment, and only the - * max heap element can be retrieved (the one at the top in the {@link PriorityQueue priority queue}).

    - * - *

    {@link PriorityQueue Priority queues} are implemented as container adaptors, which are classes that - * use an encapsulated object of a specific container class as its {@link container_ underlying container}, - * providing a specific set of member functions to access its elements. Elements are popped from the "back" - * of the specific container, which is known as the top of the {@link PriorityQueue Priority queue}.

    - * - *

    The {@link container_ underlying container} may be any of the standard container class templates or some - * other specifically designed container class. The container shall be accessible through - * {@link IArrayIterator random access iterators} and support the following operations:

    - * - *
      - *
    • empty()
    • - *
    • size()
    • - *
    • front()
    • - *
    • push_back()
    • - *
    • pop_back()
    • - *
    - * - *

    The standard container classes {@link Vector} and {@link Deque} fulfill these requirements. By default, if - * no container class is specified for a particular {@link PriorityQueue} class instantiation, the standard - * container {@link Vector} is used.

    - * - *

    Support of {@link IArrayIterator random access iterators} is required to keep a heap structure internally - * at all times. This is done automatically by the container adaptor by automatically calling the algorithm - * functions make_heap, push_heap and pop_heap when needed.

    - * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/queue/priority_queue/ - * @author Jeongho Nam - */ - class PriorityQueue { - /** - *

    The underlying container for implementing the priority queue.

    - * - *

    Following standard definition from the C++ committee, the underlying container should be one of - * {@link Vector} or {@link Deque}, however, I've adopted {@link TreeMultiSet} instead of them. Of course, - * there are proper reasons for adapting the {@link TreeMultiSet} even violating standard advice.

    - * - *

    Underlying container of {@link PriorityQueue} must keep a condition; the highest (or lowest) - * element must be placed on the terminal node for fast retrieval and deletion. To keep the condition with - * {@link Vector} or {@link Deque}, lots of times will only be spent for re-arranging elements. It calls - * rearrangement functions like make_heap, push_heap and pop_head for rearrangement.

    - * - *

    However, the {@link TreeMultiSet} container always keeps arrangment automatically without additional - * operations and it even meets full criteria of {@link PriorityQueue}. Those are the reason why I've adopted - * {@link TreeMultiSet} as the underlying container of {@link PriorityQueue}.

    - */ - private container_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from compare. - * - * @param compare A binary predicate determines order of elements. - */ - constructor(compare: (left: T, right: T) => boolean); - /** - * Contruct from elements. - * - * @param array Elements to be contained. - */ - constructor(array: Array); - /** - * Contruct from elements with compare. - * - * @param array Elements to be contained. - * @param compare A binary predicate determines order of elements. - */ - constructor(array: Array, compare: (left: T, right: T) => boolean); - /** - * Copy Constructor. - */ - constructor(container: base.Container); - /** - * Copy Constructor with compare. - * - * @param container A container to be copied. - * @param compare A binary predicate determines order of elements. - */ - constructor(container: base.Container, compare: (left: T, right: T) => boolean); - /** - * Range Constructor. - * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - */ - constructor(begin: Iterator, end: Iterator); - /** - * Range Constructor with compare. - * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * @param compare A binary predicate determines order of elements. - */ - constructor(begin: Iterator, end: Iterator, compare: (left: T, right: T) => boolean); - /** - * @hidden - */ - protected construct_from_array(items: Array): void; - /** - * @hidden - */ - protected construct_from_container(container: base.IContainer): void; - /** - * @hidden - */ - protected construct_from_range(begin: Iterator, end: Iterator): void; - /** - *

    Return size.

    - * - *

    Returns the number of elements in the {@link PriorityQueue}.

    - * - *

    This member function effectively calls member {@link IArray.size size} of the - * {@link container_ underlying container} object.

    - * - * @return The number of elements in the underlying - */ - size(): number; - /** - *

    Test whether container is empty.

    - * - *

    Returns whether the {@link PriorityQueue} is empty: i.e. whether its {@link size} is zero.

    - * - *

    This member function effectively calls member {@link IARray.empty empty} of the - * {@link container_ underlying container} object.

    - */ - empty(): boolean; - /** - *

    Access top element.

    - * - *

    Returns a constant reference to the top element in the {@link PriorityQueue}.

    - * - *

    The top element is the element that compares higher in the {@link PriorityQueue}, and the next that is - * removed from the container when {@link PriorityQueue.pop} is called.

    - * - *

    This member function effectively calls member {@link IArray.front front} of the - * {@link container_ underlying container} object.

    - * - * @return A reference to the top element in the {@link PriorityQueue}. - */ - top(): T; - /** - *

    Insert element.

    - * - *

    Inserts a new element in the {@link PriorityQueue}. The content of this new element is initialized to - * val. - * - *

    This member function effectively calls the member function {@link IArray.push_back push_back} of the - * {@link container_ underlying container} object, and then reorders it to its location in the heap by calling - * the push_heap algorithm on the range that includes all the elements of the

    - * - * @param val Value to which the inserted element is initialized. - */ - push(val: T): void; - /** - *

    Remove top element.

    - * - *

    Removes the element on top of the {@link PriorityQueue}, effectively reducing its {@link size} by one. - * The element removed is the one with the highest (or lowest) value.

    - * - *

    The value of this element can be retrieved before being popped by calling member - * {@link PriorityQueue.top}.

    - * - *

    This member function effectively calls the pop_heap algorithm to keep the heap property of - * {@link PriorityQueue PriorityQueues} and then calls the member function {@link IArray.pop_back pop_back} of - * the {@link container_ underlying container} object to remove the element.

    - */ - pop(): void; - /** - *

    Swap contents.

    - * - *

    Exchanges the contents of the container adaptor by those of obj, swapping both the - * {@link container_ underlying container} value and their comparison function using the corresponding - * {@link std.swap swap} non-member functions (unqualified).

    - * - *

    This member function has a noexcept specifier that matches the combined noexcept of the - * {@link IArray.swap swap} operations on the {@link container_ underlying container} and the comparison - * functions.

    - * - * @param obj {@link PriorityQueue} container adaptor of the same type (i.e., instantiated with the same - * template parameters, T). Sizes may differ. - */ - swap(obj: PriorityQueue): void; - } -} declare namespace std { /** *

    LIFO stack.

    @@ -8142,14 +8173,14 @@ declare namespace std { * * @param container Another map to copy. */ - constructor(container: base.MapContainer); + constructor(container: TreeMap); /** * Copy Constructor. * * @param container Another map to copy. * @param compare A binary predicate determines order of elements. */ - constructor(container: base.MapContainer, compare: (x: Key, y: Key) => boolean); + constructor(container: TreeMap, compare: (x: Key, y: Key) => boolean); /** * Range Constructor. * @@ -8196,31 +8227,45 @@ declare namespace std { /** * @hidden */ - protected insert_by_pair(pair: Pair): any; + protected _Insert_by_pair(pair: Pair): any; /** * @hidden */ - protected insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; /** * @hidden */ - protected insert_by_range>>(first: InputIterator, last: InputIterator): void; + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(first: MapIterator, last: MapIterator): void; + protected _Handle_insert(first: MapIterator, last: MapIterator): void; /** * @inheritdoc */ - protected handle_erase(first: MapIterator, last: MapIterator): void; + protected _Handle_erase(first: MapIterator, last: MapIterator): void; + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link TreeMap map} of the same type. Sizes abd container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link TreeMap map container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link TreeMap container}. + */ + swap(obj: TreeMap): void; /** * @inheritdoc */ - swap(obj: base.UniqueMap): void; - /** - * @hidden - */ - private swap_tree_map(obj); + swap(obj: base.IContainer>): void; } } declare namespace std.TreeMultiMap { @@ -8330,14 +8375,14 @@ declare namespace std { * * @param container Another map to copy. */ - constructor(container: base.MapContainer); + constructor(container: TreeMultiMap); /** * Copy Constructor. * * @param container Another map to copy. * @param compare A binary predicate determines order of elements. */ - constructor(container: base.MapContainer, compare: (x: Key, y: Key) => boolean); + constructor(container: TreeMultiMap, compare: (x: Key, y: Key) => boolean); /** * Range Constructor. * @@ -8388,31 +8433,45 @@ declare namespace std { /** * @hidden */ - protected insert_by_pair(pair: Pair): any; + protected _Insert_by_pair(pair: Pair): any; /** * @hidden */ - protected insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; /** * @hidden */ - protected insert_by_range>>(first: InputIterator, last: InputIterator): void; + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(first: MapIterator, last: MapIterator): void; + protected _Handle_insert(first: MapIterator, last: MapIterator): void; /** * @inheritdoc */ - protected handle_erase(first: MapIterator, last: MapIterator): void; + protected _Handle_erase(first: MapIterator, last: MapIterator): void; + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link TreeMapMulti map} of the same type. Sizes abd container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link TreeMapMulti map container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link TreeMapMulti container}. + */ + swap(obj: TreeMultiMap): void; /** * @inheritdoc */ - swap(obj: base.MultiMap): void; - /** - * @hidden - */ - private swap_tree_multimap(obj); + swap(obj: base.IContainer>): void; } } declare namespace std.TreeMultiSet { @@ -8501,14 +8560,14 @@ declare namespace std { /** * Copy Constructor. */ - constructor(container: base.Container); + constructor(container: TreeMultiSet); /** * Copy Constructor with compare. * * @param container A container to be copied. * @param compare A binary predicate determines order of elements. */ - constructor(container: base.Container, compare: (x: T, y: T) => boolean); + constructor(container: TreeMultiSet, compare: (x: T, y: T) => boolean); /** * Range Constructor. * @@ -8559,31 +8618,49 @@ declare namespace std { /** * @hidden */ - protected insert_by_val(val: T): any; + _Get_tree(): base.AtomicTree; /** * @hidden */ - protected insert_by_hint(hint: SetIterator, val: T): SetIterator; + protected _Insert_by_val(val: T): any; /** * @hidden */ - protected insert_by_range>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - protected handle_insert(first: SetIterator, last: SetIterator): void; - /** - * @inheritdoc - */ - protected handle_erase(first: SetIterator, last: SetIterator): void; - /** - * @inheritdoc - */ - swap(obj: base.MultiSet): void; + protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; /** * @hidden */ - private swap_tree_set(obj); + protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; + /** + * @inheritdoc + */ + protected _Handle_insert(first: SetIterator, last: SetIterator): void; + /** + * @inheritdoc + */ + protected _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link TreeMultiSet set} of the same type. Sizes abd container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link TreeMultiSet set container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link TreeMultiSet container}. + */ + swap(obj: TreeMultiSet): void; + /** + * @inheritdoc + */ + swap(obj: base.IContainer): void; } } declare namespace std.TreeSet { @@ -8671,14 +8748,14 @@ declare namespace std { /** * Copy Constructor. */ - constructor(container: base.IContainer); + constructor(container: TreeMultiSet); /** * Copy Constructor with compare. * * @param container A container to be copied. * @param compare A binary predicate determines order of elements. */ - constructor(container: base.IContainer, compare: (x: T, y: T) => boolean); + constructor(container: TreeMultiSet, compare: (x: T, y: T) => boolean); /** * Range Constructor. * @@ -8687,7 +8764,7 @@ declare namespace std { */ constructor(begin: Iterator, end: Iterator); /** - * Range Constructor with compare. + * Construct from range and compare. * * @param begin Input interator of the initial position in a sequence. * @param end Input interator of the final position in a sequence. @@ -8725,28 +8802,42 @@ declare namespace std { /** * @hidden */ - protected insert_by_val(val: T): any; - protected insert_by_hint(hint: SetIterator, val: T): SetIterator; + protected _Insert_by_val(val: T): any; + protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; /** * @hidden */ - protected insert_by_range>(first: InputIterator, last: InputIterator): void; + protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(first: SetIterator, last: SetIterator): void; + protected _Handle_insert(first: SetIterator, last: SetIterator): void; /** * @inheritdoc */ - protected handle_erase(first: SetIterator, last: SetIterator): void; + protected _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link TreeSet set} of the same type. Sizes abd container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link TreeSet set container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link TreeSet container}. + */ + swap(obj: TreeSet): void; /** * @inheritdoc */ - swap(obj: base.UniqueSet): void; - /** - * @hidden - */ - private swap_tree_set(obj); + swap(obj: base.IContainer): void; } } declare namespace std { @@ -8880,7 +8971,7 @@ declare namespace std { * @reference http://www.cplusplus.com/reference/vector/vector * @author Jeongho Nam */ - class Vector extends Array implements base.IArrayContainer { + class Vector extends Array implements base.IContainer, base.IArrayContainer { /** *

    Default Constructor.

    * @@ -8917,7 +9008,7 @@ declare namespace std { * @param container Another container object of the same type (with the same class template * arguments T), whose contents are either copied or acquired. */ - constructor(container: base.IContainer); + constructor(container: Vector); /** *

    Range Constructor.

    * @@ -9137,11 +9228,11 @@ declare namespace std { /** * @hidden */ - protected insert_by_repeating_val(position: VectorIterator, n: number, val: T): VectorIterator; + protected _Insert_by_repeating_val(position: VectorIterator, n: number, val: T): VectorIterator; /** * @hidden */ - protected insert_by_range>(position: VectorIterator, first: InputIterator, last: InputIterator): VectorIterator; + protected _Insert_by_range>(position: VectorIterator, first: InputIterator, last: InputIterator): VectorIterator; /** * @inheritdoc */ @@ -9227,7 +9318,25 @@ declare namespace std { /** * @hidden */ - protected erase_by_range(first: VectorIterator, last: VectorIterator): VectorIterator; + protected _Erase_by_range(first: VectorIterator, last: VectorIterator): VectorIterator; + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link Vector container} object with same type of elements. Sizes and container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were in obj + * before the call, and the elements of obj are those which were in this. All iterators, references and + * pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link Vector container} of the same type of elements (i.e., instantiated + * with the same template parameter, T) whose content is swapped with that of this + * {@link container Vector}. + */ + obj(obj: Vector): void; /** * @inheritdoc */ @@ -9335,7 +9444,10 @@ declare namespace std { /** * @hidden */ - protected create_neighbor(): VectorReverseIterator; + protected create_neighbor(base: VectorIterator): VectorReverseIterator; + /** + * @inheritdoc + */ /** * Set value of the iterator is pointing to. * @@ -11328,6 +11440,7 @@ declare namespace std.base { * Default Constructor. */ constructor(map: TreeMap | TreeMultiMap, compare?: (x: Key, y: Key) => boolean); + _Set_compare(val: (x: Key, y: Key) => boolean): void; find(key: Key): XTreeNode>; find(it: MapIterator): XTreeNode>; /** @@ -11628,6 +11741,7 @@ declare namespace std.base { * Default Constructor. */ constructor(set: TreeSet | TreeMultiSet, compare?: (x: T, y: T) => boolean); + _Set_compare(val: (x: T, y: T) => boolean): void; find(val: T): XTreeNode>; find(it: SetIterator): XTreeNode>; /** diff --git a/validator/validator-tests.ts b/validator/validator-tests.ts index 8afabc2099..96d5bc761a 100644 --- a/validator/validator-tests.ts +++ b/validator/validator-tests.ts @@ -4,9 +4,9 @@ import * as validator from 'validator'; let any: any; -/************** - * Validators * - **************/ +// ************** +// * Validators * +// ************** { let result: boolean; @@ -16,7 +16,7 @@ let any: any; result = validator.equals('sample', 'sample'); result = validator.isAfter('sample'); - result = validator.isAfter('sample', new Date()); + result = validator.isAfter('sample', new Date().toString()); result = validator.isAlpha('sample'); @@ -27,7 +27,7 @@ let any: any; result = validator.isBase64('sample'); result = validator.isBefore('sample'); - result = validator.isBefore('sample', new Date()); + result = validator.isBefore('sample', new Date().toString()); result = validator.isBoolean('sample'); @@ -42,6 +42,8 @@ let any: any; result = validator.isCurrency('sample'); result = validator.isCurrency('sample', isCurrencyOptions); + result = validator.isDataURI('sample'); + result = validator.isDate('sample'); result = validator.isDecimal('sample'); @@ -95,6 +97,8 @@ let any: any; result = validator.isMACAddress('sample'); + result = validator.isMD5('sample'); + result = validator.isMobilePhone('sample', 'en-US'); result = validator.isMongoId('sample'); @@ -113,6 +117,7 @@ let any: any; result = validator.isUUID('sample'); result = validator.isUUID('sample', 5); + result = validator.isUUID('sample', 'all'); result = validator.isUppercase('sample'); @@ -125,9 +130,9 @@ let any: any; result = validator.matches('foobar', 'foo', 'i'); } -/************** - * Sanitizers * - **************/ +// ************** +// * Sanitizers * +// ************** { let result: string; @@ -136,6 +141,8 @@ let any: any; result = validator.escape('sample'); + result = validator.unescape('sample'); + result = validator.ltrim('sample'); result = validator.ltrim('sample', ' '); @@ -175,16 +182,14 @@ let any: any; { let result: string; - result = validator.toString(any); - result = validator.trim('sample'); result = validator.trim('sample', ' '); result = validator.whitelist('sample', 'abc'); } -/************** - * Extensions * - **************/ +// ************** +// * Extensions * +// ************** validator.extend<(str: string, options: {}) => boolean>('isTest', (str: any, options: {}) => !str); diff --git a/validator/validator.d.ts b/validator/validator.d.ts index 0edb5e885b..1ec4711828 100644 --- a/validator/validator.d.ts +++ b/validator/validator.d.ts @@ -1,14 +1,14 @@ -// Type definitions for validator.js v4.5.1 +// Type definitions for validator.js v5.7.0 // Project: https://github.com/chriso/validator.js -// Definitions by: tgfjt , Ilya Mochalov +// Definitions by: tgfjt , Ilya Mochalov , Ayman Nedjmeddine , Louy Alakkad // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace ValidatorJS { interface ValidatorStatic { - /************** - * Validators * - **************/ + // ************** + // * Validators * + // ************** // check if the string contains the seed. contains(str: string, elem: any): boolean; @@ -17,7 +17,7 @@ declare namespace ValidatorJS { equals(str: string, comparison: any): boolean; // check if the string is a date that's after the specified date (defaults to now). - isAfter(str: string, date?: Date): boolean; + isAfter(str: string, date?: string): boolean; // check if the string contains only letters (a-zA-Z). isAlpha(str: string): boolean; @@ -32,7 +32,7 @@ declare namespace ValidatorJS { isBase64(str: string): boolean; // check if the string is a date that's before the specified date. - isBefore(str: string, date?: Date): boolean; + isBefore(str: string, date?: string): boolean; // check if a string is a boolean. isBoolean(str: string): boolean; @@ -47,6 +47,9 @@ declare namespace ValidatorJS { // check if the string is a valid currency amount. isCurrency(str: string, options?: IsCurrencyOptions): boolean; + // check if the string is a data uri format (https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs) + isDataURI(str: string): boolean; + // check if the string is a date. isDate(str: string): boolean; @@ -110,8 +113,14 @@ declare namespace ValidatorJS { // check if the string is a MAC address. isMACAddress(str: string): boolean; - // check if the string is a mobile phone number, (locale is one of ['zh-CN', 'zh-TW', 'en-ZA', 'en-AU', 'en-HK', - // 'pt-PT', 'fr-FR', 'el-GR', 'en-GB', 'en-US', 'en-ZM', 'ru-RU', 'nb-NO', 'nn-NO', 'vi-VN', 'en-NZ', 'en-IN']). + // check if the string is a MD5 hash. + isMD5(str: string): boolean; + + // check if the string is a mobile phone number, (locale is one of + // ['ar-DZ', 'ar-SA', 'ar-SY', 'cs-CZ', 'de-DE', 'da-DK', 'el-GR', 'en-AU', 'en-GB', 'en-HK', + // 'en-IN', 'en-NZ', 'en-US', 'en-CA', 'en-ZA', 'en-ZM', 'es-ES', 'fi-FI', 'fr-FR', 'hu-HU', + // 'it-IT', 'ja-JP', 'ms-MY', 'nb-NO', 'nn-NO', 'pl-PL', 'pt-PT', 'ru-RU', 'sr-RS', 'tr-TR', + // 'vi-VN', 'zh-CN', 'zh-TW']). isMobilePhone(str: string, locale: string): boolean; // check if the string is a valid hex-encoded representation of a MongoDB ObjectId @@ -133,8 +142,8 @@ declare namespace ValidatorJS { // check if the string is an URL. isURL(str: string, options?: IsURLOptions): boolean; - // check if the string is a UUID (version 3, 4 or 5). - isUUID(str: string, version?: number): boolean; + // check if the string is a UUID. Must be one of ['3', '4', '5', 'all'], default is all. + isUUID(str: string, version?: string|number): boolean; // check if the string is uppercase. isUppercase(str: string): boolean; @@ -146,11 +155,11 @@ declare namespace ValidatorJS { isWhitelisted(str: string, chars: string|string[]): boolean; // check if string matches the pattern. - matches(str: string, pattern: any, modifiers?: string): boolean; + matches(str: string, pattern: RegExp|string, modifiers?: string): boolean; - /************** - * Sanitizers * - **************/ + // ************** + // * Sanitizers * + // ************** // remove characters that appear in the blacklist. The characters are used in a RegExp and so you will need // to escape some chars, e.g. blacklist(input, '\\[\\]'). @@ -159,6 +168,9 @@ declare namespace ValidatorJS { // replace <, >, &, ', " and / with HTML entities. escape(input: string): string; + // replaces HTML encoded entities with <, >, &, ', " and /. + unescape(input: string): string; + // trim characters from the left-side of the input. ltrim(input: any, chars?: string): string; @@ -185,9 +197,6 @@ declare namespace ValidatorJS { // convert the input to an integer, or NaN if the input is not an integer. toInt(input: any, radix?: number): number; // number or NaN - // convert the input to a string. - toString(input: any): string; - // trim characters (whitespace by default) from both sides of the input. trim(input: any, chars?: string): string; @@ -195,9 +204,9 @@ declare namespace ValidatorJS { // need to escape some chars, e.g. whitelist(input, '\\[\\]'). whitelist(input: string, chars: string): string; - /************** - * Extensions * - **************/ + // ************** + // * Extensions * + // ************** // add your own validators. // Note: that the first argument will be automatically coerced to a string. @@ -263,10 +272,11 @@ declare namespace ValidatorJS { protocols?: string[]; require_tld?: boolean; require_protocol?: boolean; + require_host: boolean; require_valid_protocol?: boolean; allow_underscores?: boolean; - host_whitelist?: boolean; - host_blacklist?: boolean; + host_whitelist?: (string|RegExp)[]; + host_blacklist?: (string|RegExp)[]; allow_trailing_dot?: boolean; allow_protocol_relative_urls?: boolean; } @@ -280,8 +290,7 @@ declare namespace ValidatorJS { } declare module "validator" { - let validator: ValidatorJS.ValidatorStatic; - namespace validator {} + const validator: ValidatorJS.ValidatorStatic; export = validator; } diff --git a/videojs/videojs.d.ts b/videojs/videojs.d.ts index 7fb5005092..3ac6007daf 100644 --- a/videojs/videojs.d.ts +++ b/videojs/videojs.d.ts @@ -44,9 +44,11 @@ interface VideoJSPlayer { size(width: number, height: number): VideoJSPlayer; requestFullScreen(): VideoJSPlayer; cancelFullScreen(): VideoJSPlayer; - ready(callback: () => void ): void; - on(eventName: string, callback: () => void ): void; + ready(callback: () => void ): VideoJSPlayer; + on(eventName: string, callback: (eventObject: Event) => void ): void; off(eventName: string, callback: () => void ): void; + off(eventName: string): void; + off(): void; dispose(): void; addRemoteTextTrack(options : {}) : HTMLTrackElement; removeRemoteTextTrack(track : HTMLTrackElement) : void; diff --git a/webix/webix.d.ts b/webix/webix.d.ts index 9c516654a1..7931ef83d9 100644 --- a/webix/webix.d.ts +++ b/webix/webix.d.ts @@ -9,6 +9,7 @@ type WebixTemplate = (...args: any[])=>string; type WebixCallback = (...args: any[])=>any; interface PromisedData { then(handler:(data:any)=>any):PromisedData; + fail(handler:(error:any)=>any):PromisedData; } function ajax():webix._ajax; @@ -8620,4 +8621,4 @@ interface window extends webix.ui.baseview{ }} -declare function $$(id: string | Event | HTMLElement): webix.ui.baseview; \ No newline at end of file +declare function $$(id: string | Event | HTMLElement): webix.ui.baseview; diff --git a/ws/ws-tests.ts b/ws/ws-tests.ts index a8afa8cb99..3c85d678cb 100644 --- a/ws/ws-tests.ts +++ b/ws/ws-tests.ts @@ -2,6 +2,7 @@ import * as WebSocket from 'ws'; import * as http from'http'; +import * as https from'https'; var WebSocketServer = WebSocket.Server; @@ -54,6 +55,12 @@ var WebSocketServer = WebSocket.Server; }); } +{ + new WebSocket.Server({ server: https.createServer({}) }); + new WebSocket.Server({ server: http.createServer() }); +} + + { const verifyClient = function( info: { @@ -73,4 +80,4 @@ var WebSocketServer = WebSocket.Server; wsv.on('connection', function connection(ws) { console.log(ws.protocol) }) -} \ No newline at end of file +} diff --git a/ws/ws.d.ts b/ws/ws.d.ts index 2b16bd52ea..b7ce3bd829 100644 --- a/ws/ws.d.ts +++ b/ws/ws.d.ts @@ -8,6 +8,7 @@ declare module "ws" { import * as events from 'events'; import * as http from 'http'; + import * as https from 'https'; import * as net from 'net'; class WebSocket extends events.EventEmitter { @@ -99,7 +100,7 @@ declare module "ws" { export interface IServerOptions { host?: string; port?: number; - server?: http.Server; + server?: http.Server | https.Server; verifyClient?: VerifyClientCallbackAsync | VerifyClientCallbackSync; handleProtocols?: any; path?: string;